Compare commits
17
Commits
78c5008d64
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fc2788b05 | ||
|
|
2ef65ba399 | ||
|
|
b4c42ff131 | ||
|
|
7618702148 | ||
|
|
98acb0b40a | ||
|
|
c5f8c1edd6 | ||
|
|
aa13c8cc47 | ||
|
|
2449f20a72 | ||
|
|
04ddae51fe | ||
|
|
14b84fe28d | ||
|
|
7d5a19344b | ||
|
|
ddf7ed0a17 | ||
|
|
02a9e6f848 | ||
|
|
d01fd5e94d | ||
|
|
ccf967984f | ||
|
|
786a63a138 | ||
|
|
f7bc1e31f4 |
@@ -0,0 +1,50 @@
|
|||||||
|
"""
|
||||||
|
DAG harian: DWH SPOTA (API legacy SPOTA) -> PostgreSQL DWH.
|
||||||
|
|
||||||
|
load_raw_spota ──> build_staging_spota ──> build_mart_spota
|
||||||
|
|
||||||
|
raw : topik/draft TA, KK, jadwal ujian, angkatan mahasiswa, nama dosen dari API SPOTA
|
||||||
|
(tanpa nama/email/HP/foto mahasiswa) + raw.spota_riwayat_pembimbing, satu-satunya tabel
|
||||||
|
kumulatif: hari pertama pembimbing 1/2 terlihat terisi (API tidak menyimpan tanggal ini)
|
||||||
|
staging : NIM/NIP dinormalisasi, kode semester -> periode, KK per topik, jadwal dirapikan
|
||||||
|
mart : spota_topik (keputusan, KK, pembimbing, masa tunggu, tahap ujian eDOXID/SPOTA),
|
||||||
|
spota_mhs_judul (mahasiswa aktif belum lulus + status judul) (+ etl_log)
|
||||||
|
-> dibaca dashboard PHP (halaman Executive "Monitoring SPOTA") lewat user dashboard_ro
|
||||||
|
|
||||||
|
Butuh mart.dim_mahasiswa, mart.dim_dosen, mart.fact_ujian_ta dari dwh_tugas_akhir_daily, jadi
|
||||||
|
dijadwalkan sesudahnya. Lihat scripts/dwh_spota_etl.py dan scripts/dwh_spota_sql.py.
|
||||||
|
|
||||||
|
Environment yang wajib di-set di Coolify (service airflow-scheduler):
|
||||||
|
DWH_HOST, DWH_PASSWORD -> sama dengan dwh_tugas_akhir_daily (user etl_writer)
|
||||||
|
SPOTA_API_SECRET -> secret API legacy SPOTA
|
||||||
|
Opsional: SPOTA_API_URL (default https://spota.untan.ac.id/steven/API).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from airflow import DAG
|
||||||
|
from airflow.operators.python import PythonOperator
|
||||||
|
|
||||||
|
from scripts.dwh_spota_etl import run_build_mart_spota, run_build_staging_spota, run_load_raw_spota
|
||||||
|
|
||||||
|
with DAG(
|
||||||
|
dag_id="dwh_spota_daily",
|
||||||
|
description="ETL draft TA & penetapan pembimbing (API SPOTA) ke DWH PostgreSQL",
|
||||||
|
start_date=datetime(2026, 10, 1),
|
||||||
|
# 20:00 UTC = 03:00 WIB, setelah dwh_tugas_akhir_daily (02:00) & dwh_tracer_daily (02:30).
|
||||||
|
# Harian karena ketelitian masa tunggu pembimbing = 1 hari.
|
||||||
|
schedule_interval="0 20 * * *",
|
||||||
|
catchup=False,
|
||||||
|
max_active_runs=1,
|
||||||
|
default_args={
|
||||||
|
"owner": "informatika",
|
||||||
|
"retries": 2,
|
||||||
|
"retry_delay": timedelta(minutes=10),
|
||||||
|
},
|
||||||
|
tags=["dwh", "spota", "tugas-akhir", "dashboard"],
|
||||||
|
) as dag:
|
||||||
|
load_spota = PythonOperator(task_id="load_raw_spota", python_callable=run_load_raw_spota)
|
||||||
|
build_staging = PythonOperator(task_id="build_staging_spota", python_callable=run_build_staging_spota)
|
||||||
|
build_mart = PythonOperator(task_id="build_mart_spota", python_callable=run_build_mart_spota)
|
||||||
|
|
||||||
|
load_spota >> build_staging >> build_mart
|
||||||
@@ -38,7 +38,7 @@ with DAG(
|
|||||||
description="ETL tugas akhir eDOXID + data mahasiswa/dosen ke DWH PostgreSQL",
|
description="ETL tugas akhir eDOXID + data mahasiswa/dosen ke DWH PostgreSQL",
|
||||||
start_date=datetime(2026, 10, 1),
|
start_date=datetime(2026, 10, 1),
|
||||||
# 19:00 UTC = 02:00 WIB, di luar jam sibuk eDOXID
|
# 19:00 UTC = 02:00 WIB, di luar jam sibuk eDOXID
|
||||||
schedule_interval="0 19 * * *",
|
schedule_interval="0 * * * *",
|
||||||
catchup=False,
|
catchup=False,
|
||||||
max_active_runs=1,
|
max_active_runs=1,
|
||||||
default_args={
|
default_args={
|
||||||
|
|||||||
+10
-5
@@ -1,6 +1,8 @@
|
|||||||
version: '3.8'
|
version: '3.8'
|
||||||
services:
|
services:
|
||||||
postgres:
|
# Database metadata Airflow. Sengaja tidak dinamai "postgres": di jaringan Coolify nama itu bisa
|
||||||
|
# ter-resolve ke container Postgres lain (mis. DWH) sehingga login user airflow gagal.
|
||||||
|
airflow-metadb:
|
||||||
image: postgres:13
|
image: postgres:13
|
||||||
environment:
|
environment:
|
||||||
- POSTGRES_USER=airflow
|
- POSTGRES_USER=airflow
|
||||||
@@ -13,10 +15,10 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
user: "50000:0"
|
user: "50000:0"
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- airflow-metadb
|
||||||
environment:
|
environment:
|
||||||
- PYTHONPATH=/opt/airflow
|
- PYTHONPATH=/opt/airflow
|
||||||
- AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres/airflow
|
- AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@airflow-metadb/airflow
|
||||||
- AIRFLOW__CORE__EXECUTOR=LocalExecutor
|
- AIRFLOW__CORE__EXECUTOR=LocalExecutor
|
||||||
- AIRFLOW__CORE__LOAD_EXAMPLES=False
|
- AIRFLOW__CORE__LOAD_EXAMPLES=False
|
||||||
volumes:
|
volumes:
|
||||||
@@ -30,10 +32,10 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
user: "50000:0"
|
user: "50000:0"
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- airflow-metadb
|
||||||
environment:
|
environment:
|
||||||
- PYTHONPATH=/opt/airflow
|
- PYTHONPATH=/opt/airflow
|
||||||
- AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres/airflow
|
- AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@airflow-metadb/airflow
|
||||||
- AIRFLOW__CORE__EXECUTOR=LocalExecutor
|
- AIRFLOW__CORE__EXECUTOR=LocalExecutor
|
||||||
# koneksi DB dashboard akreditasi + SerpAPI (nilai di-set di Coolify UI)
|
# koneksi DB dashboard akreditasi + SerpAPI (nilai di-set di Coolify UI)
|
||||||
- DB_HOST=${DB_HOST:-host.docker.internal}
|
- DB_HOST=${DB_HOST:-host.docker.internal}
|
||||||
@@ -63,6 +65,9 @@ services:
|
|||||||
- DWH_USERNAME=${DWH_USERNAME:-etl_writer}
|
- DWH_USERNAME=${DWH_USERNAME:-etl_writer}
|
||||||
- DWH_PASSWORD=${DWH_PASSWORD}
|
- DWH_PASSWORD=${DWH_PASSWORD}
|
||||||
- DWH_MIN_ANGKATAN=${DWH_MIN_ANGKATAN:-2019}
|
- 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:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+260
-125
@@ -14,14 +14,15 @@ Usage:
|
|||||||
python bigquery_cleaned_layer.py
|
python bigquery_cleaned_layer.py
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import pandas as pd
|
import re
|
||||||
import numpy as np
|
|
||||||
from datetime import datetime
|
|
||||||
import logging
|
|
||||||
from typing import Dict
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Dict, Optional
|
||||||
|
|
||||||
from scripts.bigquery_config import get_bigquery_client, CONFIG, get_table_id
|
import pandas as pd
|
||||||
|
|
||||||
|
from scripts.bigquery_config import get_bigquery_client
|
||||||
from scripts.bigquery_helpers import (
|
from scripts.bigquery_helpers import (
|
||||||
log_update,
|
log_update,
|
||||||
load_to_bigquery,
|
load_to_bigquery,
|
||||||
@@ -36,16 +37,36 @@ from google.cloud import bigquery
|
|||||||
# LOAD STAGING DATA
|
# LOAD STAGING DATA
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
|
REQUIRED_INPUT_COLUMNS = [
|
||||||
|
'source', 'indicator_original', 'indicator_standardized', 'country',
|
||||||
|
'year', 'year_range', 'value', 'unit',
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def load_staging_data(client: bigquery.Client) -> pd.DataFrame:
|
def load_staging_data(client: bigquery.Client) -> pd.DataFrame:
|
||||||
"""Load data dari staging_integrated (STAGING/Silver layer)."""
|
"""Load data dari staging_integrated (STAGING/Silver layer)."""
|
||||||
print("\nLoading data from staging_integrated (fs_asean_silver)...")
|
print("\nLoading data from staging_integrated (fs_asean_silver)...")
|
||||||
df_staging = read_from_bigquery(client, 'staging_integrated', layer='silver')
|
df_staging = read_from_bigquery(client, 'staging_integrated', layer='silver')
|
||||||
print(f" ✓ Loaded : {len(df_staging):,} rows")
|
print(f" ✓ Loaded : {len(df_staging):,} rows")
|
||||||
print(f" Columns : {len(df_staging.columns)}")
|
print(f" Columns : {len(df_staging.columns)}")
|
||||||
|
|
||||||
|
if df_staging.empty:
|
||||||
|
print(" ⚠ staging_integrated kosong.")
|
||||||
|
return df_staging
|
||||||
|
|
||||||
|
missing_cols = [c for c in REQUIRED_INPUT_COLUMNS if c not in df_staging.columns]
|
||||||
|
if missing_cols:
|
||||||
|
raise ValueError(f"Kolom wajib tidak ada di staging_integrated: {missing_cols}")
|
||||||
|
|
||||||
print(f" Sources : {df_staging['source'].nunique()}")
|
print(f" Sources : {df_staging['source'].nunique()}")
|
||||||
print(f" Indicators : {df_staging['indicator_standardized'].nunique()}")
|
print(f" Indicators : {df_staging['indicator_standardized'].nunique()}")
|
||||||
print(f" Countries : {df_staging['country'].nunique()}")
|
print(f" Countries : {df_staging['country'].nunique()}")
|
||||||
print(f" Year range : {int(df_staging['year'].min())}-{int(df_staging['year'].max())}")
|
|
||||||
|
years = pd.to_numeric(df_staging['year'], errors='coerce').dropna()
|
||||||
|
if not years.empty:
|
||||||
|
print(f" Year range : {int(years.min())}-{int(years.max())}")
|
||||||
|
else:
|
||||||
|
print(" Year range : - (kolom year kosong)")
|
||||||
return df_staging
|
return df_staging
|
||||||
|
|
||||||
|
|
||||||
@@ -66,7 +87,7 @@ COLUMN_CONSTRAINTS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def truncate_string(value, max_length: int) -> str:
|
def truncate_string(value, max_length: int):
|
||||||
"""Truncate string ke max_length, return as-is jika None/NaN."""
|
"""Truncate string ke max_length, return as-is jika None/NaN."""
|
||||||
if pd.isna(value):
|
if pd.isna(value):
|
||||||
return value
|
return value
|
||||||
@@ -94,7 +115,7 @@ def apply_column_constraints(df: pd.DataFrame) -> pd.DataFrame:
|
|||||||
truncation_report[column] = {
|
truncation_report[column] = {
|
||||||
'count' : int(truncated_count),
|
'count' : int(truncated_count),
|
||||||
'max_length': max_length,
|
'max_length': max_length,
|
||||||
'examples' : df_constrained[mask][column].head(3).tolist()
|
'examples' : df_constrained.loc[mask, column].head(3).tolist()
|
||||||
}
|
}
|
||||||
df_constrained[column] = df_constrained[column].apply(
|
df_constrained[column] = df_constrained[column].apply(
|
||||||
lambda x: truncate_string(x, max_length)
|
lambda x: truncate_string(x, max_length)
|
||||||
@@ -142,6 +163,8 @@ ASEAN_MAPPING = {
|
|||||||
'VIET NAM' : 'Vietnam',
|
'VIET NAM' : 'Vietnam',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ASEAN_COUNTRIES = set(ASEAN_MAPPING.values())
|
||||||
|
|
||||||
|
|
||||||
def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'country') -> tuple:
|
def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'country') -> tuple:
|
||||||
"""
|
"""
|
||||||
@@ -156,17 +179,26 @@ def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'cou
|
|||||||
def map_country(country):
|
def map_country(country):
|
||||||
if pd.isna(country):
|
if pd.isna(country):
|
||||||
return country
|
return country
|
||||||
s = str(country).strip()
|
# rapikan spasi & apostrof melengkung sebelum lookup
|
||||||
|
s = re.sub(r'\s+', ' ', str(country).strip().replace('’', "'"))
|
||||||
mapped = ASEAN_MAPPING.get(s.upper(), s)
|
mapped = ASEAN_MAPPING.get(s.upper(), s)
|
||||||
return mapped[:100] if len(mapped) > 100 else mapped
|
return mapped[:100] if len(mapped) > 100 else mapped
|
||||||
|
|
||||||
original = df_clean[country_column].copy()
|
original = df_clean[country_column].copy()
|
||||||
df_clean[country_column] = df_clean[country_column].apply(map_country)
|
df_clean[country_column] = original.apply(map_country)
|
||||||
changes = {orig: new for orig, new in zip(original, df_clean[country_column]) if orig != new}
|
|
||||||
|
# NaN != NaN bernilai True, jadi baris NaN harus dikecualikan secara eksplisit
|
||||||
|
changed = original.notna() & (original != df_clean[country_column])
|
||||||
|
changes = dict(zip(original[changed], df_clean.loc[changed, country_column]))
|
||||||
|
|
||||||
|
unmapped = sorted(
|
||||||
|
set(df_clean[country_column].dropna().unique()) - ASEAN_COUNTRIES
|
||||||
|
)
|
||||||
|
|
||||||
return df_clean, {
|
return df_clean, {
|
||||||
'countries_mapped': len(set(changes.keys())),
|
'countries_mapped': len(changes),
|
||||||
'changes' : changes,
|
'changes' : changes,
|
||||||
|
'non_asean_values': unmapped,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -174,14 +206,8 @@ def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'cou
|
|||||||
# PILLAR CLASSIFICATION
|
# PILLAR CLASSIFICATION
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
def assign_pillar(indicator_name: str) -> str:
|
def _match_pillar(indicator_name) -> Optional[str]:
|
||||||
"""
|
"""Return pillar jika ada keyword yang cocok, None jika tidak ada."""
|
||||||
Assign pillar berdasarkan keyword indikator.
|
|
||||||
Return values: 'Availability', 'Access', 'Utilization', 'Stability', 'Sustainability'
|
|
||||||
All ≤ 20 chars (varchar(20) constraint).
|
|
||||||
"""
|
|
||||||
if pd.isna(indicator_name):
|
|
||||||
return 'Sustainability'
|
|
||||||
ind = str(indicator_name).lower()
|
ind = str(indicator_name).lower()
|
||||||
|
|
||||||
for kw in ['requirement', 'coefficient', 'losses', 'fat supply']:
|
for kw in ['requirement', 'coefficient', 'losses', 'fat supply']:
|
||||||
@@ -215,21 +241,73 @@ def assign_pillar(indicator_name: str) -> str:
|
|||||||
]):
|
]):
|
||||||
return 'Utilization'
|
return 'Utilization'
|
||||||
|
|
||||||
return 'Sustainability'
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def assign_pillar(indicator_name: str) -> str:
|
||||||
|
"""
|
||||||
|
Assign pillar berdasarkan keyword indikator.
|
||||||
|
Return values: 'Availability', 'Access', 'Utilization', 'Stability', 'Sustainability'
|
||||||
|
All ≤ 20 chars (varchar(20) constraint).
|
||||||
|
Indikator tanpa keyword yang cocok jatuh ke 'Sustainability' (default).
|
||||||
|
"""
|
||||||
|
if pd.isna(indicator_name):
|
||||||
|
return 'Sustainability'
|
||||||
|
return _match_pillar(indicator_name) or 'Sustainability'
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# DIRECTION CLASSIFICATION
|
# DIRECTION CLASSIFICATION
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
def assign_direction(indicator_name: str) -> str:
|
_HIGHER_BETTER_EXCEPTIONS = [
|
||||||
"""
|
'exclusive breastfeeding',
|
||||||
Assign direction berdasarkan indikator.
|
'dietary energy supply',
|
||||||
Return values: 'higher_better' (13 chars) atau 'lower_better' (12 chars)
|
'dietary energy supply adequacy',
|
||||||
Both ≤ 15 chars (varchar(15) constraint).
|
'average fat supply',
|
||||||
"""
|
'average protein supply',
|
||||||
if pd.isna(indicator_name):
|
'supply of protein of animal origin',
|
||||||
return 'higher_better'
|
]
|
||||||
|
|
||||||
|
_LOWER_BETTER_KEYWORDS = [
|
||||||
|
'prevalence of undernourishment',
|
||||||
|
'prevalence of severe food insecurity',
|
||||||
|
'prevalence of moderate or severe food insecurity',
|
||||||
|
'prevalence of moderate food insecurity',
|
||||||
|
'prevalence of wasting',
|
||||||
|
'prevalence of stunting',
|
||||||
|
'prevalence of overweight',
|
||||||
|
'prevalence of obesity',
|
||||||
|
'prevalence of anemia',
|
||||||
|
'prevalence of low birthweight',
|
||||||
|
'number of people undernourished',
|
||||||
|
'number of severely food insecure',
|
||||||
|
'number of moderately or severely food insecure',
|
||||||
|
'number of children under 5 years affected by wasting',
|
||||||
|
'number of children under 5 years of age who are overweight',
|
||||||
|
'number of children under 5 years of age who are stunted',
|
||||||
|
'number of newborns with low birthweight',
|
||||||
|
'number of obese adults',
|
||||||
|
'number of women of reproductive age',
|
||||||
|
'percentage of children under 5 years affected by wasting',
|
||||||
|
'percentage of children under 5 years of age who are overweight',
|
||||||
|
'percentage of children under 5 years of age who are stunted',
|
||||||
|
'cereal import dependency',
|
||||||
|
'import dependency',
|
||||||
|
'value of food imports in total merchandise exports',
|
||||||
|
'value of food imports',
|
||||||
|
'variability of food production',
|
||||||
|
'variability of food supply',
|
||||||
|
'per capita food production variability',
|
||||||
|
'per capita food supply variability',
|
||||||
|
'coefficient of variation',
|
||||||
|
'incidence of caloric losses',
|
||||||
|
'food losses',
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _match_direction(indicator_name) -> Optional[str]:
|
||||||
|
"""Return direction jika ada keyword yang cocok, None jika tidak ada."""
|
||||||
ind = str(indicator_name).lower()
|
ind = str(indicator_name).lower()
|
||||||
|
|
||||||
# Spesifik lower_better
|
# Spesifik lower_better
|
||||||
@@ -237,57 +315,26 @@ def assign_direction(indicator_name: str) -> str:
|
|||||||
return 'lower_better'
|
return 'lower_better'
|
||||||
|
|
||||||
# Higher_better exceptions — cek sebelum lower_better keywords
|
# Higher_better exceptions — cek sebelum lower_better keywords
|
||||||
for kw in [
|
if any(kw in ind for kw in _HIGHER_BETTER_EXCEPTIONS):
|
||||||
'exclusive breastfeeding',
|
return 'higher_better'
|
||||||
'dietary energy supply',
|
|
||||||
'dietary energy supply adequacy',
|
|
||||||
'average fat supply',
|
|
||||||
'average protein supply',
|
|
||||||
'supply of protein of animal origin',
|
|
||||||
]:
|
|
||||||
if kw in ind:
|
|
||||||
return 'higher_better'
|
|
||||||
|
|
||||||
# Lower_better — masalah yang harus diminimalkan
|
# Lower_better — masalah yang harus diminimalkan
|
||||||
for kw in [
|
if any(kw in ind for kw in _LOWER_BETTER_KEYWORDS):
|
||||||
'prevalence of undernourishment',
|
return 'lower_better'
|
||||||
'prevalence of severe food insecurity',
|
|
||||||
'prevalence of moderate or severe food insecurity',
|
|
||||||
'prevalence of moderate food insecurity',
|
|
||||||
'prevalence of wasting',
|
|
||||||
'prevalence of stunting',
|
|
||||||
'prevalence of overweight',
|
|
||||||
'prevalence of obesity',
|
|
||||||
'prevalence of anemia',
|
|
||||||
'prevalence of low birthweight',
|
|
||||||
'number of people undernourished',
|
|
||||||
'number of severely food insecure',
|
|
||||||
'number of moderately or severely food insecure',
|
|
||||||
'number of children under 5 years affected by wasting',
|
|
||||||
'number of children under 5 years of age who are overweight',
|
|
||||||
'number of children under 5 years of age who are stunted',
|
|
||||||
'number of newborns with low birthweight',
|
|
||||||
'number of obese adults',
|
|
||||||
'number of women of reproductive age',
|
|
||||||
'percentage of children under 5 years affected by wasting',
|
|
||||||
'percentage of children under 5 years of age who are overweight',
|
|
||||||
'percentage of children under 5 years of age who are stunted',
|
|
||||||
'cereal import dependency',
|
|
||||||
'import dependency',
|
|
||||||
'value of food imports in total merchandise exports',
|
|
||||||
'value of food imports',
|
|
||||||
'variability of food production',
|
|
||||||
'variability of food supply',
|
|
||||||
'per capita food production variability',
|
|
||||||
'per capita food supply variability',
|
|
||||||
'coefficient of variation',
|
|
||||||
'incidence of caloric losses',
|
|
||||||
'food losses',
|
|
||||||
]:
|
|
||||||
if kw in ind:
|
|
||||||
return 'lower_better'
|
|
||||||
|
|
||||||
return 'higher_better'
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def assign_direction(indicator_name: str) -> str:
|
||||||
|
"""
|
||||||
|
Assign direction berdasarkan indikator.
|
||||||
|
Return values: 'higher_better' (13 chars) atau 'lower_better' (12 chars)
|
||||||
|
Both ≤ 15 chars (varchar(15) constraint).
|
||||||
|
Indikator tanpa keyword yang cocok jatuh ke 'higher_better' (default).
|
||||||
|
"""
|
||||||
|
if pd.isna(indicator_name):
|
||||||
|
return 'higher_better'
|
||||||
|
return _match_direction(indicator_name) or 'higher_better'
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -305,11 +352,11 @@ class CleanedDataLoader:
|
|||||||
|
|
||||||
Pipeline steps:
|
Pipeline steps:
|
||||||
1. Standardize country names (ASEAN)
|
1. Standardize country names (ASEAN)
|
||||||
2. Remove missing values
|
2. Remove missing values (hanya kolom wajib)
|
||||||
3. Remove duplicates
|
3. Remove duplicates
|
||||||
4. Add pillar classification
|
4. Add pillar & direction classification
|
||||||
5. Add direction classification
|
5. Apply column constraints & cast tipe data
|
||||||
6. Apply column constraints
|
6. Validate
|
||||||
7. Load ke BigQuery
|
7. Load ke BigQuery
|
||||||
8. Log ke Audit layer
|
8. Log ke Audit layer
|
||||||
"""
|
"""
|
||||||
@@ -327,13 +374,28 @@ class CleanedDataLoader:
|
|||||||
bigquery.SchemaField("direction", "STRING", mode="REQUIRED"),
|
bigquery.SchemaField("direction", "STRING", mode="REQUIRED"),
|
||||||
]
|
]
|
||||||
|
|
||||||
def __init__(self, client: bigquery.Client, load_mode: str = 'full_refresh'):
|
# Kolom yang benar-benar wajib ada (sesuai mode REQUIRED di schema + value
|
||||||
self.client = client
|
# karena baris tanpa nilai tidak berguna untuk analisis).
|
||||||
self.load_mode = load_mode
|
# year, year_range, unit bersifat NULLABLE sehingga TIDAK boleh membuat baris dibuang.
|
||||||
self.logger = logging.getLogger(self.__class__.__name__)
|
REQUIRED_NOT_NULL = [
|
||||||
|
'source', 'indicator_original', 'indicator_standardized', 'country', 'value'
|
||||||
|
]
|
||||||
|
|
||||||
|
# Kunci unik satu observasi. source & year_range ikut agar data dari sumber
|
||||||
|
# berbeda / periode berbeda tidak saling menimpa.
|
||||||
|
DEDUP_KEY = ['source', 'indicator_standardized', 'country', 'year', 'year_range']
|
||||||
|
|
||||||
|
OUTPUT_COLUMNS = [f.name for f in SCHEMA]
|
||||||
|
|
||||||
|
def __init__(self, client: bigquery.Client, load_mode: str = 'full_refresh',
|
||||||
|
filter_non_asean: bool = False):
|
||||||
|
self.client = client
|
||||||
|
self.load_mode = load_mode
|
||||||
|
self.filter_non_asean = filter_non_asean
|
||||||
|
self.logger = logging.getLogger(self.__class__.__name__)
|
||||||
self.logger.propagate = False
|
self.logger.propagate = False
|
||||||
self.table_name = 'cleaned_integrated'
|
self.table_name = 'cleaned_integrated'
|
||||||
self.target_layer = 'silver'
|
self.target_layer = 'silver'
|
||||||
|
|
||||||
self.metadata = {
|
self.metadata = {
|
||||||
'source_class' : self.__class__.__name__,
|
'source_class' : self.__class__.__name__,
|
||||||
@@ -355,37 +417,74 @@ class CleanedDataLoader:
|
|||||||
def _step_standardize_countries(self, df: pd.DataFrame) -> pd.DataFrame:
|
def _step_standardize_countries(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||||
print("\n [Step 1/5] Standardize country names...")
|
print("\n [Step 1/5] Standardize country names...")
|
||||||
df, report = standardize_country_names_asean(df, country_column='country')
|
df, report = standardize_country_names_asean(df, country_column='country')
|
||||||
print(f" ✓ ASEAN countries mapped : {report['countries_mapped']}")
|
print(f" ✓ Country name variants mapped : {report['countries_mapped']}")
|
||||||
unique_countries = sorted(df['country'].unique())
|
|
||||||
|
if report['non_asean_values']:
|
||||||
|
print(f" ⚠ Non-ASEAN values found : {report['non_asean_values']}")
|
||||||
|
if self.filter_non_asean:
|
||||||
|
before = len(df)
|
||||||
|
df = df[df['country'].isin(ASEAN_COUNTRIES)]
|
||||||
|
print(f" ✓ Non-ASEAN rows removed : {before - len(df):,}")
|
||||||
|
|
||||||
|
unique_countries = sorted(df['country'].dropna().unique())
|
||||||
print(f" Countries ({len(unique_countries)}) : {', '.join(unique_countries)}")
|
print(f" Countries ({len(unique_countries)}) : {', '.join(unique_countries)}")
|
||||||
log_update(self.client, 'STAGING', 'staging_integrated',
|
# Log ke tabel TARGET (bukan staging_integrated) agar audit trail benar
|
||||||
|
log_update(self.client, 'STAGING', self.table_name,
|
||||||
'standardize_asean', report['countries_mapped'])
|
'standardize_asean', report['countries_mapped'])
|
||||||
return df
|
return df
|
||||||
|
|
||||||
def _step_remove_missing(self, df: pd.DataFrame) -> pd.DataFrame:
|
def _step_remove_missing(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||||
print("\n [Step 2/5] Remove missing values...")
|
print("\n [Step 2/5] Remove missing values...")
|
||||||
rows_before = len(df)
|
rows_before = len(df)
|
||||||
df_clean = df.dropna(subset=list(df.columns))
|
df_clean = df.copy()
|
||||||
rows_after = len(df_clean)
|
|
||||||
removed = rows_before - rows_after
|
# String kosong / whitespace dianggap missing
|
||||||
|
for col in df_clean.select_dtypes(include='object').columns:
|
||||||
|
df_clean[col] = df_clean[col].replace(r'^\s*$', pd.NA, regex=True)
|
||||||
|
|
||||||
|
# Hanya kolom wajib — year_range / unit NULLABLE dan sering kosong
|
||||||
|
df_clean = df_clean.dropna(subset=self.REQUIRED_NOT_NULL)
|
||||||
|
|
||||||
|
# Observasi harus punya periode: minimal year ATAU year_range
|
||||||
|
has_period = df_clean['year'].notna() | df_clean['year_range'].notna()
|
||||||
|
df_clean = df_clean[has_period]
|
||||||
|
|
||||||
|
rows_after = len(df_clean)
|
||||||
|
removed = rows_before - rows_after
|
||||||
print(f" Rows before : {rows_before:,}")
|
print(f" Rows before : {rows_before:,}")
|
||||||
print(f" Rows after : {rows_after:,}")
|
print(f" Rows after : {rows_after:,}")
|
||||||
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
|
if rows_before:
|
||||||
print(f" Retention : {rows_after/rows_before*100:.1f}%")
|
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
|
||||||
|
print(f" Retention : {rows_after/rows_before*100:.1f}%")
|
||||||
return df_clean
|
return df_clean
|
||||||
|
|
||||||
def _step_remove_duplicates(self, df: pd.DataFrame) -> pd.DataFrame:
|
def _step_remove_duplicates(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||||
print("\n [Step 3/5] Remove duplicates...")
|
print("\n [Step 3/5] Remove duplicates...")
|
||||||
|
if df.empty:
|
||||||
|
return df
|
||||||
|
|
||||||
|
key = self.DEDUP_KEY
|
||||||
exact_dups = df.duplicated().sum()
|
exact_dups = df.duplicated().sum()
|
||||||
data_dups = df.duplicated(subset=['indicator_standardized', 'country', 'year', 'value']).sum()
|
key_dups = df.duplicated(subset=key).sum()
|
||||||
print(f" Exact duplicates : {exact_dups:,}")
|
# duplikat kunci dengan nilai berbeda = konflik data, perlu perhatian
|
||||||
print(f" Data duplicates : {data_dups:,}")
|
conflicts = (
|
||||||
rows_before = len(df)
|
df.groupby(key, dropna=False)['value'].nunique().gt(1).sum()
|
||||||
df_clean = df.drop_duplicates(
|
|
||||||
subset=['indicator_standardized', 'country', 'year'], keep='first'
|
|
||||||
)
|
)
|
||||||
removed = rows_before - len(df_clean)
|
print(f" Exact duplicates : {exact_dups:,}")
|
||||||
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
|
print(f" Key duplicates : {key_dups:,}")
|
||||||
|
if conflicts:
|
||||||
|
print(f" ⚠ Key dengan nilai berbeda (konflik): {conflicts:,} "
|
||||||
|
f"— baris pertama (urut deterministik) dipertahankan")
|
||||||
|
|
||||||
|
rows_before = len(df)
|
||||||
|
# Urutkan dulu agar keep='first' deterministik antar-run
|
||||||
|
df_sorted = df.sort_values(
|
||||||
|
key + ['indicator_original', 'value'],
|
||||||
|
na_position='last', kind='mergesort'
|
||||||
|
)
|
||||||
|
df_clean = df_sorted.drop_duplicates(subset=key, keep='first')
|
||||||
|
removed = rows_before - len(df_clean)
|
||||||
|
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
|
||||||
return df_clean
|
return df_clean
|
||||||
|
|
||||||
def _step_add_classifications(self, df: pd.DataFrame) -> pd.DataFrame:
|
def _step_add_classifications(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||||
@@ -394,21 +493,44 @@ class CleanedDataLoader:
|
|||||||
df['pillar'] = df['indicator_standardized'].apply(assign_pillar)
|
df['pillar'] = df['indicator_standardized'].apply(assign_pillar)
|
||||||
df['direction'] = df['indicator_standardized'].apply(assign_direction)
|
df['direction'] = df['indicator_standardized'].apply(assign_direction)
|
||||||
|
|
||||||
pillar_counts = df['pillar'].value_counts()
|
# Laporkan indikator yang jatuh ke nilai default (tidak ada keyword cocok)
|
||||||
print(f" ✓ Pillar distribution:")
|
indicators = df['indicator_standardized'].drop_duplicates()
|
||||||
for pillar, count in pillar_counts.items():
|
no_pillar = [i for i in indicators if _match_pillar(i) is None]
|
||||||
|
no_dir = [i for i in indicators if _match_direction(i) is None]
|
||||||
|
if no_pillar:
|
||||||
|
print(f" ⚠ {len(no_pillar)} indikator tanpa rule pillar (default 'Sustainability'):")
|
||||||
|
for ind in no_pillar[:10]:
|
||||||
|
print(f" - {ind}")
|
||||||
|
if no_dir:
|
||||||
|
print(f" ℹ {len(no_dir)} indikator tanpa rule direction (default 'higher_better'):")
|
||||||
|
for ind in no_dir[:10]:
|
||||||
|
print(f" - {ind}")
|
||||||
|
|
||||||
|
print(" ✓ Pillar distribution:")
|
||||||
|
for pillar, count in df['pillar'].value_counts().items():
|
||||||
print(f" - {pillar}: {count:,}")
|
print(f" - {pillar}: {count:,}")
|
||||||
|
|
||||||
direction_counts = df['direction'].value_counts()
|
print(" ✓ Direction distribution:")
|
||||||
print(f" ✓ Direction distribution:")
|
for direction, count in df['direction'].value_counts().items():
|
||||||
for direction, count in direction_counts.items():
|
print(f" - {direction}: {count:,} ({count / len(df) * 100:.1f}%)")
|
||||||
pct = count / len(df) * 100
|
|
||||||
print(f" - {direction}: {count:,} ({pct:.1f}%)")
|
|
||||||
return df
|
return df
|
||||||
|
|
||||||
def _step_apply_constraints(self, df: pd.DataFrame) -> pd.DataFrame:
|
def _step_apply_constraints(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||||
print("\n [Step 5/5] Apply column constraints...")
|
print("\n [Step 5/5] Apply column constraints & cast types...")
|
||||||
return apply_column_constraints(df)
|
df = apply_column_constraints(df)
|
||||||
|
|
||||||
|
# Cast sesuai schema BigQuery: year INTEGER (nullable), value FLOAT.
|
||||||
|
# Tanpa ini year bisa menjadi float64 dan gagal/berubah saat load.
|
||||||
|
df['year'] = pd.to_numeric(df['year'], errors='coerce').astype('Int64')
|
||||||
|
df['value'] = pd.to_numeric(df['value'], errors='coerce').astype('float64')
|
||||||
|
|
||||||
|
# Baris yang valuenya tidak bisa di-cast tidak boleh lolos
|
||||||
|
bad_value = df['value'].isna().sum()
|
||||||
|
if bad_value:
|
||||||
|
print(f" ⚠ {bad_value:,} baris dibuang: value bukan angka")
|
||||||
|
df = df.dropna(subset=['value'])
|
||||||
|
|
||||||
|
return df[self.OUTPUT_COLUMNS].reset_index(drop=True)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# VALIDATION
|
# VALIDATION
|
||||||
@@ -442,10 +564,11 @@ class CleanedDataLoader:
|
|||||||
column_length_check = {}
|
column_length_check = {}
|
||||||
for col, max_len in COLUMN_CONSTRAINTS.items():
|
for col, max_len in COLUMN_CONSTRAINTS.items():
|
||||||
if col in df.columns:
|
if col in df.columns:
|
||||||
max_actual = df[col].astype(str).str.len().max()
|
max_actual = df[col].dropna().astype(str).str.len().max()
|
||||||
|
max_actual = 0 if pd.isna(max_actual) else int(max_actual)
|
||||||
column_length_check[col] = {
|
column_length_check[col] = {
|
||||||
'max_length_constraint': max_len,
|
'max_length_constraint': max_len,
|
||||||
'max_actual_length' : int(max_actual),
|
'max_actual_length' : max_actual,
|
||||||
'within_limit' : bool(max_actual <= max_len)
|
'within_limit' : bool(max_actual <= max_len)
|
||||||
}
|
}
|
||||||
validation['column_length_check'] = column_length_check
|
validation['column_length_check'] = column_length_check
|
||||||
@@ -473,8 +596,14 @@ class CleanedDataLoader:
|
|||||||
df = self._step_standardize_countries(df)
|
df = self._step_standardize_countries(df)
|
||||||
df = self._step_remove_missing(df)
|
df = self._step_remove_missing(df)
|
||||||
df = self._step_remove_duplicates(df)
|
df = self._step_remove_duplicates(df)
|
||||||
df = self._step_add_classifications(df)
|
df = self._step_add_classifications(df) if not df.empty else df
|
||||||
df = self._step_apply_constraints(df)
|
df = self._step_apply_constraints(df) if not df.empty else df
|
||||||
|
|
||||||
|
# Pengaman: WRITE_TRUNCATE dengan DataFrame kosong akan MENGHAPUS tabel target.
|
||||||
|
if df.empty:
|
||||||
|
print("\n ERROR: Hasil cleaning kosong — load dibatalkan, "
|
||||||
|
"tabel cleaned_integrated tidak diubah.")
|
||||||
|
return 0
|
||||||
|
|
||||||
self.metadata['rows_transformed'] = len(df)
|
self.metadata['rows_transformed'] = len(df)
|
||||||
|
|
||||||
@@ -512,7 +641,11 @@ class CleanedDataLoader:
|
|||||||
).total_seconds()
|
).total_seconds()
|
||||||
self.metadata['execution_timestamp'] = self.metadata['start_time']
|
self.metadata['execution_timestamp'] = self.metadata['start_time']
|
||||||
self.metadata['completeness_pct'] = validation.get('completeness_pct', 0)
|
self.metadata['completeness_pct'] = validation.get('completeness_pct', 0)
|
||||||
self.metadata['config_snapshot'] = json.dumps({'load_mode': self.load_mode})
|
self.metadata['config_snapshot'] = json.dumps({
|
||||||
|
'load_mode' : self.load_mode,
|
||||||
|
'filter_non_asean': self.filter_non_asean,
|
||||||
|
'dedup_key' : self.DEDUP_KEY,
|
||||||
|
})
|
||||||
self.metadata['validation_metrics'] = json.dumps(validation)
|
self.metadata['validation_metrics'] = json.dumps(validation)
|
||||||
save_etl_metadata(self.client, self.metadata)
|
save_etl_metadata(self.client, self.metadata)
|
||||||
|
|
||||||
@@ -526,11 +659,11 @@ class CleanedDataLoader:
|
|||||||
print(f" Year range : {yr['min']}–{yr['max']}")
|
print(f" Year range : {yr['min']}–{yr['max']}")
|
||||||
print(f" Indicators : {validation.get('unique_indicators', '-')}")
|
print(f" Indicators : {validation.get('unique_indicators', '-')}")
|
||||||
print(f" Countries : {validation.get('unique_countries', '-')}")
|
print(f" Countries : {validation.get('unique_countries', '-')}")
|
||||||
print(f"\n Schema Validation:")
|
print("\n Schema Validation:")
|
||||||
for col, info in validation.get('column_length_check', {}).items():
|
for col, info in validation.get('column_length_check', {}).items():
|
||||||
status = "✓" if info['within_limit'] else "✗"
|
status = "✓" if info['within_limit'] else "✗"
|
||||||
print(f" {status} {col}: {info['max_actual_length']}/{info['max_length_constraint']}")
|
print(f" {status} {col}: {info['max_actual_length']}/{info['max_length_constraint']}")
|
||||||
print(f"\n Metadata → [AUDIT] etl_metadata")
|
print("\n Metadata → [AUDIT] etl_metadata")
|
||||||
|
|
||||||
return rows_loaded
|
return rows_loaded
|
||||||
|
|
||||||
@@ -545,12 +678,14 @@ def run_cleaned_integration():
|
|||||||
|
|
||||||
Dipanggil oleh DAG setelah task staging_integration_to_silver selesai.
|
Dipanggil oleh DAG setelah task staging_integration_to_silver selesai.
|
||||||
"""
|
"""
|
||||||
from scripts.bigquery_config import get_bigquery_client
|
|
||||||
client = get_bigquery_client()
|
client = get_bigquery_client()
|
||||||
df_staging = load_staging_data(client)
|
df_staging = load_staging_data(client)
|
||||||
loader = CleanedDataLoader(client, load_mode='full_refresh')
|
loader = CleanedDataLoader(client, load_mode='full_refresh')
|
||||||
rows = loader.run(df_staging)
|
rows = loader.run(df_staging)
|
||||||
print(f"Cleaned layer loaded: {rows:,} rows")
|
print(f"Cleaned layer loaded: {rows:,} rows")
|
||||||
|
if rows == 0:
|
||||||
|
# Gagalkan task Airflow agar tidak lanjut ke layer berikutnya dengan data lama/kosong
|
||||||
|
raise ValueError("Cleaned layer menghasilkan 0 rows — periksa staging_integrated.")
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -566,7 +701,7 @@ if __name__ == "__main__":
|
|||||||
print(" Audit : AUDIT → etl_logs, etl_metadata")
|
print(" Audit : AUDIT → etl_logs, etl_metadata")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
logger = setup_logging()
|
setup_logging()
|
||||||
client = get_bigquery_client()
|
client = get_bigquery_client()
|
||||||
df_staging = load_staging_data(client)
|
df_staging = load_staging_data(client)
|
||||||
|
|
||||||
@@ -577,5 +712,5 @@ if __name__ == "__main__":
|
|||||||
print("\n" + "=" * 60)
|
print("\n" + "=" * 60)
|
||||||
print("✓ CLEANED LAYER ETL COMPLETED")
|
print("✓ CLEANED LAYER ETL COMPLETED")
|
||||||
print(f" 🥈 STAGING (Silver) : cleaned_integrated ({final_count:,} rows)")
|
print(f" 🥈 STAGING (Silver) : cleaned_integrated ({final_count:,} rows)")
|
||||||
print(f" 📋 AUDIT : etl_logs, etl_metadata")
|
print(" 📋 AUDIT : etl_logs, etl_metadata")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
"""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 _kk_rows() -> list:
|
||||||
|
"""(id, nama) kelompok keahlian dari getListKK, untuk KK selain 4 KK prodi yang memakai singkatan tetap
|
||||||
|
(lihat dwh_spota_sql.py). Bentuk responsnya tidak terdokumentasi, jadi nama kolom dicari dari beberapa kemungkinan."""
|
||||||
|
try:
|
||||||
|
data = _spota_get("getListKK.php")
|
||||||
|
except Exception as exc: # noqa: BLE001 - KK hanya label, jangan gagalkan seluruh load
|
||||||
|
logger.warning("getListKK tidak terbaca, KK selain AI/NS/SE/IS tampil sebagai 'KK <id>': %s", exc)
|
||||||
|
return []
|
||||||
|
rows = []
|
||||||
|
for k in data:
|
||||||
|
if not isinstance(k, dict):
|
||||||
|
continue
|
||||||
|
id_kk = next((k[c] for c in ("idKK", "id_kk", "id") if c in k), None)
|
||||||
|
nama = next((k[c] for c in ("namaKK", "nama_kk", "nama", "name") if c in k), None)
|
||||||
|
rows.append((_int(id_kk), _teks(nama)))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _extract() -> list:
|
||||||
|
"""(tabel raw, [(kolom, tipe postgres)], baris) dari 5 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_kk", [("id", "int"), ("nama", "text")], _kk_rows()),
|
||||||
|
(
|
||||||
|
"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
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
"""SQL DWH SPOTA: riwayat pembimbing (kumulatif), raw -> staging -> mart (PostgreSQL).
|
||||||
|
|
||||||
|
Semua tabel staging/mart dibangun ulang penuh tiap run (DROP + CREATE AS), sama seperti
|
||||||
|
dwh_edoxid_sql.py. Satu-satunya tabel kumulatif adalah raw.spota_riwayat_pembimbing: API SPOTA
|
||||||
|
tidak menyimpan kapan Kajur menetapkan pembimbing, jadi hari pertama pemb1/pemb2 terlihat terisi
|
||||||
|
dicatat di sini setiap run (ketelitian 1 hari).
|
||||||
|
|
||||||
|
Dijalankan tanpa parameter psycopg2, jadi tanda persen ditulis tunggal.
|
||||||
|
Mart memakai mart.dim_mahasiswa, mart.dim_dosen dan mart.fact_ujian_ta dari dwh_tugas_akhir_daily.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# RIWAYAT: dijalankan di task load_raw_spota, setelah raw.spota_tugas_akhir dimuat
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
RIWAYAT_SQL = r"""
|
||||||
|
CREATE TABLE IF NOT EXISTS raw.spota_riwayat_pembimbing (
|
||||||
|
id_ta bigint PRIMARY KEY,
|
||||||
|
nim text,
|
||||||
|
tgl_disetujui date NOT NULL,
|
||||||
|
pertama_terlihat date NOT NULL,
|
||||||
|
pemb1_pada date,
|
||||||
|
pemb2_pada date,
|
||||||
|
keputusan text,
|
||||||
|
terakhir_terlihat date NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Topik yang sudah tercatat: isi hari pertama pembimbing terlihat terisi
|
||||||
|
UPDATE raw.spota_riwayat_pembimbing r SET
|
||||||
|
pemb1_pada = coalesce(r.pemb1_pada, CASE WHEN t.pemb1 IS NOT NULL THEN (now() AT TIME ZONE 'Asia/Pontianak')::date END),
|
||||||
|
pemb2_pada = coalesce(r.pemb2_pada, CASE WHEN t.pemb2 IS NOT NULL THEN (now() AT TIME ZONE 'Asia/Pontianak')::date END),
|
||||||
|
keputusan = t.keputusan,
|
||||||
|
terakhir_terlihat = (now() AT TIME ZONE 'Asia/Pontianak')::date
|
||||||
|
FROM raw.spota_tugas_akhir t
|
||||||
|
WHERE t.id = r.id_ta;
|
||||||
|
|
||||||
|
-- Topik baru yang sedang menunggu (diterima Ketua KK, pembimbing belum lengkap).
|
||||||
|
-- Topik yang sudah lengkap saat pertama terlihat tidak dicatat: masa tunggunya tidak diketahui.
|
||||||
|
INSERT INTO raw.spota_riwayat_pembimbing
|
||||||
|
(id_ta, nim, tgl_disetujui, pertama_terlihat, pemb1_pada, pemb2_pada, keputusan, terakhir_terlihat)
|
||||||
|
SELECT
|
||||||
|
t.id,
|
||||||
|
upper(t.nim),
|
||||||
|
t.tanggal_keputusan,
|
||||||
|
(now() AT TIME ZONE 'Asia/Pontianak')::date,
|
||||||
|
CASE WHEN t.pemb1 IS NOT NULL THEN (now() AT TIME ZONE 'Asia/Pontianak')::date END,
|
||||||
|
CASE WHEN t.pemb2 IS NOT NULL THEN (now() AT TIME ZONE 'Asia/Pontianak')::date END,
|
||||||
|
t.keputusan,
|
||||||
|
(now() AT TIME ZONE 'Asia/Pontianak')::date
|
||||||
|
FROM raw.spota_tugas_akhir t
|
||||||
|
WHERE t.id IS NOT NULL
|
||||||
|
AND t.keputusan = '1'
|
||||||
|
AND t.tanggal_keputusan IS NOT NULL
|
||||||
|
AND (t.pemb1 IS NULL OR t.pemb2 IS NULL)
|
||||||
|
ON CONFLICT (id_ta) DO NOTHING;
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# STAGING: normalisasi NIM/NIP, kode semester -> periode, KK per topik, jadwal ujian
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
STAGING_SQL = r"""
|
||||||
|
DROP TABLE IF EXISTS staging.spota_topik;
|
||||||
|
CREATE TABLE staging.spota_topik AS
|
||||||
|
WITH kk_nama AS (
|
||||||
|
-- getListDataTAMahasiswa mengirim ID KK (tb_kelompok_keahlian.idKK). KK prodi memakai singkatan
|
||||||
|
-- yang disepakati (1 Computation & AI, 2 Networking & Security, 3 Software Engineering &
|
||||||
|
-- Mobile Computing, 4 Information System & Data Spatial); KK lain memakai nama dari getListKK.
|
||||||
|
SELECT v.id, v.nama
|
||||||
|
FROM (VALUES (1, 'AI'), (2, 'NS'), (3, 'SE'), (4, 'IS')) AS v (id, nama)
|
||||||
|
UNION ALL
|
||||||
|
SELECT id, nama FROM raw.spota_kk WHERE id NOT IN (1, 2, 3, 4) AND nama IS NOT NULL
|
||||||
|
),
|
||||||
|
kk_id AS (
|
||||||
|
SELECT DISTINCT ON (id) id, nullif(trim(kelompok_keahlian), '') AS kk
|
||||||
|
FROM raw.spota_data_ta
|
||||||
|
WHERE id IS NOT NULL
|
||||||
|
ORDER BY id
|
||||||
|
),
|
||||||
|
-- cadangan bila id getListDataTAMahasiswa tidak sama dengan id getListTugasAkhir
|
||||||
|
kk_nim AS (
|
||||||
|
SELECT DISTINCT ON (upper(nim)) upper(nim) AS nim, nullif(trim(kelompok_keahlian), '') AS kk
|
||||||
|
FROM raw.spota_data_ta
|
||||||
|
WHERE nim IS NOT NULL
|
||||||
|
ORDER BY upper(nim), id DESC
|
||||||
|
)
|
||||||
|
SELECT DISTINCT ON (t.id)
|
||||||
|
t.id AS id_ta,
|
||||||
|
t.id_praoutline,
|
||||||
|
upper(t.nim) AS nim,
|
||||||
|
t.judul,
|
||||||
|
t.keputusan,
|
||||||
|
CASE t.keputusan WHEN '1' THEN 'Diterima' WHEN '2' THEN 'Ditolak' WHEN '3' THEN 'Gugur'
|
||||||
|
ELSE 'Lainnya' END AS status_keputusan,
|
||||||
|
t.tanggal_keputusan AS tgl_keputusan,
|
||||||
|
-- tahun "2026/2027" + semester "GAS-2026" (ganjil) / "GEN-2026" (genap)
|
||||||
|
substring(t.tahun FROM '^([0-9]{4})')::int AS tahun_mulai,
|
||||||
|
CASE WHEN upper(t.semester) LIKE 'GEN%' THEN 2 ELSE 1 END AS semester_no,
|
||||||
|
nullif(regexp_replace(t.pemb1, '\s', '', 'g'), '') AS pemb1,
|
||||||
|
nullif(regexp_replace(t.pemb2, '\s', '', 'g'), '') AS pemb2,
|
||||||
|
nullif(regexp_replace(t.peng1, '\s', '', 'g'), '') AS peng1,
|
||||||
|
nullif(regexp_replace(t.peng2, '\s', '', 'g'), '') AS peng2,
|
||||||
|
CASE WHEN t.keputusan = '1' THEN
|
||||||
|
CASE WHEN coalesce(ki.kk, kn.kk) ~ '^[0-9]+$'
|
||||||
|
THEN coalesce(nk.nama, 'KK ' || coalesce(ki.kk, kn.kk))
|
||||||
|
ELSE coalesce(ki.kk, kn.kk) END
|
||||||
|
END AS kelompok_keahlian,
|
||||||
|
t.sidang
|
||||||
|
FROM raw.spota_tugas_akhir t
|
||||||
|
LEFT JOIN kk_id ki ON ki.id = t.id
|
||||||
|
LEFT JOIN kk_nim kn ON kn.nim = upper(t.nim)
|
||||||
|
LEFT JOIN kk_nama nk ON nk.id::text = coalesce(ki.kk, kn.kk) -- bandingkan teks: cast ::int bisa gagal pada nilai non-angka
|
||||||
|
WHERE t.id IS NOT NULL AND t.nim IS NOT NULL
|
||||||
|
ORDER BY t.id;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS staging.spota_jadwal;
|
||||||
|
CREATE TABLE staging.spota_jadwal AS
|
||||||
|
SELECT
|
||||||
|
j.id_ta,
|
||||||
|
upper(j.nim) AS nim,
|
||||||
|
CASE j.jenis WHEN 'Outline' THEN 1 WHEN 'SidHas' THEN 2 WHEN 'Sidang' THEN 3 END AS tahap_id,
|
||||||
|
j.waktu AS tgl_ujian,
|
||||||
|
nullif(trim(j.ruangan), '') AS ruang
|
||||||
|
FROM raw.spota_jadwal j
|
||||||
|
WHERE j.jenis IN ('Outline', 'SidHas', 'Sidang') AND j.waktu IS NOT NULL;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS staging.spota_dosen;
|
||||||
|
CREATE TABLE staging.spota_dosen AS
|
||||||
|
SELECT DISTINCT ON (regexp_replace(nip, '\s', '', 'g'))
|
||||||
|
regexp_replace(nip, '\s', '', 'g') AS nip,
|
||||||
|
nullif(trim(nama), '') AS nama
|
||||||
|
FROM raw.spota_dosen
|
||||||
|
WHERE nullif(trim(nip), '') IS NOT NULL
|
||||||
|
ORDER BY regexp_replace(nip, '\s', '', 'g');
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# MART: dibaca dashboard (halaman Executive "Monitoring SPOTA") lewat dashboard_ro
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
MART_SQL = r"""
|
||||||
|
-- Satu baris per topik (draft praoutline) beserta keputusan, pembimbing, masa tunggu dan tahap ujian
|
||||||
|
DROP TABLE IF EXISTS mart.spota_topik;
|
||||||
|
CREATE TABLE mart.spota_topik AS
|
||||||
|
WITH nama_dosen AS (
|
||||||
|
SELECT DISTINCT ON (nip) nip, nama
|
||||||
|
FROM (
|
||||||
|
SELECT nip, nama, 1 AS prioritas FROM mart.dim_dosen
|
||||||
|
UNION ALL
|
||||||
|
SELECT nip, nama, 2 FROM staging.spota_dosen
|
||||||
|
) d
|
||||||
|
WHERE nama IS NOT NULL
|
||||||
|
ORDER BY nip, prioritas
|
||||||
|
),
|
||||||
|
angkatan_spota AS (
|
||||||
|
SELECT DISTINCT ON (upper(nim)) upper(nim) AS nim, angkatan
|
||||||
|
FROM raw.spota_mahasiswa
|
||||||
|
WHERE nim IS NOT NULL
|
||||||
|
ORDER BY upper(nim)
|
||||||
|
),
|
||||||
|
-- Ujian eDOXID disambungkan per NIM hanya ke topik diterima terakhir mahasiswa itu
|
||||||
|
terakhir AS (
|
||||||
|
SELECT DISTINCT ON (nim) id_ta
|
||||||
|
FROM staging.spota_topik
|
||||||
|
WHERE keputusan = '1'
|
||||||
|
ORDER BY nim, tgl_keputusan DESC NULLS LAST, id_ta DESC
|
||||||
|
),
|
||||||
|
ujian_edoxid AS (
|
||||||
|
SELECT DISTINCT ON (nim, tahap_id) nim, tahap_id, tgl_ujian, ruang
|
||||||
|
FROM mart.fact_ujian_ta
|
||||||
|
WHERE lulus_tahap AND tgl_ujian IS NOT NULL
|
||||||
|
ORDER BY nim, tahap_id, tgl_ujian
|
||||||
|
),
|
||||||
|
ujian_spota AS (
|
||||||
|
SELECT DISTINCT ON (id_ta, tahap_id) id_ta, tahap_id, tgl_ujian, ruang
|
||||||
|
FROM staging.spota_jadwal
|
||||||
|
ORDER BY id_ta, tahap_id, tgl_ujian
|
||||||
|
),
|
||||||
|
tahap AS (
|
||||||
|
-- eDOXID diutamakan (sumber resmi penjadwalan ujian); jadwal SPOTA sebagai cadangan data lama
|
||||||
|
SELECT
|
||||||
|
t.id_ta,
|
||||||
|
x.tahap_id,
|
||||||
|
coalesce(e.tgl_ujian, s.tgl_ujian) AS tgl,
|
||||||
|
CASE WHEN e.tgl_ujian IS NOT NULL THEN e.ruang ELSE s.ruang END AS ruang,
|
||||||
|
CASE WHEN e.tgl_ujian IS NOT NULL THEN 'eDOXID'
|
||||||
|
WHEN s.tgl_ujian IS NOT NULL THEN 'SPOTA' END AS sumber
|
||||||
|
FROM staging.spota_topik t
|
||||||
|
CROSS JOIN (VALUES (1), (2), (3)) AS x (tahap_id)
|
||||||
|
LEFT JOIN ujian_edoxid e
|
||||||
|
ON e.nim = t.nim AND e.tahap_id = x.tahap_id
|
||||||
|
AND t.id_ta IN (SELECT id_ta FROM terakhir)
|
||||||
|
AND (t.tgl_keputusan IS NULL OR e.tgl_ujian::date >= t.tgl_keputusan)
|
||||||
|
LEFT JOIN ujian_spota s ON s.id_ta = t.id_ta AND s.tahap_id = x.tahap_id
|
||||||
|
WHERE t.keputusan = '1'
|
||||||
|
),
|
||||||
|
tp AS (
|
||||||
|
SELECT
|
||||||
|
id_ta,
|
||||||
|
max(tgl) FILTER (WHERE tahap_id = 1) AS tgl_seminar_proposal,
|
||||||
|
max(ruang) FILTER (WHERE tahap_id = 1) AS ruang_seminar_proposal,
|
||||||
|
max(tgl) FILTER (WHERE tahap_id = 2) AS tgl_sidang_hasil,
|
||||||
|
max(ruang) FILTER (WHERE tahap_id = 2) AS ruang_sidang_hasil,
|
||||||
|
max(tgl) FILTER (WHERE tahap_id = 3) AS tgl_sidang_akhir,
|
||||||
|
max(ruang) FILTER (WHERE tahap_id = 3) AS ruang_sidang_akhir,
|
||||||
|
string_agg(DISTINCT sumber, ', ') AS sumber_tahap
|
||||||
|
FROM tahap
|
||||||
|
GROUP BY id_ta
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
t.id_ta,
|
||||||
|
t.id_praoutline,
|
||||||
|
t.nim,
|
||||||
|
m.nama,
|
||||||
|
coalesce(m.angkatan, a.angkatan,
|
||||||
|
CASE WHEN t.nim ~ '^D104[0-9]{7}$' THEN 2000 + substring(t.nim FROM 6 FOR 2)::int END) AS angkatan,
|
||||||
|
t.judul,
|
||||||
|
t.keputusan,
|
||||||
|
t.status_keputusan,
|
||||||
|
t.tgl_keputusan,
|
||||||
|
t.tahun_mulai || '-' || t.semester_no AS periode_kunci,
|
||||||
|
CASE t.semester_no WHEN 2 THEN 'Genap ' ELSE 'Ganjil ' END
|
||||||
|
|| t.tahun_mulai || '/' || (t.tahun_mulai + 1) AS periode_label,
|
||||||
|
CASE WHEN t.keputusan = '1' THEN coalesce(t.kelompok_keahlian, 'Tidak tercatat') END AS kelompok_keahlian,
|
||||||
|
t.pemb1 AS pemb1_nip, coalesce(d1.nama, t.pemb1) AS pemb1_nama,
|
||||||
|
t.pemb2 AS pemb2_nip, coalesce(d2.nama, t.pemb2) AS pemb2_nama,
|
||||||
|
t.peng1 AS peng1_nip, coalesce(d3.nama, t.peng1) AS peng1_nama,
|
||||||
|
t.peng2 AS peng2_nip, coalesce(d4.nama, t.peng2) AS peng2_nama,
|
||||||
|
(t.pemb1 IS NOT NULL AND t.pemb2 IS NOT NULL) AS pembimbing_lengkap,
|
||||||
|
-- Masa tunggu berjalan: topik diterima yang pembimbingnya belum lengkap
|
||||||
|
CASE WHEN t.keputusan = '1' AND (t.pemb1 IS NULL OR t.pemb2 IS NULL) AND t.tgl_keputusan IS NOT NULL
|
||||||
|
THEN (now() AT TIME ZONE 'Asia/Pontianak')::date - t.tgl_keputusan END AS hari_menunggu,
|
||||||
|
-- Masa tunggu selesai, dari riwayat harian; sisa data lama (> 1 tahun saat mulai dicatat) tidak dihitung
|
||||||
|
r.pertama_terlihat AS antrean_dicatat_sejak,
|
||||||
|
CASE WHEN r.pemb1_pada IS NOT NULL AND r.pemb2_pada IS NOT NULL
|
||||||
|
THEN greatest(r.pemb1_pada, r.pemb2_pada) END AS tgl_pembimbing_lengkap,
|
||||||
|
CASE WHEN r.pemb1_pada IS NOT NULL AND r.pemb2_pada IS NOT NULL
|
||||||
|
AND r.pertama_terlihat - r.tgl_disetujui <= 365
|
||||||
|
THEN greatest(r.pemb1_pada, r.pemb2_pada) - r.tgl_disetujui END AS hari_tunggu_pembimbing,
|
||||||
|
tp.tgl_seminar_proposal, tp.ruang_seminar_proposal,
|
||||||
|
tp.tgl_sidang_hasil, tp.ruang_sidang_hasil,
|
||||||
|
tp.tgl_sidang_akhir, tp.ruang_sidang_akhir,
|
||||||
|
tp.sumber_tahap
|
||||||
|
FROM staging.spota_topik t
|
||||||
|
LEFT JOIN mart.dim_mahasiswa m ON m.nim = t.nim
|
||||||
|
LEFT JOIN angkatan_spota a ON a.nim = t.nim
|
||||||
|
LEFT JOIN nama_dosen d1 ON d1.nip = t.pemb1
|
||||||
|
LEFT JOIN nama_dosen d2 ON d2.nip = t.pemb2
|
||||||
|
LEFT JOIN nama_dosen d3 ON d3.nip = t.peng1
|
||||||
|
LEFT JOIN nama_dosen d4 ON d4.nip = t.peng2
|
||||||
|
LEFT JOIN raw.spota_riwayat_pembimbing r ON r.id_ta = t.id_ta
|
||||||
|
LEFT JOIN tp ON tp.id_ta = t.id_ta
|
||||||
|
WHERE t.tahun_mulai IS NOT NULL;
|
||||||
|
ALTER TABLE mart.spota_topik ADD PRIMARY KEY (id_ta);
|
||||||
|
CREATE INDEX ON mart.spota_topik (nim);
|
||||||
|
CREATE INDEX ON mart.spota_topik (periode_kunci);
|
||||||
|
|
||||||
|
-- Mahasiswa aktif yang belum lulus + status judul di SPOTA (peringatan dini masa studi)
|
||||||
|
DROP TABLE IF EXISTS mart.spota_mhs_judul;
|
||||||
|
CREATE TABLE mart.spota_mhs_judul AS
|
||||||
|
WITH st AS (
|
||||||
|
SELECT nim, bool_or(keputusan = '1') AS diterima
|
||||||
|
FROM staging.spota_topik
|
||||||
|
GROUP BY nim
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
m.nim,
|
||||||
|
m.nama,
|
||||||
|
m.angkatan,
|
||||||
|
-- semester ganjil mulai Agustus (sama dengan mart.mhs_progres_ta)
|
||||||
|
(extract(year FROM current_date)::int - m.angkatan) * 2
|
||||||
|
+ CASE WHEN extract(month FROM current_date) >= 8 THEN 1 ELSE 0 END AS semester_ke,
|
||||||
|
CASE WHEN st.diterima THEN 'terima'
|
||||||
|
WHEN st.nim IS NOT NULL THEN 'draft'
|
||||||
|
ELSE 'belum' END AS status_judul
|
||||||
|
FROM mart.dim_mahasiswa m
|
||||||
|
LEFT JOIN st ON st.nim = m.nim
|
||||||
|
WHERE m.terdaftar_aktif AND NOT m.tercatat_lulus;
|
||||||
|
ALTER TABLE mart.spota_mhs_judul ADD PRIMARY KEY (nim);
|
||||||
|
"""
|
||||||
Reference in New Issue
Block a user