Compare commits

..
17 Commits
Author SHA1 Message Date
Debby 3fc2788b05 to 2024 2026-11-09 00:00:20 +07:00
Debby 2ef65ba399 analytical_fixed 2026-11-08 23:25:50 +07:00
Debby b4c42ff131 bigqueryanalitical in 2023 2026-11-08 22:22:37 +07:00
Debby 7618702148 analitical in 2023 2026-11-08 22:17:09 +07:00
Debby 98acb0b40a bigquery_analytical_2023 2026-11-05 12:50:43 +07:00
Debby c5f8c1edd6 Merge remote changes into main 2026-11-05 10:40:01 +07:00
Debby aa13c8cc47 bigquery_analytical_2 2026-11-05 10:37:47 +07:00
Power BI Dev 2449f20a72 adjust refresh date dwh edoxid 2026-11-04 22:39:06 +07:00
Debby 04ddae51fe bigquery_analytical_1 2026-11-04 21:41:15 +07:00
Debby 14b84fe28d update bigquery_cleaned_1 2026-11-04 21:15:11 +07:00
Power BI DevandClaude Opus 5.5 7d5a19344b dwh_spota: KK prodi pakai singkatan AI/NS/SE/IS
1 = AI (Computation & Artificial Intelligence), 2 = NS (Networking & Security),
3 = SE (Software Engineering & Mobile Computing), 4 = IS (Information System & Data Spatial).
KK lain tetap memakai nama dari getListKK, atau "KK <id>" bila tidak terbaca.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:27:09 +07:00
Power BI DevandClaude Opus 5.5 ddf7ed0a17 dwh_spota: nama kelompok keahlian, bukan ID
getListDataTAMahasiswa mengirim kelompokKeahlian berupa idKK (1..4), sehingga dashboard
menampilkan "1 2 3 4". Load kini ikut menarik getListKK ke raw.spota_kk dan staging
memetakan ID -> nama; daftar cadangan dari tb_kelompok_keahlian SPOTA dipakai bila
getListKK gagal atau bentuk responsnya lain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:24:30 +07:00
Power BI DevandClaude Opus 5.5 02a9e6f848 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>
2026-10-20 15:17:31 +07:00
Power BI DevandClaude Opus 5.5 d01fd5e94d re-add spota_antrean_daily dag (spota api -> antrean penetapan pembimbing di db dashboard)
Mengembalikan f7bc1e3 (di-revert di 786a63a saat Airflow down). Penyebab down ternyata
bentrok host "postgres", sudah diperbaiki di ccf9679, bukan DAG ini.
Env baru: SPOTA_API_SECRET (wajib, set di Coolify), SPOTA_API_URL (opsional).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:04:44 +07:00
Power BI DevandClaude Opus 5.5 ccf967984f rename airflow metadata db service postgres -> airflow-metadb
Setelah redeploy 2026-10-20, host "postgres" ter-resolve ke container Postgres lain
di jaringan Coolify (fd6c:e709:9132::17) sehingga scheduler & webserver gagal login
("password authentication failed for user airflow"), juga pada versi 78c5008.
Nama service unik mencegah bentrok; volume postgres_data tetap dipakai.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 14:59:38 +07:00
Power BI Dev 786a63a138 Revert "add spota_antrean_daily dag (spota api -> antrean penetapan pembimbing di db dashboard)"
This reverts commit f7bc1e31f4.
2026-10-20 14:51:39 +07:00
Power BI DevandClaude Opus 5.5 f7bc1e31f4 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>
2026-10-20 14:44:46 +07:00
7 changed files with 1463 additions and 559 deletions
+50
View File
@@ -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
+1 -1
View File
@@ -38,7 +38,7 @@ with DAG(
description="ETL tugas akhir eDOXID + data mahasiswa/dosen ke DWH PostgreSQL",
start_date=datetime(2026, 10, 1),
# 19:00 UTC = 02:00 WIB, di luar jam sibuk eDOXID
schedule_interval="0 19 * * *",
schedule_interval="0 * * * *",
catchup=False,
max_active_runs=1,
default_args={
+10 -5
View File
@@ -1,6 +1,8 @@
version: '3.8'
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
environment:
- POSTGRES_USER=airflow
@@ -13,10 +15,10 @@ services:
build: .
user: "50000:0"
depends_on:
- postgres
- airflow-metadb
environment:
- 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__LOAD_EXAMPLES=False
volumes:
@@ -30,10 +32,10 @@ services:
build: .
user: "50000:0"
depends_on:
- postgres
- airflow-metadb
environment:
- 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
# koneksi DB dashboard akreditasi + SerpAPI (nilai di-set di Coolify UI)
- DB_HOST=${DB_HOST:-host.docker.internal}
@@ -63,6 +65,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:
File diff suppressed because it is too large Load Diff
+260 -125
View File
@@ -14,14 +14,15 @@ Usage:
python bigquery_cleaned_layer.py
"""
import pandas as pd
import numpy as np
from datetime import datetime
import logging
from typing import Dict
import re
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 (
log_update,
load_to_bigquery,
@@ -36,16 +37,36 @@ from google.cloud import bigquery
# 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:
"""Load data dari staging_integrated (STAGING/Silver layer)."""
print("\nLoading data from staging_integrated (fs_asean_silver)...")
df_staging = read_from_bigquery(client, 'staging_integrated', layer='silver')
print(f" ✓ Loaded : {len(df_staging):,} rows")
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" Indicators : {df_staging['indicator_standardized'].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
@@ -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."""
if pd.isna(value):
return value
@@ -94,7 +115,7 @@ def apply_column_constraints(df: pd.DataFrame) -> pd.DataFrame:
truncation_report[column] = {
'count' : int(truncated_count),
'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(
lambda x: truncate_string(x, max_length)
@@ -142,6 +163,8 @@ ASEAN_MAPPING = {
'VIET NAM' : 'Vietnam',
}
ASEAN_COUNTRIES = set(ASEAN_MAPPING.values())
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):
if pd.isna(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)
return mapped[:100] if len(mapped) > 100 else mapped
original = df_clean[country_column].copy()
df_clean[country_column] = df_clean[country_column].apply(map_country)
changes = {orig: new for orig, new in zip(original, df_clean[country_column]) if orig != new}
original = df_clean[country_column].copy()
df_clean[country_column] = original.apply(map_country)
# 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, {
'countries_mapped': len(set(changes.keys())),
'countries_mapped': len(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
# =============================================================================
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).
"""
if pd.isna(indicator_name):
return 'Sustainability'
def _match_pillar(indicator_name) -> Optional[str]:
"""Return pillar jika ada keyword yang cocok, None jika tidak ada."""
ind = str(indicator_name).lower()
for kw in ['requirement', 'coefficient', 'losses', 'fat supply']:
@@ -215,21 +241,73 @@ def assign_pillar(indicator_name: str) -> str:
]):
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
# =============================================================================
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).
"""
if pd.isna(indicator_name):
return 'higher_better'
_HIGHER_BETTER_EXCEPTIONS = [
'exclusive breastfeeding',
'dietary energy supply',
'dietary energy supply adequacy',
'average fat supply',
'average protein supply',
'supply of protein of animal origin',
]
_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()
# Spesifik lower_better
@@ -237,57 +315,26 @@ def assign_direction(indicator_name: str) -> str:
return 'lower_better'
# Higher_better exceptions — cek sebelum lower_better keywords
for kw in [
'exclusive breastfeeding',
'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'
if any(kw in ind for kw in _HIGHER_BETTER_EXCEPTIONS):
return 'higher_better'
# Lower_better — masalah yang harus diminimalkan
for kw in [
'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',
]:
if kw in ind:
return 'lower_better'
if any(kw in ind for kw in _LOWER_BETTER_KEYWORDS):
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:
1. Standardize country names (ASEAN)
2. Remove missing values
2. Remove missing values (hanya kolom wajib)
3. Remove duplicates
4. Add pillar classification
5. Add direction classification
6. Apply column constraints
4. Add pillar & direction classification
5. Apply column constraints & cast tipe data
6. Validate
7. Load ke BigQuery
8. Log ke Audit layer
"""
@@ -327,13 +374,28 @@ class CleanedDataLoader:
bigquery.SchemaField("direction", "STRING", mode="REQUIRED"),
]
def __init__(self, client: bigquery.Client, load_mode: str = 'full_refresh'):
self.client = client
self.load_mode = load_mode
self.logger = logging.getLogger(self.__class__.__name__)
# Kolom yang benar-benar wajib ada (sesuai mode REQUIRED di schema + value
# karena baris tanpa nilai tidak berguna untuk analisis).
# year, year_range, unit bersifat NULLABLE sehingga TIDAK boleh membuat baris dibuang.
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.table_name = 'cleaned_integrated'
self.target_layer = 'silver'
self.table_name = 'cleaned_integrated'
self.target_layer = 'silver'
self.metadata = {
'source_class' : self.__class__.__name__,
@@ -355,37 +417,74 @@ class CleanedDataLoader:
def _step_standardize_countries(self, df: pd.DataFrame) -> pd.DataFrame:
print("\n [Step 1/5] Standardize country names...")
df, report = standardize_country_names_asean(df, country_column='country')
print(f" ✓ ASEAN countries mapped : {report['countries_mapped']}")
unique_countries = sorted(df['country'].unique())
print(f" ✓ Country name variants mapped : {report['countries_mapped']}")
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)}")
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'])
return df
def _step_remove_missing(self, df: pd.DataFrame) -> pd.DataFrame:
print("\n [Step 2/5] Remove missing values...")
rows_before = len(df)
df_clean = df.dropna(subset=list(df.columns))
rows_after = len(df_clean)
removed = rows_before - rows_after
df_clean = df.copy()
# 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 after : {rows_after:,}")
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
print(f" Retention : {rows_after/rows_before*100:.1f}%")
if rows_before:
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
print(f" Retention : {rows_after/rows_before*100:.1f}%")
return df_clean
def _step_remove_duplicates(self, df: pd.DataFrame) -> pd.DataFrame:
print("\n [Step 3/5] Remove duplicates...")
if df.empty:
return df
key = self.DEDUP_KEY
exact_dups = df.duplicated().sum()
data_dups = df.duplicated(subset=['indicator_standardized', 'country', 'year', 'value']).sum()
print(f" Exact duplicates : {exact_dups:,}")
print(f" Data duplicates : {data_dups:,}")
rows_before = len(df)
df_clean = df.drop_duplicates(
subset=['indicator_standardized', 'country', 'year'], keep='first'
key_dups = df.duplicated(subset=key).sum()
# duplikat kunci dengan nilai berbeda = konflik data, perlu perhatian
conflicts = (
df.groupby(key, dropna=False)['value'].nunique().gt(1).sum()
)
removed = rows_before - len(df_clean)
print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)")
print(f" Exact duplicates : {exact_dups:,}")
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
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['direction'] = df['indicator_standardized'].apply(assign_direction)
pillar_counts = df['pillar'].value_counts()
print(f" ✓ Pillar distribution:")
for pillar, count in pillar_counts.items():
# Laporkan indikator yang jatuh ke nilai default (tidak ada keyword cocok)
indicators = df['indicator_standardized'].drop_duplicates()
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:,}")
direction_counts = df['direction'].value_counts()
print(f" ✓ Direction distribution:")
for direction, count in direction_counts.items():
pct = count / len(df) * 100
print(f" - {direction}: {count:,} ({pct:.1f}%)")
print(" ✓ Direction distribution:")
for direction, count in df['direction'].value_counts().items():
print(f" - {direction}: {count:,} ({count / len(df) * 100:.1f}%)")
return df
def _step_apply_constraints(self, df: pd.DataFrame) -> pd.DataFrame:
print("\n [Step 5/5] Apply column constraints...")
return apply_column_constraints(df)
print("\n [Step 5/5] Apply column constraints & cast types...")
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
@@ -442,10 +564,11 @@ class CleanedDataLoader:
column_length_check = {}
for col, max_len in COLUMN_CONSTRAINTS.items():
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] = {
'max_length_constraint': max_len,
'max_actual_length' : int(max_actual),
'max_actual_length' : max_actual,
'within_limit' : bool(max_actual <= max_len)
}
validation['column_length_check'] = column_length_check
@@ -473,8 +596,14 @@ class CleanedDataLoader:
df = self._step_standardize_countries(df)
df = self._step_remove_missing(df)
df = self._step_remove_duplicates(df)
df = self._step_add_classifications(df)
df = self._step_apply_constraints(df)
df = self._step_add_classifications(df) if not df.empty else 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)
@@ -512,7 +641,11 @@ class CleanedDataLoader:
).total_seconds()
self.metadata['execution_timestamp'] = self.metadata['start_time']
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)
save_etl_metadata(self.client, self.metadata)
@@ -526,11 +659,11 @@ class CleanedDataLoader:
print(f" Year range : {yr['min']}–{yr['max']}")
print(f" Indicators : {validation.get('unique_indicators', '-')}")
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():
status = "✓" if info['within_limit'] else "✗"
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
@@ -545,12 +678,14 @@ def run_cleaned_integration():
Dipanggil oleh DAG setelah task staging_integration_to_silver selesai.
"""
from scripts.bigquery_config import get_bigquery_client
client = get_bigquery_client()
df_staging = load_staging_data(client)
loader = CleanedDataLoader(client, load_mode='full_refresh')
rows = loader.run(df_staging)
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("=" * 60)
logger = setup_logging()
setup_logging()
client = get_bigquery_client()
df_staging = load_staging_data(client)
@@ -577,5 +712,5 @@ if __name__ == "__main__":
print("\n" + "=" * 60)
print("✓ CLEANED LAYER ETL COMPLETED")
print(f" 🥈 STAGING (Silver) : cleaned_integrated ({final_count:,} rows)")
print(f" 📋 AUDIT : etl_logs, etl_metadata")
print(" 📋 AUDIT : etl_logs, etl_metadata")
print("=" * 60)
+202
View File
@@ -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
+280
View File
@@ -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);
"""