commit 6c5f811c8bfc217591abeb4556cd0bc414833399 Author: rakha Date: Wed Jan 14 19:31:41 2026 +0700 Init project with jetpack compose diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..836cb8b --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +Sistem Akademik \ No newline at end of file diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/appInsightsSettings.xml b/.idea/appInsightsSettings.xml new file mode 100644 index 0000000..371f2e2 --- /dev/null +++ b/.idea/appInsightsSettings.xml @@ -0,0 +1,26 @@ + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b86273d --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.agent.xml b/.idea/copilot.data.migration.agent.xml new file mode 100644 index 0000000..4ea72a9 --- /dev/null +++ b/.idea/copilot.data.migration.agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask.xml b/.idea/copilot.data.migration.ask.xml new file mode 100644 index 0000000..7ef04e2 --- /dev/null +++ b/.idea/copilot.data.migration.ask.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask2agent.xml b/.idea/copilot.data.migration.ask2agent.xml new file mode 100644 index 0000000..1f2ea11 --- /dev/null +++ b/.idea/copilot.data.migration.ask2agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.edit.xml b/.idea/copilot.data.migration.edit.xml new file mode 100644 index 0000000..8648f94 --- /dev/null +++ b/.idea/copilot.data.migration.edit.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..b77ef91 --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,18 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml new file mode 100644 index 0000000..91f9558 --- /dev/null +++ b/.idea/deviceManager.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..639c779 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..f0c6ad0 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,50 @@ + + + + \ No newline at end of file diff --git a/.idea/markdown.xml b/.idea/markdown.xml new file mode 100644 index 0000000..c61ea33 --- /dev/null +++ b/.idea/markdown.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/.idea/migrations.xml b/.idea/migrations.xml new file mode 100644 index 0000000..f8051a6 --- /dev/null +++ b/.idea/migrations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b2c751a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/studiobot.xml b/.idea/studiobot.xml new file mode 100644 index 0000000..539e3b8 --- /dev/null +++ b/.idea/studiobot.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..47500fb --- /dev/null +++ b/README.md @@ -0,0 +1,1116 @@ +# Aplikasi Absensi Akademik Berbasis Koordinat dan Foto + +Sistem Absensi Mahasiswa Universitas Bhayangkara Jakarta Raya +Berbasis Android dengan validasi lokasi GPS dan foto real-time + +--- + +## INFORMASI PROYEK + +Nama : Rakha Adi Saputro +NPM : 202310715083 +Mata Kuliah : Pemrograman Mobile +Universitas : Universitas Bhayangkara Jakarta Raya +Tahun : 2025-2026 + +--- + +## DESKRIPSI SISTEM + +Aplikasi absensi mahasiswa modern berbasis Android yang mengimplementasikan arsitektur MVVM (Model-View-ViewModel) dengan pendekatan offline-first. Sistem ini memastikan validitas kehadiran mahasiswa melalui verifikasi lokasi GPS dan pengambilan foto selfie secara real-time saat melakukan absensi. + +Fitur utama: +- Validasi lokasi berbasis GPS dengan radius 500 meter dari titik kampus +- Pengambilan foto selfie wajib saat absensi +- Penyimpanan data lokal dengan sinkronisasi otomatis ke backend +- Sistem login offline dengan enkripsi data +- Riwayat absensi tersimpan secara lokal +- Anti-spam: Satu foto untuk satu kali absensi + +--- + +## DEPENDENCY LENGKAP (build.gradle.kts) + +### Core Android +```kotlin +// AndroidX Core +implementation("androidx.core:core-ktx:1.17.0") +// Kotlin standard library dan extensions +``` + +### Jetpack Compose +```kotlin +// Compose BOM (Bill of Materials) - Mengelola versi Compose +implementation(platform("androidx.compose:compose-bom:2024.09.00")) + +// Compose UI +implementation("androidx.compose.ui:ui") +implementation("androidx.compose.ui:ui-graphics") +implementation("androidx.compose.ui:ui-tooling-preview") + +// Material Design 3 +implementation("androidx.compose.material3:material3") + +// Material Icons Extended +implementation("androidx.compose.material:material-icons-extended:1.6.0") +``` + +### Lifecycle & ViewModel +```kotlin +// Lifecycle Runtime +implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.4") +implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") + +// ViewModel untuk Compose +implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0") +``` + +### Activity & Navigation +```kotlin +// Activity untuk Compose +implementation("androidx.activity:activity-compose:1.9.0") +``` + +### Location Services +```kotlin +// Google Play Services Location +implementation("com.google.android.gms:play-services-location:21.0.1") +``` + +### Database (Room) +```kotlin +// Room components +implementation("androidx.room:room-runtime:2.6.1") +implementation("androidx.room:room-ktx:2.6.1") +kapt("androidx.room:room-compiler:2.6.1") // Annotation processor +``` + +### Network +```kotlin +// Retrofit +implementation("com.squareup.retrofit2:retrofit:2.9.0") +implementation("com.squareup.retrofit2:converter-gson:2.9.0") + +// OkHttp +implementation("com.squareup.okhttp3:logging-interceptor:4.11.0") +``` + +### Security +```kotlin +// Encrypted SharedPreferences +implementation("androidx.security:security-crypto:1.1.0-alpha06") +``` + +### Background Work +```kotlin +// WorkManager +implementation("androidx.work:work-runtime-ktx:2.9.0") +``` + +### Coroutines +```kotlin +// Kotlin Coroutines +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") +``` + +### Image Loading +```kotlin +// Coil untuk Compose +implementation("io.coil-kt:coil-compose:2.6.0") +``` + +### JSON Processing +```kotlin +// Gson +implementation("com.google.code.gson:gson:2.10.1") +``` + +### Testing +```kotlin +// Unit Testing +testImplementation("junit:junit:4.13.2") + +// Instrumented Testing +androidTestImplementation("androidx.test.ext:junit:1.3.0") +androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") +androidTestImplementation(platform("androidx.compose:compose-bom:2024.09.00")) +androidTestImplementation("androidx.compose.ui:ui-test-junit4") + +// Debug +debugImplementation("androidx.compose.ui:ui-tooling") +debugImplementation("androidx.compose.ui:ui-test-manifest") +``` + +### Gradle Plugins +```kotlin +plugins { + alias(libs.plugins.android.application) // AGP 8.13.2 + alias(libs.plugins.kotlin.android) // Kotlin 2.0.21 + alias(libs.plugins.kotlin.compose) // Compose Compiler + id("org.jetbrains.kotlin.kapt") // KAPT untuk Room +} +``` + +--- + +## ALASAN PEMILIHAN TEKNOLOGI + +### Mengapa Jetpack Compose? +1. **Modern & Declarative**: Lebih intuitif dan less boilerplate dibanding XML +2. **Type-safe**: Compile-time error detection +3. **Reactive**: Automatic UI updates saat state berubah +4. **Performance**: Efficient rendering dengan recomposition +5. **Official**: Recommended oleh Google untuk new projects +6. **Community**: Strong community support dan active development + +### Mengapa Room Database? +1. **Type-safe SQL**: Compile-time SQL query verification +2. **Coroutine Support**: Native async/await dengan suspend functions +3. **Reactive Queries**: Flow untuk reactive updates +4. **Migration Support**: Easy database version management +5. **Performance**: Optimized SQLite wrapper +6. **Official**: Part of Android Jetpack + +### Mengapa WorkManager? +1. **Guaranteed Execution**: Task akan dijalankan meski app tertutup +2. **Battery Efficient**: System-managed scheduling +3. **Constraints**: Network, battery, storage constraints +4. **Backward Compatible**: Works dari API 14+ +5. **Retry Logic**: Built-in retry dengan backoff +6. **Official**: Recommended untuk background work + +### Mengapa Retrofit + OkHttp? +1. **Type-safe**: Type-safe REST client +2. **Coroutine Support**: Native suspend functions +3. **Converter**: Auto JSON parsing dengan Gson +4. **Interceptor**: Logging, auth, retry logic +5. **Industry Standard**: Most popular Android HTTP client +6. **Maintained**: Active development dan support + +### Mengapa Encrypted SharedPreferences? +1. **Security**: AES256-GCM encryption +2. **Hardware-backed**: Android Keystore System +3. **Transparent**: No manual encryption code needed +4. **Simple API**: Same as regular SharedPreferences +5. **Official**: Part of Jetpack Security +6. **Compliant**: Meets security best practices + +### Mengapa Kotlin Coroutines? +1. **Lightweight**: Efficient thread management +2. **Structured Concurrency**: Prevents memory leaks +3. **Sequential Code**: Async code looks synchronous +4. **Exception Handling**: Structured exception propagation +5. **Cancellation**: Automatic cleanup +6. **Official**: First-class support in Android + +### Mengapa Coil untuk Image Loading? +1. **Kotlin-first**: Written in Kotlin untuk Kotlin +2. **Compose-native**: AsyncImage composable +3. **Coroutine-based**: Non-blocking operations +4. **Modern**: Uses OkHttp, supports latest formats +5. **Lightweight**: Smaller APK size vs Glide/Picasso +6. **Fast**: Memory & disk caching + +--- + +## PERBANDINGAN ALTERNATIF + +### UI Framework +- **Jetpack Compose** vs XML Views + - Compose: Less code, reactive, modern + - XML: Mature, more resources, backward compatible + - **Pilihan**: Compose (future-proof, better DX) + +### Database +- **Room** vs Realm vs SQLite + - Room: Type-safe, official, Jetpack integration + - Realm: Fast, cross-platform + - SQLite: Full control, verbose + - **Pilihan**: Room (best practices, official support) + +### Image Loading +- **Coil** vs Glide vs Picasso + - Coil: Kotlin-first, Compose-native, modern + - Glide: Mature, feature-rich, large + - Picasso: Simple, lightweight, older + - **Pilihan**: Coil (best for Compose) + +### HTTP Client +- **Retrofit** vs Ktor vs Volley + - Retrofit: Type-safe, widely used, mature + - Ktor: Kotlin-native, modern, less adoption + - Volley: Google-made, older, less features + - **Pilihan**: Retrofit (industry standard) + +### State Management +- **StateFlow** vs LiveData vs RxJava + - StateFlow: Kotlin-native, Compose-friendly + - LiveData: Lifecycle-aware, older + - RxJava: Powerful, steep learning curve + - **Pilihan**: StateFlow (modern, simple, official) + +--- + +## ARSITEKTUR APLIKASI + +### Pattern & Struktur +MVVM (Model-View-ViewModel) dengan Offline-First Architecture + +``` +presentation/ UI Layer (Jetpack Compose) +├── auth/ Halaman Login & Registrasi +├── absensi/ Halaman Absensi Utama +└── history/ Halaman Riwayat Absensi + +data/ Data Layer +├── local/ Local Storage +│ ├── database/ Room Database +│ ├── dao/ Data Access Object +│ └── entity/ Database Entity +├── repository/ Repository Pattern +├── network/ Network Service (n8n) +├── worker/ Background Sync Worker +└── model/ Data Models + +utils/ Utility Classes +├── NetworkUtils Network Connection Check +└── ImageUtils Image Processing & Base64 +``` + +--- + +## TEKNOLOGI & LIBRARY + +### Platform & Bahasa +- **Platform**: Android +- **Bahasa**: Kotlin 2.0.21 +- **Min SDK**: 28 (Android 9.0 Pie) + - Alasan: Support untuk Security Crypto, modern permission system, dan coverage market share yang memadai +- **Target SDK**: 36 (Android 14+) +- **Compile SDK**: 36 +- **JDK**: Java 11 (source & target compatibility) + +### UI Framework & Design System +**Jetpack Compose** - Modern Declarative UI Framework +- **Compose BOM**: 2024.09.00 +- **androidx.compose.ui**: Core Compose UI +- **androidx.compose.ui.graphics**: Graphics primitives +- **androidx.compose.ui.tooling**: Preview & debugging tools +- **Keunggulan**: + - Less code dibanding XML + - Reactive & declarative + - Type-safe + - Hot reload support + - Interoperability dengan View system + +**Material Design 3** +- **androidx.compose.material3**: Material Design 3 components +- **Components yang digunakan**: + - Scaffold (app structure) + - TopAppBar (navigation bar) + - Card (content containers) + - Button & OutlinedButton (actions) + - OutlinedTextField (form inputs) + - Text (typography) + - CircularProgressIndicator (loading states) + - AlertDialog (confirmations) +- **Fitur**: Dynamic color, adaptive layouts, modern color system + +**Material Icons Extended** +- **Version**: 1.6.0 +- **Library**: androidx.compose.material:material-icons-extended +- **Icons**: Person, Lock, Visibility, VisibilityOff, CameraAlt, MyLocation, History, Logout, Check, Close +- **Total Icons**: 2000+ icons tersedia + +### Database & Storage Layer +**Room Database** - SQLite ORM (Object-Relational Mapping) +- **Version**: 2.6.1 +- **Components**: + - **room-runtime**: Core library + - **room-ktx**: Kotlin extensions & coroutine support + - **room-compiler**: Annotation processor (KAPT) +- **Fitur yang digunakan**: + - @Entity (table definition) + - @Dao (data access object) + - @Query (SQL queries) + - @Insert, @Update, @Delete + - Flow untuk reactive queries + - Suspend functions untuk coroutines + - Migration support +- **Table**: attendance_history +- **Keunggulan**: Compile-time verification, type-safe queries, reactive streams + +**Encrypted SharedPreferences** - Secure Key-Value Storage +- **Library**: androidx.security:security-crypto:1.1.0-alpha06 +- **Encryption**: AES256-GCM (Galois/Counter Mode) +- **Key Management**: MasterKey dengan Android Keystore System +- **Key Scheme**: AES256_GCM +- **Value Encryption**: AES256_GCM +- **Key Encryption**: AES256_SIV (Synthetic IV) +- **Fitur**: Transparent encryption/decryption, hardware-backed keys +- **Data yang disimpan**: Username, Password, isRegistered, isLogin (semua terenkripsi) + +### Location Services +**Google Play Services Location** +- **Version**: 21.0.1 +- **Library**: com.google.android.gms:play-services-location +- **API**: Fused Location Provider API +- **Fitur yang digunakan**: + - FusedLocationProviderClient (high-level API) + - LocationRequest (accuracy & interval settings) + - LocationCallback (location updates) + - Priority: PRIORITY_HIGH_ACCURACY +- **Validasi**: + - 12 campus points dengan koordinat GPS + - Haversine Formula untuk kalkulasi jarak + - Location.distanceBetween() (Android built-in) + - Max radius: 500 meter +- **Keunggulan**: Battery-efficient, most accurate location + +### Network & Backend Integration +**Retrofit** - Type-safe HTTP Client +- **Version**: 2.9.0 +- **Library**: com.squareup.retrofit2:retrofit +- **Fitur**: REST API calls, coroutine support, request/response converters +- **Usage**: POST data absensi ke n8n webhook + +**Gson** - JSON Serialization/Deserialization +- **Gson Version**: 2.10.1 +- **Retrofit Converter**: com.squareup.retrofit2:converter-gson:2.9.0 +- **Fitur**: Automatic JSON parsing, custom type adapters +- **Usage**: Convert data objects ke JSON payload + +**OkHttp** - HTTP Client & Interceptor +- **Version**: 4.11.0 +- **Library**: com.squareup.okhttp3:logging-interceptor +- **Fitur**: HTTP logging, connection pooling, interceptors +- **Usage**: Debug network requests/responses, timeout configuration +- **Timeout Settings**: 30 detik connection & read timeout + +**n8n Webhook Integration** +- **Backend**: n8n Self-hosted Workflow Automation +- **Host**: n8n.lab.ubharajaya.ac.id +- **Method**: HTTP POST +- **Content-Type**: application/json +- **Endpoint Production**: /webhook/23c6993d-1792-48fb-ad1c-ffc78a3e6254 +- **Endpoint Testing**: /webhook-test/23c6993d-1792-48fb-ad1c-ffc78a3e6254 +- **Payload**: JSON dengan foto Base64, koordinat, timestamp, mata kuliah + +### Background Processing +**WorkManager** - Background Task Scheduler +- **Version**: 2.9.0 +- **Library**: androidx.work:work-runtime-ktx +- **Fitur**: + - Guaranteed execution (even after app restart) + - Constraints (network, battery, storage) + - Retry logic dengan exponential backoff + - Work chaining + - CoroutineWorker integration +- **Usage**: AttendanceSyncWorker untuk sync data PENDING ke backend +- **Trigger**: Network available constraint +- **Strategy**: Periodic check & automatic retry + +**Kotlin Coroutines** - Asynchronous Programming +- **Version**: 1.7.3 +- **Library**: org.jetbrains.kotlinx:kotlinx-coroutines-android +- **Dispatchers**: + - **Dispatchers.Main**: UI operations & state updates + - **Dispatchers.IO**: Network requests & database operations + - **Dispatchers.Default**: CPU-intensive computations +- **Features**: suspend functions, async/await, structured concurrency +- **Usage**: Semua async operations (database, network, location) + +**Flow & StateFlow** - Reactive Streams +- **Flow**: Cold stream untuk one-time operations +- **StateFlow**: Hot stream untuk UI state management +- **MutableStateFlow**: Mutable state holder +- **collectAsState()**: Compose integration untuk observe state +- **Usage**: ViewModel state management, database queries, UI updates + +### Image Processing +**Coil** - Image Loading Library untuk Compose +- **Version**: 2.6.0 +- **Library**: io.coil-kt:coil-compose +- **Fitur**: + - AsyncImage composable + - Memory & disk caching + - Image transformations + - Compose-first design + - Coroutine-based +- **Usage**: Load & display foto absensi di riwayat + +**Custom Image Utils** +- **Base64 Encoding**: Convert Bitmap ke Base64 string +- **Bitmap Compression**: JPEG compression dengan quality 80% +- **File I/O**: Save/load foto dari internal storage +- **Camera Integration**: ActivityResultContracts.TakePicture() +- **Usage**: Prepare foto untuk kirim ke backend + +### Architecture Components +**Lifecycle** - Lifecycle-Aware Components +- **lifecycle-runtime-ktx**: 2.9.4 +- **lifecycle-runtime-compose**: 2.7.0 +- **lifecycle-viewmodel-compose**: 2.7.0 +- **Fitur**: LifecycleOwner, ViewModelScope, collectAsStateWithLifecycle +- **Usage**: Manage UI lifecycle, survive configuration changes + +**ViewModel** - UI State Holder +- **Library**: androidx.lifecycle:lifecycle-viewmodel-compose +- **Features**: Survive configuration changes, ViewModelScope +- **ViewModels**: AuthViewModel, AbsensiViewModel, AttendanceHistoryViewModel +- **State Management**: StateFlow untuk expose state ke UI + +**Activity Compose** +- **Version**: 1.9.0 +- **Library**: androidx.activity:activity-compose +- **Features**: setContent {} untuk Compose, ComponentActivity, permission handling +- **Usage**: MainActivity sebagai entry point + +### Build Tools & Gradle +**Gradle** +- **Version**: 8.13.2 +- **Type**: Kotlin DSL (build.gradle.kts) +- **Plugin**: Android Gradle Plugin (AGP) +- **Features**: Dependency management, build variants, ProGuard/R8 + +**Kotlin Compiler** +- **Kotlin Version**: 2.0.21 +- **Compose Compiler Plugin**: org.jetbrains.kotlin.plugin.compose +- **KAPT**: Kotlin Annotation Processing Tool (untuk Room compiler) +- **Target**: JVM 11 + +**Version Catalog** +- **File**: gradle/libs.versions.toml +- **Fitur**: Centralized dependency management, type-safe accessors +- **Benefits**: Single source of truth, easy updates, IDE support + +### Testing Framework +**Unit Testing** +- **JUnit**: 4.13.2 (unit test framework) +- **Location**: src/test/java/ + +**Instrumented Testing** +- **AndroidX Test JUnit**: 1.3.0 +- **Espresso Core**: 3.7.0 +- **Compose UI Test**: androidx.compose.ui:ui-test-junit4 +- **Location**: src/androidTest/java/ + +**Debug Tools** +- **Compose UI Tooling**: Preview & inspection +- **Compose UI Test Manifest**: Test configuration + +### Utilities & Helpers +**NetworkUtils.kt** +- **Purpose**: Network connectivity checking +- **API**: ConnectivityManager +- **Usage**: Cek internet sebelum sync ke backend + +**ImageUtils.kt** +- **Purpose**: Image processing & conversion +- **Functions**: bitmapToBase64, compression, file operations +- **Usage**: Prepare foto untuk upload + +### Security & Permissions +**Android Permissions** +- ACCESS_FINE_LOCATION (GPS) +- ACCESS_COARSE_LOCATION (Network location) +- CAMERA (Take photos) +- INTERNET (Network communication) + +**Security Features** +- Encrypted local storage +- HTTPS communication +- Hardware-backed key storage (Keystore) +- No hardcoded credentials +- Certificate transparency + +--- + +## FITUR APLIKASI + +### 1. SISTEM LOGIN OFFLINE +- Konsep: First-time setup dengan one-time registration +- Metode: Offline (tidak menggunakan server) +- Penyimpanan: Encrypted SharedPreferences +- Enkripsi: AES256-GCM dengan MasterKey +- Data tersimpan: + - Username (terenkripsi) + - Password (terenkripsi) + - isRegistered flag + - isLogin flag +- Flow: + - Pertama kali: Buat username & password + - Selanjutnya: Login dengan kredensial tersimpan + - Validasi: Dilakukan secara lokal + +### 2. ABSENSI BERBASIS LOKASI +- Validasi radius: Maksimal 500 meter dari titik kampus +- Jumlah titik kampus: 12 lokasi strategis +- Titik kampus meliputi: + - Kampus Ubhara Jaya (Pusat) + - Fakultas Ilmu Komputer + - Fakultas Ekonomi dan Bisnis + - Fakultas Psikologi + - Perpustakaan Tanoto + - Grha Tanoto + - Masjid Ulul Albab + - Work Caffe Bekasi + - Lapangan Ubhara + - Sekretariat Kapal Baja + - Ruang Sedang Semu + - ATM BRI Ubhara Jaya +- Algoritma: Haversine Formula untuk hitung jarak +- Response: Menampilkan nama lokasi terdekat & jarak + +### 3. PENGAMBILAN FOTO ABSENSI +- Mode: Kamera depan (selfie) +- Trigger: Langsung saat proses absensi +- Batasan: Satu foto untuk satu kali absensi (anti-spam) +- Penyimpanan: Internal storage aplikasi +- Format: JPEG dengan kompresi +- Pengiriman: Konversi ke Base64 untuk dikirim ke backend + +### 4. PENYIMPANAN DATA LOKAL +Database: Room (SQLite) +Table: attendance_history + +Schema: +- id: String (UUID, Primary Key) +- studentId: String (NPM mahasiswa) +- studentName: String (Nama mahasiswa) +- courseName: String (Nama mata kuliah) +- photoPath: String (Path foto di storage) +- dateTime: Long (Timestamp Unix) +- latitude: Double (Koordinat lintang) +- longitude: Double (Koordinat bujur) +- locationName: String (Nama lokasi terdekat) +- distanceMeter: Int (Jarak dari titik kampus) +- attendanceStatus: String (SUCCESS/FAILED) +- syncStatus: String (PENDING/SYNCED) +- createdAt: Long (Timestamp pembuatan) + +### 5. SINKRONISASI BACKEND +- Service: n8n Webhook Automation +- Method: POST HTTP Request +- Format: JSON dengan foto Base64 +- Strategy: Offline-first dengan background sync +- Worker: AttendanceSyncWorker (WorkManager) +- Retry: Otomatis saat koneksi internet tersedia +- Flow: + 1. Simpan data ke local database + 2. Cek koneksi internet + 3. Jika online: Kirim langsung ke n8n + 4. Jika offline: Tandai PENDING + 5. Background worker cek pending data + 6. Kirim ulang saat internet tersedia + 7. Update status menjadi SYNCED + +Payload ke n8n: +```json +{ + "npm": "202310715083", + "nama": "Rakha Adi Saputro", + "mata_kuliah": "Nama Mata Kuliah", + "latitude": -6.224158, + "longitude": 107.009268, + "timestamp": "2025-01-14T10:30:00Z", + "foto_base64": "base64_encoded_image_string" +} +``` + +### 6. RIWAYAT ABSENSI +- Screen: AttendanceHistoryScreen +- Data source: Room Database (local) +- Layout: LazyColumn (efficient scrolling) +- Card components: + - Thumbnail foto absensi + - Nama mata kuliah + - Waktu absensi (formatted) + - Koordinat lokasi + - Jarak dari kampus + - Status sinkronisasi (PENDING/SYNCED) +- Filter: Semua data dari lokal +- Offline support: Full offline browsing + +### 7. DATA MAHASISWA +Data mahasiswa yang digunakan fixed (hardcoded): +- NPM: 202310715083 +- Nama: Rakha Adi Saputro + +Catatan: Data ini tidak diambil dari login, tetapi langsung diset di aplikasi + +--- + +## PERMISSIONS ANDROID + +Aplikasi memerlukan izin berikut: + +```xml + + + + +``` + +Hardware features: +```xml + +``` + +--- + +## BACKEND INTEGRATION + +### n8n Workflow Automation +- Platform: n8n (Self-hosted) +- Host: n8n.lab.ubharajaya.ac.id +- Endpoint Production: /webhook/23c6993d-1792-48fb-ad1c-ffc78a3e6254 +- Endpoint Testing: /webhook-test/23c6993d-1792-48fb-ad1c-ffc78a3e6254 + +### Data Destination +1. Google Sheets + - URL: https://docs.google.com/spreadsheets/d/1jH15MfnNgpPGuGeid0hYfY7fFUHCEFbCmg8afTyyLZs + - Columns: NPM, Nama, Mata Kuliah, Latitude, Longitude, Timestamp, Foto + +2. ntfy Notification Service + - URL: https://ntfy.ubharajaya.ac.id/EAS + - Purpose: Real-time notification untuk dosen/admin + +### Workflow n8n +File: n8n-workflow-EAS.json +Flow: +1. Webhook Trigger (receive POST data) +2. Data Validation +3. Write to Google Sheets +4. Send notification via ntfy +5. Return response to mobile app + +--- + +## STRUKTUR DATA FLOW + +``` +User Action (Absensi) + | + v +Validasi Lokasi GPS + | + v +Ambil Foto Selfie + | + v +Simpan ke Room Database (Local) + | + v +Update UI (Riwayat bertambah) + | + v +Cek Koneksi Internet + | + +---> [Online] ---> Kirim ke n8n Webhook + | | + | v + | Update syncStatus = SYNCED + | + +---> [Offline] ---> Set syncStatus = PENDING + | + v + WorkManager scheduled + | + v + [Internet tersedia] + | + v + Retry kirim data PENDING + | + v + Update syncStatus = SYNCED +``` + +--- + +## CARA KERJA SISTEM + +### Flow Lengkap Absensi: + +1. PERSIAPAN + - User buka aplikasi + - Jika belum login: tampilkan AuthScreen + - Jika sudah login: tampilkan AbsensiScreen + +2. HALAMAN ABSENSI + - Tampilkan NPM dan Nama (hardcoded) + - Input mata kuliah + - Tombol ambil foto + - Request permissions (Camera & Location) + +3. PROSES ABSENSI + - User klik tombol absensi + - Sistem cek permission camera + - Buka camera untuk selfie + - User ambil foto + - Foto ditampilkan sebagai preview + - Sistem ambil koordinat GPS otomatis + - Validasi jarak dari titik kampus + +4. VALIDASI + - Cek jarak < 500 meter? + - Ya: Lanjut proses + - Tidak: Tampilkan error & batalkan + - Cek foto valid? + - Ya: Lanjut proses + - Tidak: Minta foto ulang + +5. PENYIMPANAN + - Generate UUID untuk attendance ID + - Simpan foto ke internal storage + - Simpan data ke Room Database + - Set syncStatus = PENDING + +6. SINKRONISASI + - Cek koneksi internet + - Jika online: + - Encode foto ke Base64 + - Kirim POST ke n8n webhook + - Jika sukses: Update syncStatus = SYNCED + - Jika gagal: Tetap PENDING + - Jika offline: + - Skip sync + - Data tetap PENDING + - WorkManager akan retry nanti + +7. BACKGROUND SYNC + - WorkManager cek setiap internet tersedia + - Ambil semua data PENDING + - Kirim satu per satu ke n8n + - Update status yang berhasil + - Retry yang gagal + +8. RIWAYAT + - User bisa lihat semua absensi di HistoryScreen + - Data diambil dari Room Database + - Menampilkan status PENDING/SYNCED + - Full offline support + +--- + +## KEAMANAN + +### 1. Enkripsi Data +- Encrypted SharedPreferences dengan AES256-GCM +- MasterKey untuk enkripsi kredensial login +- Password tidak disimpan plain text + +### 2. Validasi Lokasi +- Multi-point validation (12 titik kampus) +- Radius enforcement (500 meter maksimal) +- Real-time distance calculation + +### 3. Anti-Fraud +- Satu foto untuk satu absensi +- Foto harus diambil real-time (tidak bisa dari gallery) +- Timestamp server-side di n8n +- Validasi koordinat di backend (opsional) + +### 4. Offline Security +- Data lokal terenkripsi +- No sensitive data in plain text +- Secure file storage + +--- + +## KONFIGURASI ENDPOINT + +File: ApiConfig.kt +Location: data/network/ApiConfig.kt + +```kotlin +object ApiConfig { + const val N8N_WEBHOOK_URL = + "https://n8n.lab.ubharajaya.ac.id/webhook/23c6993d-1792-48fb-ad1c-ffc78a3e6254" + + // Untuk testing: + // const val N8N_WEBHOOK_URL = + // "https://n8n.lab.ubharajaya.ac.id/webhook-test/23c6993d-1792-48fb-ad1c-ffc78a3e6254" + + const val CONNECTION_TIMEOUT = 30000 // 30 detik + const val READ_TIMEOUT = 30000 // 30 detik +} +``` + +Keuntungan centralized config: +- Mudah switch antara production & testing +- Tidak perlu ubah banyak file +- Maintenance lebih simple +- Deploy lebih aman + +--- + +## ANDROID SDK CONFIGURATION + +### SDK Versions +```kotlin +android { + compileSdk = 36 + + defaultConfig { + applicationId = "id.ac.ubharajaya.sistemakademik" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + } +} +``` + +### Min SDK 28 (Android 9.0 Pie) - Coverage & Features +**Alasan pemilihan Min SDK 28:** +1. **Market Coverage**: ~80% devices (2024-2025 data) +2. **Security Features**: + - Mandatory HTTPS + - BiometricPrompt API + - Security Crypto support +3. **Modern APIs**: + - ImageDecoder API + - DisplayCutout support + - Indoor positioning (WiFi RTT) +4. **Location Features**: + - Foreground location access + - Better battery optimization +5. **Camera Features**: + - Multi-camera API + - Session parameters +6. **Performance**: + - ART improvements + - Background restrictions + +### Target SDK 36 (Android 14+) - Latest Features +**Benefits:** +1. Google Play requirement compliance +2. Latest security patches +3. Performance optimizations +4. New API features +5. Better battery management +6. Enhanced privacy controls + +### Compile SDK 36 +- Access to latest Android APIs +- Build tools compatibility +- Preview features +- Development libraries + +### Java Compatibility +```kotlin +compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +kotlinOptions { + jvmTarget = "11" +} +``` + +**Java 11 Features:** +- Lambda expressions +- Method references +- Stream API +- Optional class +- Try-with-resources +- Type inference (var) + +--- + +## BUILD CONFIGURATION + +### Build Types + +#### Debug Build +```kotlin +buildTypes { + debug { + isMinifyEnabled = false + isDebuggable = true + applicationIdSuffix = ".debug" + versionNameSuffix = "-DEBUG" + } +} +``` +**Features:** +- No code obfuscation +- Full logging enabled +- Faster build time +- Debug symbols included +- Network profiler enabled + +#### Release Build +```kotlin +buildTypes { + release { + isMinifyEnabled = false // Set true for production + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + signingConfig = signingConfigs.getByName("release") + } +} +``` +**Features:** +- Code shrinking (ProGuard/R8) +- Obfuscation +- Optimization +- Signing required +- Smaller APK size + +### Build Features +```kotlin +buildFeatures { + compose = true +} +``` +- Enables Jetpack Compose +- Compose compiler integration +- Preview support + +### ProGuard/R8 Configuration +File: `proguard-rules.pro` + +**Purpose:** +- Code shrinking (remove unused code) +- Obfuscation (rename classes/methods) +- Optimization (inline, etc.) +- APK size reduction + +**Keep Rules for:** +- Room entities (@Entity) +- Retrofit interfaces +- Gson models +- Parcelable classes + +### APK Outputs +**Debug APK:** +- Path: `app/build/outputs/apk/debug/app-debug.apk` +- Size: ~15-20 MB (with debug symbols) +- Command: `.\gradlew assembleDebug` + +**Release APK:** +- Path: `app/build/outputs/apk/release/app-release.apk` +- Size: ~8-12 MB (minified) +- Command: `.\gradlew assembleRelease` + +--- + +## GRADLE BUILD SYSTEM + +### Requirements +- Android Studio Ladybug atau lebih baru +- JDK 11 atau lebih tinggi +- Android SDK 28-36 +- Gradle 8.13.2 +- Koneksi internet (untuk dependency download) + +### Build Commands + +Development Build: +```bash +.\gradlew assembleDebug +``` + +Release Build: +```bash +.\gradlew assembleRelease +``` + +Clean Build: +```bash +.\gradlew clean assembleDebug +``` + +Install ke Device: +```bash +.\gradlew installDebug +``` + +Run Tests: +```bash +.\gradlew test +``` + +### Output Location +APK Debug: app/build/outputs/apk/debug/app-debug.apk +APK Release: app/build/outputs/apk/release/app-release.apk + +--- + +## TESTING + +### Akun Testing +Saat pertama kali buka aplikasi: +- Buat username dan password bebas +- Data tersimpan secara offline +- Login selanjutnya gunakan kredensial tersebut + +### Testing Lokasi +Opsi 1: Test di lokasi kampus (ideal) +Opsi 2: Mock location untuk development: +- Enable Developer Options +- Select mock location app +- Gunakan koordinat salah satu dari 12 titik kampus + +### Testing n8n Webhook +Gunakan endpoint testing: +``` +https://n8n.lab.ubharajaya.ac.id/webhook-test/23c6993d-1792-48fb-ad1c-ffc78a3e6254 +``` + +Ganti di ApiConfig.kt untuk testing + +### Monitoring +- Google Sheets: Cek data masuk +- ntfy: Cek notifikasi real-time +- Logcat: Monitor logs di Android Studio + +--- + +## TROUBLESHOOTING + +### Issue: Foto tidak terkirim ke backend +Solusi: +- Cek koneksi internet +- Cek endpoint n8n aktif +- Lihat syncStatus di riwayat (PENDING berarti belum terkirim) +- Background worker akan retry otomatis + +### Issue: Lokasi tidak valid padahal di kampus +Solusi: +- Pastikan GPS aktif +- Tunggu GPS lock (butuh waktu) +- Cek permission lokasi granted +- Pastikan tidak menggunakan VPN yang mengubah lokasi + +### Issue: Kamera tidak bisa dibuka +Solusi: +- Cek permission camera granted +- Restart aplikasi +- Pastikan camera tidak digunakan app lain +- Cek hardware camera berfungsi + +### Issue: Data tidak tersimpan di database +Solusi: +- Cek storage permission +- Cek disk space mencukupi +- Lihat logcat untuk error Room +- Clear app data dan coba lagi + +### Issue: WorkManager tidak sync +Solusi: +- Pastikan internet stabil +- Cek battery optimization (disable untuk app ini) +- Force sync dengan buka riwayat +- Restart device + +--- +### Author +- NAMA : RAKHA ADI SAPUTRO +- NPM : 202310715083 diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..433ab44 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,98 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) + id("org.jetbrains.kotlin.kapt") +} + +android { + namespace = "id.ac.ubharajaya.sistemakademik" + compileSdk { + version = release(36) + } + + defaultConfig { + applicationId = "id.ac.ubharajaya.sistemakademik" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + buildFeatures { + compose = true + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation("androidx.activity:activity-compose:1.9.0") + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + + // Material Icons Extended + implementation("androidx.compose.material:material-icons-extended:1.6.0") + + // Location (GPS) + implementation("com.google.android.gms:play-services-location:21.0.1") + + // ViewModel & Lifecycle + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") + + // Coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + + // Security Crypto - Encrypted SharedPreferences + implementation("androidx.security:security-crypto:1.1.0-alpha06") + + // Room Database + implementation("androidx.room:room-runtime:2.6.1") + implementation("androidx.room:room-ktx:2.6.1") + kapt("androidx.room:room-compiler:2.6.1") + + // Retrofit for API calls + implementation("com.squareup.retrofit2:retrofit:2.9.0") + implementation("com.squareup.retrofit2:converter-gson:2.9.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.11.0") + + // WorkManager for background sync + implementation("androidx.work:work-runtime-ktx:2.9.0") + + // Coil for image loading + implementation("io.coil-kt:coil-compose:2.6.0") + + // Gson for JSON parsing + implementation("com.google.code.gson:gson:2.10.1") + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/id/ac/ubharajaya/sistemakademik/ExampleInstrumentedTest.kt b/app/src/androidTest/java/id/ac/ubharajaya/sistemakademik/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..ef22af9 --- /dev/null +++ b/app/src/androidTest/java/id/ac/ubharajaya/sistemakademik/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package id.ac.ubharajaya.sistemakademik + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("id.ac.ubharajaya.sistemakademik", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4619836 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/MainActivity.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/MainActivity.kt new file mode 100644 index 0000000..acf08d5 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/MainActivity.kt @@ -0,0 +1,144 @@ +package id.ac.ubharajaya.sistemakademik + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.work.* +import id.ac.ubharajaya.sistemakademik.data.local.SecurePreferences +import id.ac.ubharajaya.sistemakademik.data.local.database.AppDatabase +import id.ac.ubharajaya.sistemakademik.data.network.N8nService +import id.ac.ubharajaya.sistemakademik.data.repository.AttendanceRepository +import id.ac.ubharajaya.sistemakademik.data.repository.AuthRepository +import id.ac.ubharajaya.sistemakademik.data.worker.AttendanceSyncWorker +import id.ac.ubharajaya.sistemakademik.presentation.absensi.AbsensiScreen +import id.ac.ubharajaya.sistemakademik.presentation.absensi.AbsensiViewModel +import id.ac.ubharajaya.sistemakademik.presentation.auth.AuthScreen +import id.ac.ubharajaya.sistemakademik.presentation.auth.AuthViewModel +import id.ac.ubharajaya.sistemakademik.presentation.history.AttendanceHistoryScreen +import id.ac.ubharajaya.sistemakademik.presentation.history.AttendanceHistoryViewModel +import id.ac.ubharajaya.sistemakademik.ui.theme.SistemAkademikTheme +import java.util.concurrent.TimeUnit + +/* ================= ACTIVITY ================= */ + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + + // Initialize dependencies + val securePreferences = SecurePreferences(this) + val authRepository = AuthRepository(securePreferences) + val database = AppDatabase.getDatabase(this) + val attendanceDao = database.attendanceDao() + val n8nService = N8nService() + val attendanceRepository = AttendanceRepository(this, attendanceDao, n8nService) + + // Setup WorkManager for background sync + setupBackgroundSync() + + setContent { + SistemAkademikTheme { + // Navigation state + var currentScreen by remember { mutableStateOf("auth") } + var isLoggedIn by remember { mutableStateOf(authRepository.isLoggedIn()) } + + // Update current screen when login state changes + LaunchedEffect(isLoggedIn) { + currentScreen = if (isLoggedIn) "absensi" else "auth" + } + + Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> + when (currentScreen) { + "auth" -> { + // Halaman Login/Register + val authViewModel = remember { + AuthViewModel(authRepository) + } + + AuthScreen( + viewModel = authViewModel, + onLoginSuccess = { + isLoggedIn = true + currentScreen = "absensi" + }, + modifier = Modifier.padding(innerPadding) + ) + } + + "absensi" -> { + // Halaman Absensi + val absensiViewModel = remember { + AbsensiViewModel( + context = this@MainActivity, + attendanceRepository = attendanceRepository, + authRepository = authRepository + ) + } + + AbsensiScreen( + modifier = Modifier.padding(innerPadding), + viewModel = absensiViewModel, + onLogout = { + isLoggedIn = false + currentScreen = "auth" + }, + onNavigateToHistory = { + currentScreen = "history" + } + ) + } + + "history" -> { + // Halaman Riwayat Absensi + val historyViewModel = remember { + AttendanceHistoryViewModel(attendanceRepository) + } + + AttendanceHistoryScreen( + viewModel = historyViewModel, + onBackClick = { + currentScreen = "absensi" + }, + modifier = Modifier.padding(innerPadding) + ) + } + } + } + } + } + } + + private fun setupBackgroundSync() { + // Create periodic work request for syncing pending attendance + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val syncWorkRequest = PeriodicWorkRequestBuilder( + repeatInterval = 15, // Minimum interval is 15 minutes + repeatIntervalTimeUnit = TimeUnit.MINUTES + ) + .setConstraints(constraints) + .setBackoffCriteria( + BackoffPolicy.EXPONENTIAL, + WorkRequest.MIN_BACKOFF_MILLIS, + TimeUnit.MILLISECONDS + ) + .build() + + // Enqueue unique periodic work + WorkManager.getInstance(this).enqueueUniquePeriodicWork( + AttendanceSyncWorker.WORK_NAME, + ExistingPeriodicWorkPolicy.KEEP, + syncWorkRequest + ) + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/SecurePreferences.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/SecurePreferences.kt new file mode 100644 index 0000000..4efac9a --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/SecurePreferences.kt @@ -0,0 +1,84 @@ +package id.ac.ubharajaya.sistemakademik.data.local + +import android.content.Context +import android.content.SharedPreferences +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey + +/** + * Secure storage menggunakan Encrypted SharedPreferences + * untuk menyimpan credentials user secara terenkripsi + */ +class SecurePreferences(context: Context) { + + private val masterKey = MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build() + + private val sharedPreferences: SharedPreferences = EncryptedSharedPreferences.create( + context, + PREFS_NAME, + masterKey, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ) + + companion object { + private const val PREFS_NAME = "secure_auth_prefs" + private const val KEY_USERNAME = "username" + private const val KEY_PASSWORD = "password" + private const val KEY_IS_REGISTERED = "is_registered" + private const val KEY_IS_LOGIN = "is_login" + } + + // Simpan username + fun saveUsername(username: String) { + sharedPreferences.edit().putString(KEY_USERNAME, username).apply() + } + + // Simpan password (terenkripsi otomatis) + fun savePassword(password: String) { + sharedPreferences.edit().putString(KEY_PASSWORD, password).apply() + } + + // Get username + fun getUsername(): String? { + return sharedPreferences.getString(KEY_USERNAME, null) + } + + // Get password + fun getPassword(): String? { + return sharedPreferences.getString(KEY_PASSWORD, null) + } + + // Set flag registrasi + fun setRegistered(isRegistered: Boolean) { + sharedPreferences.edit().putBoolean(KEY_IS_REGISTERED, isRegistered).apply() + } + + // Cek apakah sudah terdaftar + fun isRegistered(): Boolean { + return sharedPreferences.getBoolean(KEY_IS_REGISTERED, false) + } + + // Set status login + fun setLogin(isLogin: Boolean) { + sharedPreferences.edit().putBoolean(KEY_IS_LOGIN, isLogin).apply() + } + + // Cek status login + fun isLogin(): Boolean { + return sharedPreferences.getBoolean(KEY_IS_LOGIN, false) + } + + // Logout - hapus status login tapi tetap simpan credentials + fun logout() { + sharedPreferences.edit().putBoolean(KEY_IS_LOGIN, false).apply() + } + + // Clear semua data (untuk reset aplikasi) + fun clearAll() { + sharedPreferences.edit().clear().apply() + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/dao/AttendanceDao.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/dao/AttendanceDao.kt new file mode 100644 index 0000000..bb818b5 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/dao/AttendanceDao.kt @@ -0,0 +1,34 @@ +package id.ac.ubharajaya.sistemakademik.data.local.dao + +import androidx.room.* +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceEntity +import kotlinx.coroutines.flow.Flow + +@Dao +interface AttendanceDao { + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertAttendance(attendance: AttendanceEntity) + + @Query("SELECT * FROM attendance_history ORDER BY dateTime DESC") + fun getAllAttendance(): Flow> + + @Query("SELECT * FROM attendance_history WHERE syncStatus = 'PENDING' ORDER BY dateTime ASC") + suspend fun getPendingAttendance(): List + + @Query("UPDATE attendance_history SET syncStatus = :status WHERE id = :attendanceId") + suspend fun updateSyncStatus(attendanceId: String, status: String) + + @Query("SELECT * FROM attendance_history WHERE id = :attendanceId") + suspend fun getAttendanceById(attendanceId: String): AttendanceEntity? + + @Query("DELETE FROM attendance_history WHERE id = :attendanceId") + suspend fun deleteAttendance(attendanceId: String) + + @Query("SELECT COUNT(*) FROM attendance_history") + suspend fun getAttendanceCount(): Int + + @Query("SELECT * FROM attendance_history WHERE studentId = :studentId ORDER BY dateTime DESC") + fun getAttendanceByStudent(studentId: String): Flow> +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/database/AppDatabase.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/database/AppDatabase.kt new file mode 100644 index 0000000..95c1e2d --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/database/AppDatabase.kt @@ -0,0 +1,38 @@ +package id.ac.ubharajaya.sistemakademik.data.local.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import id.ac.ubharajaya.sistemakademik.data.local.dao.AttendanceDao +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceEntity + +@Database( + entities = [AttendanceEntity::class], + version = 1, + exportSchema = false +) +abstract class AppDatabase : RoomDatabase() { + + abstract fun attendanceDao(): AttendanceDao + + companion object { + @Volatile + private var INSTANCE: AppDatabase? = null + + fun getDatabase(context: Context): AppDatabase { + return INSTANCE ?: synchronized(this) { + val instance = Room.databaseBuilder( + context.applicationContext, + AppDatabase::class.java, + "attendance_database" + ) + .fallbackToDestructiveMigration() + .build() + INSTANCE = instance + instance + } + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/entity/AttendanceEntity.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/entity/AttendanceEntity.kt new file mode 100644 index 0000000..ec0771f --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/local/entity/AttendanceEntity.kt @@ -0,0 +1,33 @@ +package id.ac.ubharajaya.sistemakademik.data.local.entity + +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "attendance_history") +data class AttendanceEntity( + @PrimaryKey + val id: String, // UUID + val studentId: String, // NPM + val studentName: String, // Nama + val courseName: String, // Mata Kuliah + val photoPath: String, // Path foto di internal storage + val dateTime: Long, // Timestamp + val latitude: Double, + val longitude: Double, + val locationName: String, // Nama lokasi (misal: "Gedung A") + val distanceMeter: Int, // Jarak dari titik kampus + val attendanceStatus: String, // SUCCESS | FAILED + val syncStatus: String, // PENDING | SYNCED + val createdAt: Long = System.currentTimeMillis() +) + +enum class AttendanceStatus { + SUCCESS, + FAILED +} + +enum class SyncStatus { + PENDING, + SYNCED +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/AbsensiData.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/AbsensiData.kt new file mode 100644 index 0000000..33e42d7 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/AbsensiData.kt @@ -0,0 +1,14 @@ +package id.ac.ubharajaya.sistemakademik.data.model + +import android.graphics.Bitmap + +data class AbsensiData( + val npm: String, + val nama: String, + val mataKuliah: String, + val latitude: Double, + val longitude: Double, + val timestamp: Long, + val foto: Bitmap +) + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/CampusPoint.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/CampusPoint.kt new file mode 100644 index 0000000..46a0f29 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/model/CampusPoint.kt @@ -0,0 +1,21 @@ +package id.ac.ubharajaya.sistemakademik.data.model + +/** + * Data class untuk merepresentasikan titik koordinat kampus + */ +data class CampusPoint( + val name: String, + val latitude: Double, + val longitude: Double +) + +/** + * Result dari validasi lokasi + */ +data class LocationValidationResult( + val isValid: Boolean, + val nearestPoint: CampusPoint, + val distanceInMeters: Float, + val message: String +) + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/ApiConfig.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/ApiConfig.kt new file mode 100644 index 0000000..80c1355 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/ApiConfig.kt @@ -0,0 +1,14 @@ +package id.ac.ubharajaya.sistemakademik.data.network + +object ApiConfig { + // Endpoint N8n - mudah diubah dari sini + const val N8N_WEBHOOK_URL = "https://n8n.lab.ubharajaya.ac.id/webhook/23c6993d-1792-48fb-ad1c-ffc78a3e6254" + + // Untuk testing, uncomment baris di bawah + // const val N8N_WEBHOOK_URL = "https://n8n.lab.ubharajaya.ac.id/webhook-test/23c6993d-1792-48fb-ad1c-ffc78a3e6254" + + // Timeout settings + const val CONNECTION_TIMEOUT = 30000 // 30 detik + const val READ_TIMEOUT = 30000 // 30 detik +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/N8nService.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/N8nService.kt new file mode 100644 index 0000000..6721859 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/network/N8nService.kt @@ -0,0 +1,48 @@ +package id.ac.ubharajaya.sistemakademik.data.network + +import id.ac.ubharajaya.sistemakademik.data.model.AbsensiData +import id.ac.ubharajaya.sistemakademik.utils.ImageUtils +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL + +class N8nService { + + suspend fun kirimAbsensi(data: AbsensiData): Result = withContext(Dispatchers.IO) { + try { + val url = URL(ApiConfig.N8N_WEBHOOK_URL) + val conn = url.openConnection() as HttpURLConnection + + conn.requestMethod = "POST" + conn.setRequestProperty("Content-Type", "application/json") + conn.doOutput = true + conn.connectTimeout = ApiConfig.CONNECTION_TIMEOUT + conn.readTimeout = ApiConfig.READ_TIMEOUT + + val json = JSONObject().apply { + put("npm", data.npm) + put("nama", data.nama) + put("mata_kuliah", data.mataKuliah) + put("latitude", data.latitude) + put("longitude", data.longitude) + put("timestamp", data.timestamp) + put("foto_base64", ImageUtils.bitmapToBase64(data.foto)) + } + + conn.outputStream.use { + it.write(json.toString().toByteArray()) + } + + val responseCode = conn.responseCode + conn.disconnect() + + Result.success(responseCode == 200) + + } catch (e: Exception) { + Result.failure(e) + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AbsensiRepository.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AbsensiRepository.kt new file mode 100644 index 0000000..7a03e8b --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AbsensiRepository.kt @@ -0,0 +1,14 @@ +package id.ac.ubharajaya.sistemakademik.data.repository + +import id.ac.ubharajaya.sistemakademik.data.model.AbsensiData +import id.ac.ubharajaya.sistemakademik.data.network.N8nService + +class AbsensiRepository( + private val n8nService: N8nService = N8nService() +) { + + suspend fun kirimAbsensi(data: AbsensiData): Result { + return n8nService.kirimAbsensi(data) + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AttendanceRepository.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AttendanceRepository.kt new file mode 100644 index 0000000..78a1c83 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AttendanceRepository.kt @@ -0,0 +1,152 @@ +package id.ac.ubharajaya.sistemakademik.data.repository + +import android.content.Context +import android.graphics.Bitmap +import android.util.Log +import id.ac.ubharajaya.sistemakademik.data.local.dao.AttendanceDao +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceEntity +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceStatus +import id.ac.ubharajaya.sistemakademik.data.local.entity.SyncStatus +import id.ac.ubharajaya.sistemakademik.data.model.AbsensiData +import id.ac.ubharajaya.sistemakademik.data.network.N8nService +import id.ac.ubharajaya.sistemakademik.utils.ImageUtils +import id.ac.ubharajaya.sistemakademik.utils.NetworkUtils +import kotlinx.coroutines.flow.Flow +import java.util.UUID + +class AttendanceRepository( + private val context: Context, + private val attendanceDao: AttendanceDao, + private val n8nService: N8nService +) { + + companion object { + private const val TAG = "AttendanceRepository" + } + + /** + * Submit attendance - Save to local DB first, then sync to backend if online + * This ensures no data loss even when offline + */ + suspend fun submitAttendance( + studentId: String, + studentName: String, + courseName: String, + photo: Bitmap, + latitude: Double, + longitude: Double, + locationName: String, + distanceMeter: Int, + isLocationValid: Boolean + ): Result { + return try { + val attendanceId = UUID.randomUUID().toString() + val timestamp = System.currentTimeMillis() + + // Save photo to internal storage + val photoPath = ImageUtils.saveBitmapToInternalStorage(context, photo, attendanceId) + + // Create attendance entity + val attendance = AttendanceEntity( + id = attendanceId, + studentId = studentId, + studentName = studentName, + courseName = courseName, + photoPath = photoPath, + dateTime = timestamp, + latitude = latitude, + longitude = longitude, + locationName = locationName, + distanceMeter = distanceMeter, + attendanceStatus = if (isLocationValid) AttendanceStatus.SUCCESS.name else AttendanceStatus.FAILED.name, + syncStatus = SyncStatus.PENDING.name, + createdAt = timestamp + ) + + // Save to local database (SINGLE SOURCE OF TRUTH) + attendanceDao.insertAttendance(attendance) + Log.d(TAG, "Attendance saved to local DB: $attendanceId") + + // Try to sync to backend if online + if (NetworkUtils.isNetworkAvailable(context)) { + Log.d(TAG, "Network available, attempting to sync...") + val syncResult = syncAttendanceToBackend(attendance) + + if (syncResult.isSuccess) { + // Update sync status to SYNCED + attendanceDao.updateSyncStatus(attendanceId, SyncStatus.SYNCED.name) + Log.d(TAG, "Attendance synced to backend successfully") + } else { + Log.w(TAG, "Failed to sync to backend, will retry later") + } + } else { + Log.d(TAG, "No network available, attendance will be synced later") + } + + Result.success(attendanceId) + + } catch (e: Exception) { + Log.e(TAG, "Error submitting attendance: ${e.message}", e) + Result.failure(e) + } + } + + /** + * Sync single attendance to backend (n8n webhook) + */ + suspend fun syncAttendanceToBackend(attendance: AttendanceEntity): Result { + return try { + // Load photo from storage + val photo = ImageUtils.loadBitmapFromInternalStorage(attendance.photoPath) + ?: return Result.failure(Exception("Photo not found")) + + // Create AbsensiData for n8n + val absensiData = AbsensiData( + npm = attendance.studentId, + nama = attendance.studentName, + mataKuliah = attendance.courseName, + latitude = attendance.latitude, + longitude = attendance.longitude, + timestamp = attendance.dateTime, + foto = photo + ) + + // Send to n8n webhook + val result = n8nService.kirimAbsensi(absensiData) + + if (result.isSuccess && result.getOrNull() == true) { + Log.d(TAG, "Successfully synced attendance ${attendance.id} to backend") + Result.success(true) + } else { + Log.e(TAG, "Failed to sync attendance ${attendance.id}: ${result.exceptionOrNull()?.message}") + Result.failure(result.exceptionOrNull() ?: Exception("Sync failed")) + } + + } catch (e: Exception) { + Log.e(TAG, "Error syncing to backend: ${e.message}", e) + Result.failure(e) + } + } + + /** + * Get all attendance history from local database + */ + fun getAllAttendance(): Flow> { + return attendanceDao.getAllAttendance() + } + + /** + * Get attendance for specific student + */ + fun getAttendanceByStudent(studentId: String): Flow> { + return attendanceDao.getAttendanceByStudent(studentId) + } + + /** + * Get pending attendance count + */ + suspend fun getPendingAttendanceCount(): Int { + return attendanceDao.getPendingAttendance().size + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AuthRepository.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AuthRepository.kt new file mode 100644 index 0000000..a93dc0e --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/AuthRepository.kt @@ -0,0 +1,90 @@ +package id.ac.ubharajaya.sistemakademik.data.repository + +import id.ac.ubharajaya.sistemakademik.data.local.SecurePreferences + +class AuthRepository( + private val securePreferences: SecurePreferences +) { + fun isRegistered(): Boolean { + return securePreferences.isRegistered() + } + fun isLoggedIn(): Boolean { + return securePreferences.isLogin() + } + + fun register(username: String, password: String): Result { + return try { + // Validasi input + if (username.isBlank() || password.isBlank()) { + return Result.failure(Exception("Username dan password tidak boleh kosong")) + } + + if (username.length < 3) { + return Result.failure(Exception("Username minimal 3 karakter")) + } + + if (password.length < 6) { + return Result.failure(Exception("Password minimal 6 karakter")) + } + + // Simpan credentials terenkripsi + securePreferences.saveUsername(username) + securePreferences.savePassword(password) + securePreferences.setRegistered(true) + securePreferences.setLogin(true) // Auto login setelah register + + Result.success(true) + } catch (e: Exception) { + Result.failure(e) + } + } + fun login(username: String, password: String): Result { + return try { + // Validasi input + if (username.isBlank() || password.isBlank()) { + return Result.failure(Exception("Username dan password tidak boleh kosong")) + } + + // Ambil credentials tersimpan + val savedUsername = securePreferences.getUsername() + val savedPassword = securePreferences.getPassword() + + // Validasi + if (savedUsername == null || savedPassword == null) { + return Result.failure(Exception("Akun tidak ditemukan")) + } + + if (username != savedUsername) { + return Result.failure(Exception("Username salah")) + } + + if (password != savedPassword) { + return Result.failure(Exception("Password salah")) + } + + // Login berhasil + securePreferences.setLogin(true) + Result.success(true) + + } catch (e: Exception) { + Result.failure(e) + } + } + + fun logout() { + securePreferences.logout() + } + + fun getCurrentUsername(): String? { + return if (isLoggedIn()) { + securePreferences.getUsername() + } else { + null + } + } + + fun resetApp() { + securePreferences.clearAll() + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/LocationRepository.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/LocationRepository.kt new file mode 100644 index 0000000..7045cde --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/repository/LocationRepository.kt @@ -0,0 +1,93 @@ +package id.ac.ubharajaya.sistemakademik.data.repository + +import android.location.Location +import id.ac.ubharajaya.sistemakademik.data.model.CampusPoint +import id.ac.ubharajaya.sistemakademik.data.model.LocationValidationResult + +class LocationRepository { + + companion object { + // Radius maksimum dalam meter untuk validasi lokasi + private const val MAX_RADIUS_METERS = 500f + private val CAMPUS_POINTS = listOf( + CampusPoint("Kampus Ubhara Jaya", -6.224158637147388, 107.00926807316523), + CampusPoint("Fakultas Ilmu Komputer", -6.2233250279671815, 107.00883769887214), + CampusPoint("Fakultas Ekonomi dan Bisnis", -6.223034072255051, 107.0087474389664), + CampusPoint("Lapangan Ubhara", -6.223098281906011, 107.00907009382797), + CampusPoint("Work Caffe Bekasi", -6.222959404241003, 107.00945173918328), + CampusPoint("Masjid Ulul Albab", -6.22282636356083, 107.00994136768242), + CampusPoint("Grha Tanoto", -6.223321153904385, 107.00974833692445), + CampusPoint("Perpustakaan Tanoto", -6.223445307823836, 107.00969434144955), + CampusPoint("Fakultas Psikologi", -6.223532666210009, 107.00915032451451), + CampusPoint("Sekretariat Kapal Baja", -6.223676072959635, 107.00914332180665), + CampusPoint("Ruang Sedang Semu Ubhara Jaya", -6.22369905775531, 107.00937898193018), + CampusPoint("ATM BRI Ubhara Jaya", -6.22388153867499, 107.0092023096524) + ) + } + private fun calculateDistance( + userLat: Double, + userLon: Double, + campusPoint: CampusPoint + ): Float { + val results = FloatArray(1) + Location.distanceBetween( + userLat, + userLon, + campusPoint.latitude, + campusPoint.longitude, + results + ) + return results[0] + } + + private fun findNearestCampusPoint( + userLat: Double, + userLon: Double + ): Pair { + var nearestPoint = CAMPUS_POINTS[0] + var minDistance = calculateDistance(userLat, userLon, nearestPoint) + + CAMPUS_POINTS.forEach { point -> + val distance = calculateDistance(userLat, userLon, point) + if (distance < minDistance) { + minDistance = distance + nearestPoint = point + } + } + + return Pair(nearestPoint, minDistance) + } + + /** + * Memvalidasi lokasi user apakah berada dalam radius kampus + * @param userLatitude Latitude user + * @param userLongitude Longitude user + * @return LocationValidationResult berisi hasil validasi + */ + fun validateLocation( + userLatitude: Double, + userLongitude: Double + ): LocationValidationResult { + val (nearestPoint, distance) = findNearestCampusPoint(userLatitude, userLongitude) + + val isValid = distance <= MAX_RADIUS_METERS + val message = if (isValid) { + "Anda berada di area ${nearestPoint.name} (${distance.toInt()}m)" + } else { + "Anda terlalu jauh dari ${nearestPoint.name} (${distance.toInt()}m). Maksimal ${MAX_RADIUS_METERS.toInt()}m" + } + + return LocationValidationResult( + isValid = isValid, + nearestPoint = nearestPoint, + distanceInMeters = distance, + message = message + ) + } + + /** + * Mendapatkan semua titik kampus (untuk keperluan debugging/info) + */ + fun getAllCampusPoints(): List = CAMPUS_POINTS +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/worker/AttendanceSyncWorker.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/worker/AttendanceSyncWorker.kt new file mode 100644 index 0000000..de98a9e --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/data/worker/AttendanceSyncWorker.kt @@ -0,0 +1,81 @@ +package id.ac.ubharajaya.sistemakademik.data.worker + +import android.content.Context +import android.util.Log +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import id.ac.ubharajaya.sistemakademik.data.local.database.AppDatabase +import id.ac.ubharajaya.sistemakademik.data.local.entity.SyncStatus +import id.ac.ubharajaya.sistemakademik.data.network.N8nService +import id.ac.ubharajaya.sistemakademik.data.repository.AttendanceRepository +import id.ac.ubharajaya.sistemakademik.utils.NetworkUtils + +class AttendanceSyncWorker( + context: Context, + params: WorkerParameters +) : CoroutineWorker(context, params) { + + companion object { + const val TAG = "AttendanceSyncWorker" + const val WORK_NAME = "attendance_sync_work" + } + + override suspend fun doWork(): Result { + Log.d(TAG, "Starting attendance sync...") + + // Check internet connection + if (!NetworkUtils.isNetworkAvailable(applicationContext)) { + Log.d(TAG, "No internet connection, skipping sync") + return Result.retry() + } + + return try { + val database = AppDatabase.getDatabase(applicationContext) + val attendanceDao = database.attendanceDao() + val n8nService = N8nService() + val repository = AttendanceRepository(applicationContext, attendanceDao, n8nService) + + // Get all pending attendance records + val pendingAttendances = attendanceDao.getPendingAttendance() + + if (pendingAttendances.isEmpty()) { + Log.d(TAG, "No pending attendance to sync") + return Result.success() + } + + Log.d(TAG, "Found ${pendingAttendances.size} pending attendance records") + + var successCount = 0 + var failCount = 0 + + // Sync each pending attendance + for (attendance in pendingAttendances) { + val result = repository.syncAttendanceToBackend(attendance) + + if (result.isSuccess) { + // Update sync status to SYNCED + attendanceDao.updateSyncStatus(attendance.id, SyncStatus.SYNCED.name) + successCount++ + Log.d(TAG, "Successfully synced attendance: ${attendance.id}") + } else { + failCount++ + Log.e(TAG, "Failed to sync attendance: ${attendance.id}") + } + } + + Log.d(TAG, "Sync completed: $successCount success, $failCount failed") + + // If all failed, retry later + if (successCount == 0 && failCount > 0) { + Result.retry() + } else { + Result.success() + } + + } catch (e: Exception) { + Log.e(TAG, "Error during sync: ${e.message}", e) + Result.retry() + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiScreen.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiScreen.kt new file mode 100644 index 0000000..4155acd --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiScreen.kt @@ -0,0 +1,744 @@ +package id.ac.ubharajaya.sistemakademik.presentation.absensi + +import android.Manifest +import android.app.Activity +import android.content.Intent +import android.content.pm.PackageManager +import android.graphics.Bitmap +import android.provider.MediaStore +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.Image +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.CameraAlt +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.LocationOn +import androidx.compose.material.icons.filled.Logout +import androidx.compose.material.icons.filled.Person +import androidx.compose.material.icons.filled.School +import androidx.compose.material.icons.filled.Send +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.google.android.gms.location.LocationServices + +@Composable +fun AbsensiScreen( + modifier: Modifier = Modifier, + viewModel: AbsensiViewModel, + onLogout: () -> Unit, + onNavigateToHistory: () -> Unit +) { + val context = LocalContext.current + val state by viewModel.state.collectAsStateWithLifecycle() + + val fusedLocationClient = remember { + LocationServices.getFusedLocationProviderClient(context) + } + + /* ===== Permission Lokasi ===== */ + + val locationPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + if (ContextCompat.checkSelfPermission( + context, + Manifest.permission.ACCESS_FINE_LOCATION + ) == PackageManager.PERMISSION_GRANTED + ) { + fusedLocationClient.lastLocation + .addOnSuccessListener { location -> + if (location != null) { + // Deteksi mock location (fake GPS) + val isMock = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { + location.isMock + } else { + @Suppress("DEPRECATION") + location.isFromMockProvider + } + + viewModel.updateLocation( + location.latitude, + location.longitude, + isMock + ) + + if (isMock) { + Toast.makeText( + context, + "⚠️ Fake GPS terdeteksi! Matikan aplikasi lokasi palsu", + Toast.LENGTH_LONG + ).show() + } + } else { + viewModel.updateLocationError("Lokasi tidak tersedia") + } + } + .addOnFailureListener { + viewModel.updateLocationError("Gagal mengambil lokasi") + } + } + } else { + Toast.makeText(context, "Izin lokasi ditolak", Toast.LENGTH_SHORT).show() + } + } + + /* ===== Kamera ===== */ + + val cameraLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { result -> + if (result.resultCode == Activity.RESULT_OK) { + @Suppress("DEPRECATION") + val bitmap = result.data?.extras?.get("data") as? Bitmap + if (bitmap != null) { + viewModel.updateFoto(bitmap) + Toast.makeText(context, "Foto berhasil diambil", Toast.LENGTH_SHORT).show() + } + } + } + + val cameraPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) + cameraLauncher.launch(intent) + } else { + Toast.makeText(context, "Izin kamera ditolak", Toast.LENGTH_SHORT).show() + } + } + + /* ===== Request Awal ===== */ + + LaunchedEffect(Unit) { + locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION) + } + + /* ===== Show Messages ===== */ + + LaunchedEffect(state.error, state.successMessage) { + state.error?.let { error -> + Toast.makeText(context, error, Toast.LENGTH_SHORT).show() + viewModel.clearMessages() + } + state.successMessage?.let { message -> + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + viewModel.clearMessages() + } + } + + /* ===== UI ===== */ + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + ) { + // Header dengan gradient-like background + Surface( + modifier = Modifier.fillMaxWidth(), + color = MaterialTheme.colorScheme.primaryContainer, + tonalElevation = 3.dp + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + imageVector = Icons.Filled.Person, + contentDescription = "User", + modifier = Modifier + .size(64.dp) + .clip(CircleShape) + .border( + width = 2.dp, + color = MaterialTheme.colorScheme.primary, + shape = CircleShape + ) + .padding(12.dp), + tint = MaterialTheme.colorScheme.primary + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Text( + text = state.nama.ifEmpty { "User" }, + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) + + if (state.npm.isNotEmpty()) { + Text( + text = "NPM: ${state.npm}", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f) + ) + } + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = "Sistem Absensi Akademik", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f) + ) + } + } + + // Content + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // Lokasi Card + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + colors = CardDefaults.cardColors( + containerColor = when { + state.isMockLocation -> MaterialTheme.colorScheme.errorContainer + state.isLocationValid -> MaterialTheme.colorScheme.primaryContainer + state.latitude != null && !state.isLocationValid -> MaterialTheme.colorScheme.errorContainer + else -> MaterialTheme.colorScheme.surface + } + ) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.LocationOn, + contentDescription = "Lokasi", + modifier = Modifier.size(40.dp), + tint = when { + state.isMockLocation -> MaterialTheme.colorScheme.error + state.isLocationValid -> MaterialTheme.colorScheme.primary + state.latitude != null && !state.isLocationValid -> MaterialTheme.colorScheme.error + else -> MaterialTheme.colorScheme.primary + } + ) + + Spacer(modifier = Modifier.width(16.dp)) + + Column(modifier = Modifier.weight(1f)) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Lokasi Anda", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = when { + state.isMockLocation -> MaterialTheme.colorScheme.onErrorContainer + state.isLocationValid -> MaterialTheme.colorScheme.onPrimaryContainer + state.latitude != null && !state.isLocationValid -> MaterialTheme.colorScheme.onErrorContainer + else -> MaterialTheme.colorScheme.onSurface + } + ) + Spacer(modifier = Modifier.width(8.dp)) + // Status indicator + when { + state.isMockLocation -> { + Text( + text = "⚠️ FAKE GPS", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error + ) + } + state.isLocationValid -> { + Text( + text = "✓ Valid", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) + } + state.latitude != null && !state.isLocationValid -> { + Text( + text = "✗ Terlalu Jauh", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error + ) + } + } + } + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = state.lokasi, + style = MaterialTheme.typography.bodyMedium, + color = when { + state.isMockLocation -> MaterialTheme.colorScheme.onErrorContainer + state.isLocationValid -> MaterialTheme.colorScheme.onPrimaryContainer + state.latitude != null && !state.isLocationValid -> MaterialTheme.colorScheme.onErrorContainer + else -> MaterialTheme.colorScheme.onSurfaceVariant + } + ) + } + } + } + + // Mata Kuliah Card + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.School, + contentDescription = "Mata Kuliah", + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = "Mata Kuliah", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Spacer(modifier = Modifier.height(12.dp)) + + // Dropdown Mata Kuliah + var expanded by remember { mutableStateOf(false) } + val mataKuliahOptions = listOf( + "Pemrograman Perangkat Lunak", + "Management Proyek Perangkat Lunak", + "Interaksi Manusia dan Komputer", + "Keamanan Siber", + "Management Sekuriti", + "Kecerdasan Buatan", + "Machine Learning", + ) + + Box( + modifier = Modifier.fillMaxWidth() + ) { + OutlinedTextField( + value = state.mataKuliah.ifEmpty { "Pilih Mata Kuliah" }, + onValueChange = {}, + readOnly = true, + label = { Text("Mata Kuliah") }, + trailingIcon = { + IconButton(onClick = { expanded = !expanded }) { + Icon( + imageVector = Icons.Filled.ArrowDropDown, + contentDescription = "Dropdown" + ) + } + }, + modifier = Modifier + .fillMaxWidth() + .clickable { expanded = !expanded }, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outline + ), + shape = RoundedCornerShape(8.dp) + ) + + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + modifier = Modifier.fillMaxWidth() + ) { + mataKuliahOptions.forEach { option -> + DropdownMenuItem( + text = { Text(option) }, + onClick = { + viewModel.updateMataKuliah(option) + expanded = false + } + ) + } + } + } + } + } + + // Foto Preview Card + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.CameraAlt, + contentDescription = "Foto", + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = "Foto Selfie", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + // Preview Foto atau Placeholder + if (state.foto != null) { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f) + .clip(RoundedCornerShape(12.dp)) + .border( + width = 2.dp, + color = MaterialTheme.colorScheme.primary, + shape = RoundedCornerShape(12.dp) + ) + ) { + state.foto?.let { foto -> + Image( + bitmap = foto.asImageBitmap(), + contentDescription = "Preview Foto", + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Crop + ) + } + } + + Spacer(modifier = Modifier.height(12.dp)) + + Text( + text = "✓ Foto berhasil diambil", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium + ) + } else { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f) + .clip(RoundedCornerShape(12.dp)) + .border( + width = 2.dp, + color = MaterialTheme.colorScheme.outline, + shape = RoundedCornerShape(12.dp) + ), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Icon( + imageVector = Icons.Filled.CameraAlt, + contentDescription = "Camera", + modifier = Modifier.size(64.dp), + tint = MaterialTheme.colorScheme.outline + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = "Belum ada foto", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // Tombol Ambil Foto + Button( + onClick = { + cameraPermissionLauncher.launch(Manifest.permission.CAMERA) + }, + modifier = Modifier.fillMaxWidth(), + enabled = !state.isLoading, + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Filled.CameraAlt, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = if (state.foto != null) "Ambil Ulang Foto" else "Ambil Foto", + style = MaterialTheme.typography.bodyLarge + ) + } + } + } + + // Tombol Kirim Absensi + Button( + onClick = { viewModel.kirimAbsensi() }, + modifier = Modifier + .fillMaxWidth() + .height(56.dp), + enabled = !state.isLoading + && state.foto != null + && state.latitude != null + && state.mataKuliah.isNotBlank() + && state.canSubmit + && state.isLocationValid + && !state.isMockLocation, + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary, + disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant + ) + ) { + if (state.isLoading) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + color = MaterialTheme.colorScheme.onPrimary, + strokeWidth = 2.dp + ) + Spacer(modifier = Modifier.width(12.dp)) + Text("Mengirim...") + } else { + Icon( + imageVector = Icons.Filled.Send, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "Kirim Absensi", + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold + ) + } + } + + // Info Helper Text + if (state.foto == null || state.latitude == null || state.mataKuliah.isBlank() || !state.isLocationValid || state.isMockLocation) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = if (state.isMockLocation || (!state.isLocationValid && state.latitude != null)) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.secondaryContainer + } + ) + ) { + Column( + modifier = Modifier.padding(12.dp) + ) { + if (state.isMockLocation) { + Text( + text = "⚠️ Fake GPS Terdeteksi!", + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.titleSmall + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Matikan aplikasi lokasi palsu untuk melanjutkan absensi", + color = MaterialTheme.colorScheme.onErrorContainer, + style = MaterialTheme.typography.bodySmall + ) + } else if (!state.isLocationValid && state.latitude != null) { + Text( + text = "❌ Lokasi Tidak Valid", + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.titleSmall + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = state.locationValidation?.message + ?: "Anda berada di luar area kampus (maksimal 500 meter dari titik kampus)", + color = MaterialTheme.colorScheme.onErrorContainer, + style = MaterialTheme.typography.bodySmall + ) + } else { + Text( + text = "ℹ️ Pastikan semua persyaratan terpenuhi:", + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.bodyMedium + ) + Spacer(modifier = Modifier.height(8.dp)) + + val requirements = listOf( + "Mata kuliah dipilih" to state.mataKuliah.isNotBlank(), + "Lokasi valid (dalam radius 500m)" to state.isLocationValid, + "Foto selfie diambil" to (state.foto != null), + "Tidak menggunakan fake GPS" to !state.isMockLocation + ) + + requirements.forEach { (text, fulfilled) -> + Row( + modifier = Modifier.padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = if (fulfilled) "✓" else "○", + color = if (fulfilled) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSecondaryContainer + }, + fontWeight = FontWeight.Bold, + modifier = Modifier.width(24.dp) + ) + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + } + } + } + } + } + } else if (!state.canSubmit) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer + ) + ) { + Text( + text = "⚠️ Absensi sudah terkirim. Ambil foto baru untuk absensi berikutnya.", + modifier = Modifier.padding(12.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + textAlign = TextAlign.Center, + fontWeight = FontWeight.Medium + ) + } + } + + // Anti-Spam Warning + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.tertiaryContainer + ) + ) { + Column( + modifier = Modifier.padding(12.dp) + ) { + Text( + text = "🛡️ Sistem Anti-Spam Aktif", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onTertiaryContainer, + fontWeight = FontWeight.Bold + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "• Satu foto hanya untuk satu absensi\n• Foto akan di-reset setelah berhasil kirim\n• Cooldown 5 menit antara absensi", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onTertiaryContainer + ) + } + } + + Spacer(modifier = Modifier.height(8.dp)) + + // Tombol Riwayat Absensi + OutlinedButton( + onClick = onNavigateToHistory, + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.outlinedButtonColors( + contentColor = MaterialTheme.colorScheme.primary + ) + ) { + Icon( + imageVector = Icons.Filled.History, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text("Lihat Riwayat Absensi") + } + + Spacer(modifier = Modifier.height(8.dp)) + + // Tombol Logout + OutlinedButton( + onClick = { + viewModel.logout() + onLogout() + }, + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.outlinedButtonColors( + contentColor = MaterialTheme.colorScheme.error + ) + ) { + Icon( + imageVector = Icons.Filled.Logout, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text("Logout") + } + + // Bottom Spacing + Spacer(modifier = Modifier.height(16.dp)) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiState.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiState.kt new file mode 100644 index 0000000..820b2a4 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiState.kt @@ -0,0 +1,24 @@ +package id.ac.ubharajaya.sistemakademik.presentation.absensi + +import android.graphics.Bitmap +import id.ac.ubharajaya.sistemakademik.data.model.LocationValidationResult + +data class AbsensiState( + val npm: String = "", + val nama: String = "", + val mataKuliah: String = "", + val lokasi: String = "Koordinat: -", + val latitude: Double? = null, + val longitude: Double? = null, + val foto: Bitmap? = null, + val isLoading: Boolean = false, + val error: String? = null, + val successMessage: String? = null, + val lastSubmitTime: Long = 0L, + val canSubmit: Boolean = true, + // Location validation + val locationValidation: LocationValidationResult? = null, + val isLocationValid: Boolean = false, + val isMockLocation: Boolean = false +) + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiViewModel.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiViewModel.kt new file mode 100644 index 0000000..6730b43 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/absensi/AbsensiViewModel.kt @@ -0,0 +1,195 @@ +package id.ac.ubharajaya.sistemakademik.presentation.absensi + +import android.content.Context +import android.graphics.Bitmap +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import id.ac.ubharajaya.sistemakademik.data.repository.AttendanceRepository +import id.ac.ubharajaya.sistemakademik.data.repository.AuthRepository +import id.ac.ubharajaya.sistemakademik.data.repository.LocationRepository +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +class AbsensiViewModel( + private val context: Context, + private val attendanceRepository: AttendanceRepository, + private val authRepository: AuthRepository, + private val locationRepository: LocationRepository = LocationRepository() +) : ViewModel() { + + companion object { + private const val FIXED_NPM = "202310715083" + private const val FIXED_NAMA = "Rakha Adi Saputro" + + // Cooldown 5 menit (300000 ms) antara absensi + private const val COOLDOWN_TIME_MS = 300000L // 5 menit + // Untuk testing bisa diubah jadi lebih kecil: + // private const val COOLDOWN_TIME_MS = 30000L // 30 detik + } + + private val _state = MutableStateFlow(AbsensiState()) + val state: StateFlow = _state.asStateFlow() + + init { + loadUserInfo() + } + + private fun loadUserInfo() { + // Set NPM dan Nama yang sudah fixed + _state.update { + it.copy( + npm = FIXED_NPM, + nama = FIXED_NAMA + ) + } + } + + fun updateLocation(latitude: Double, longitude: Double, isMock: Boolean = false) { + // Validasi lokasi + val validation = locationRepository.validateLocation(latitude, longitude) + + val locationText = if (validation.isValid) { + "${validation.nearestPoint.name}\n${validation.distanceInMeters.toInt()}m dari titik pusat" + } else { + validation.message + } + + _state.update { + it.copy( + latitude = latitude, + longitude = longitude, + lokasi = locationText, + locationValidation = validation, + isLocationValid = validation.isValid, + isMockLocation = isMock + ) + } + } + + fun updateLocationError(message: String) { + _state.update { + it.copy(lokasi = message) + } + } + + fun updateFoto(foto: Bitmap) { + _state.update { + it.copy( + foto = foto, + canSubmit = true // Enable submit button saat foto baru diambil + ) + } + } + + fun updateMataKuliah(mataKuliah: String) { + _state.update { + it.copy(mataKuliah = mataKuliah) + } + } + + fun kirimAbsensi() { + val currentState = _state.value + val currentTime = System.currentTimeMillis() + + // Validasi data lengkap + if (currentState.latitude == null || currentState.longitude == null || currentState.foto == null) { + _state.update { + it.copy(error = "Lokasi atau foto belum lengkap") + } + return + } + + // Validasi mata kuliah + if (currentState.mataKuliah.isBlank()) { + _state.update { + it.copy(error = "Pilih mata kuliah terlebih dahulu") + } + return + } + + // Validasi mock location (fake GPS) + if (currentState.isMockLocation) { + _state.update { + it.copy(error = "Fake GPS terdeteksi! Matikan aplikasi lokasi palsu") + } + return + } + + // Validasi lokasi - harus berada dalam radius kampus + if (!currentState.isLocationValid) { + _state.update { + it.copy( + error = currentState.locationValidation?.message + ?: "Anda berada di luar area kampus" + ) + } + return + } + + // Validasi cooldown - cegah spam absensi + val timeSinceLastSubmit = currentTime - currentState.lastSubmitTime + if (currentState.lastSubmitTime > 0 && timeSinceLastSubmit < COOLDOWN_TIME_MS) { + val remainingSeconds = ((COOLDOWN_TIME_MS - timeSinceLastSubmit) / 1000).toInt() + val remainingMinutes = remainingSeconds / 60 + val seconds = remainingSeconds % 60 + + _state.update { + it.copy( + error = "Tunggu ${remainingMinutes}:${seconds.toString().padStart(2, '0')} untuk absensi berikutnya" + ) + } + return + } + + viewModelScope.launch { + _state.update { it.copy(isLoading = true) } + + val result = attendanceRepository.submitAttendance( + studentId = currentState.npm, + studentName = currentState.nama, + courseName = currentState.mataKuliah, + photo = currentState.foto!!, + latitude = currentState.latitude!!, + longitude = currentState.longitude!!, + locationName = currentState.locationValidation?.nearestPoint?.name ?: "Unknown", + distanceMeter = currentState.locationValidation?.distanceInMeters?.toInt() ?: 0, + isLocationValid = currentState.isLocationValid + ) + + if (result.isSuccess) { + _state.update { + it.copy( + isLoading = false, + successMessage = "Absensi berhasil disimpan", + error = null, + foto = null, // Reset foto setelah berhasil + lastSubmitTime = currentTime, + canSubmit = false + ) + } + } else { + _state.update { + it.copy( + isLoading = false, + error = "Gagal menyimpan absensi: ${result.exceptionOrNull()?.message}", + successMessage = null + ) + } + } + } + } + + fun logout() { + authRepository.logout() + } + + fun clearMessages() { + _state.update { + it.copy(error = null, successMessage = null) + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthScreen.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthScreen.kt new file mode 100644 index 0000000..e8fb5b7 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthScreen.kt @@ -0,0 +1,212 @@ +package id.ac.ubharajaya.sistemakademik.presentation.auth + +import android.widget.Toast +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Visibility +import androidx.compose.material.icons.filled.VisibilityOff +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle + +@Composable +fun AuthScreen( + viewModel: AuthViewModel, + onLoginSuccess: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val state by viewModel.state.collectAsStateWithLifecycle() + + // Show error toast + LaunchedEffect(state.error) { + state.error?.let { error -> + Toast.makeText(context, error, Toast.LENGTH_SHORT).show() + viewModel.clearError() + } + } + + // Navigate jika login berhasil + LaunchedEffect(state.isLoggedIn) { + if (state.isLoggedIn) { + onLoginSuccess() + } + } + + Surface( + modifier = modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background + ) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + // Header + Text( + text = if (state.isRegistered) "Login" else "Buat Akun", + style = MaterialTheme.typography.headlineLarge, + color = MaterialTheme.colorScheme.primary + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = if (state.isRegistered) + "Masukkan username dan password Anda" + else + "Buat username dan password baru", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(32.dp)) + + // Username Field + OutlinedTextField( + value = state.username, + onValueChange = { viewModel.updateUsername(it) }, + label = { Text("Username") }, + placeholder = { Text("Minimal 3 karakter") }, + singleLine = true, + enabled = !state.isLoading, + modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text) + ) + + Spacer(modifier = Modifier.height(16.dp)) + + // Password Field + OutlinedTextField( + value = state.password, + onValueChange = { viewModel.updatePassword(it) }, + label = { Text("Password") }, + placeholder = { Text("Minimal 6 karakter") }, + singleLine = true, + enabled = !state.isLoading, + visualTransformation = if (state.passwordVisible) + VisualTransformation.None + else + PasswordVisualTransformation(), + trailingIcon = { + IconButton(onClick = { viewModel.togglePasswordVisibility() }) { + Icon( + imageVector = if (state.passwordVisible) + Icons.Filled.Visibility + else + Icons.Filled.VisibilityOff, + contentDescription = if (state.passwordVisible) + "Hide password" + else + "Show password" + ) + } + }, + modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) + ) + + // Confirm Password Field (hanya untuk register) + if (!state.isRegistered) { + Spacer(modifier = Modifier.height(16.dp)) + + OutlinedTextField( + value = state.confirmPassword, + onValueChange = { viewModel.updateConfirmPassword(it) }, + label = { Text("Konfirmasi Password") }, + placeholder = { Text("Ulangi password") }, + singleLine = true, + enabled = !state.isLoading, + visualTransformation = if (state.confirmPasswordVisible) + VisualTransformation.None + else + PasswordVisualTransformation(), + trailingIcon = { + IconButton(onClick = { viewModel.toggleConfirmPasswordVisibility() }) { + Icon( + imageVector = if (state.confirmPasswordVisible) + Icons.Filled.Visibility + else + Icons.Filled.VisibilityOff, + contentDescription = if (state.confirmPasswordVisible) + "Hide password" + else + "Show password" + ) + } + }, + modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) + ) + } + + Spacer(modifier = Modifier.height(32.dp)) + + // Submit Button + Button( + onClick = { + if (state.isRegistered) { + viewModel.login() + } else { + viewModel.register() + } + }, + enabled = !state.isLoading, + modifier = Modifier + .fillMaxWidth() + .height(56.dp) + ) { + if (state.isLoading) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + color = MaterialTheme.colorScheme.onPrimary + ) + } else { + Text( + text = if (state.isRegistered) "Login" else "Buat Akun", + style = MaterialTheme.typography.bodyLarge + ) + } + } + + // Info text untuk first-time setup + if (!state.isRegistered) { + Spacer(modifier = Modifier.height(16.dp)) + + Card( + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer + ) + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + Text( + text = "ℹ️ First-Time Setup", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Buat username dan password untuk login selanjutnya. " + + "Data akan disimpan secara terenkripsi di perangkat ini.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + } + } + } + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthState.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthState.kt new file mode 100644 index 0000000..80f0eea --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthState.kt @@ -0,0 +1,17 @@ +package id.ac.ubharajaya.sistemakademik.presentation.auth + +/** + * State untuk UI Login/Register + */ +data class AuthState( + val username: String = "", + val password: String = "", + val confirmPassword: String = "", + val isLoading: Boolean = false, + val error: String? = null, + val isRegistered: Boolean = false, + val isLoggedIn: Boolean = false, + val passwordVisible: Boolean = false, + val confirmPasswordVisible: Boolean = false +) + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthViewModel.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthViewModel.kt new file mode 100644 index 0000000..a038cbc --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/auth/AuthViewModel.kt @@ -0,0 +1,174 @@ +package id.ac.ubharajaya.sistemakademik.presentation.auth + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import id.ac.ubharajaya.sistemakademik.data.repository.AuthRepository +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * ViewModel untuk Login/Register + * Menangani logic autentikasi dengan Encrypted SharedPreferences + */ +class AuthViewModel( + private val authRepository: AuthRepository +) : ViewModel() { + + private val _state = MutableStateFlow(AuthState()) + val state: StateFlow = _state.asStateFlow() + + init { + checkAuthStatus() + } + + /** + * Cek status autentikasi saat init + */ + private fun checkAuthStatus() { + _state.update { + it.copy( + isRegistered = authRepository.isRegistered(), + isLoggedIn = authRepository.isLoggedIn() + ) + } + } + + /** + * Update username input + */ + fun updateUsername(username: String) { + _state.update { it.copy(username = username) } + } + + /** + * Update password input + */ + fun updatePassword(password: String) { + _state.update { it.copy(password = password) } + } + + /** + * Update confirm password input (untuk register) + */ + fun updateConfirmPassword(confirmPassword: String) { + _state.update { it.copy(confirmPassword = confirmPassword) } + } + + /** + * Toggle visibility password + */ + fun togglePasswordVisibility() { + _state.update { it.copy(passwordVisible = !it.passwordVisible) } + } + + /** + * Toggle visibility confirm password + */ + fun toggleConfirmPasswordVisibility() { + _state.update { it.copy(confirmPasswordVisible = !it.confirmPasswordVisible) } + } + + /** + * Register user baru (first-time setup) + */ + fun register() { + val currentState = _state.value + + // Validasi confirm password + if (currentState.password != currentState.confirmPassword) { + _state.update { it.copy(error = "Password tidak sama") } + return + } + + viewModelScope.launch { + _state.update { it.copy(isLoading = true, error = null) } + + authRepository.register(currentState.username, currentState.password) + .onSuccess { + _state.update { + it.copy( + isLoading = false, + isRegistered = true, + isLoggedIn = true, + error = null + ) + } + } + .onFailure { exception -> + _state.update { + it.copy( + isLoading = false, + error = exception.message + ) + } + } + } + } + + /** + * Login user dengan validasi credentials + */ + fun login() { + val currentState = _state.value + + viewModelScope.launch { + _state.update { it.copy(isLoading = true, error = null) } + + authRepository.login(currentState.username, currentState.password) + .onSuccess { + _state.update { + it.copy( + isLoading = false, + isLoggedIn = true, + error = null + ) + } + } + .onFailure { exception -> + _state.update { + it.copy( + isLoading = false, + error = exception.message + ) + } + } + } + } + + /** + * Logout user + */ + fun logout() { + authRepository.logout() + _state.update { + it.copy( + isLoggedIn = false, + username = "", + password = "", + confirmPassword = "" + ) + } + } + + /** + * Clear error message + */ + fun clearError() { + _state.update { it.copy(error = null) } + } + + /** + * Reset aplikasi (hapus semua data) + * Hanya untuk development/testing + */ + fun resetApp() { + authRepository.resetApp() + _state.update { + AuthState() + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryScreen.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryScreen.kt new file mode 100644 index 0000000..c7fd8bf --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryScreen.kt @@ -0,0 +1,334 @@ +package id.ac.ubharajaya.sistemakademik.presentation.history + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import coil.compose.AsyncImage +import coil.request.ImageRequest +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceEntity +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceStatus +import id.ac.ubharajaya.sistemakademik.data.local.entity.SyncStatus +import java.io.File + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AttendanceHistoryScreen( + viewModel: AttendanceHistoryViewModel, + onBackClick: () -> Unit, + modifier: Modifier = Modifier +) { + val state by viewModel.state.collectAsStateWithLifecycle() + + Scaffold( + topBar = { + TopAppBar( + title = { + Column { + Text( + text = "Riwayat Absensi", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + if (state.pendingCount > 0) { + Text( + text = "${state.pendingCount} data belum tersinkron", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + } + }, + navigationIcon = { + IconButton(onClick = onBackClick) { + Icon( + imageVector = Icons.Filled.ArrowBack, + contentDescription = "Kembali" + ) + } + }, + actions = { + IconButton(onClick = { viewModel.refreshHistory() }) { + Icon( + imageVector = Icons.Filled.Refresh, + contentDescription = "Refresh" + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + ) + }, + modifier = modifier.fillMaxSize() + ) { innerPadding -> + + if (state.isLoading) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator() + } + } else if (state.attendanceList.isEmpty()) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Icon( + imageVector = Icons.Filled.EventBusy, + contentDescription = null, + modifier = Modifier.size(64.dp), + tint = MaterialTheme.colorScheme.outline + ) + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = "Belum ada riwayat absensi", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + items(state.attendanceList, key = { it.id }) { attendance -> + AttendanceHistoryCard( + attendance = attendance, + viewModel = viewModel + ) + } + } + } + } +} + +@Composable +fun AttendanceHistoryCard( + attendance: AttendanceEntity, + viewModel: AttendanceHistoryViewModel, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val isSuccess = attendance.attendanceStatus == AttendanceStatus.SUCCESS.name + val isSynced = attendance.syncStatus == SyncStatus.SYNCED.name + + Card( + modifier = modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 3.dp), + colors = CardDefaults.cardColors( + containerColor = if (isSuccess) { + MaterialTheme.colorScheme.surface + } else { + MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.3f) + } + ), + shape = RoundedCornerShape(12.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + ) { + // Photo thumbnail + val photoFile = File(attendance.photoPath) + AsyncImage( + model = ImageRequest.Builder(context) + .data(photoFile) + .crossfade(true) + .build(), + contentDescription = "Foto Absensi", + modifier = Modifier + .size(80.dp) + .clip(RoundedCornerShape(8.dp)) + .border( + width = 2.dp, + color = if (isSuccess) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error, + shape = RoundedCornerShape(8.dp) + ), + contentScale = ContentScale.Crop + ) + + Spacer(modifier = Modifier.width(12.dp)) + + // Attendance details + Column( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + verticalArrangement = Arrangement.SpaceBetween + ) { + // Course name + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.School, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = attendance.courseName, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + // Date & Time + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.AccessTime, + contentDescription = null, + modifier = Modifier.size(14.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = viewModel.formatDateTime(attendance.dateTime), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + // Location + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.LocationOn, + contentDescription = null, + modifier = Modifier.size(14.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = "${attendance.locationName} (${attendance.distanceMeter}m)", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + Spacer(modifier = Modifier.height(8.dp)) + + // Status badges + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + // Attendance status badge + AttendanceStatusBadge(isSuccess = isSuccess) + + // Sync status badge + SyncStatusBadge(isSynced = isSynced) + } + } + } + } +} + +@Composable +fun AttendanceStatusBadge(isSuccess: Boolean) { + Surface( + color = if (isSuccess) { + Color(0xFF4CAF50).copy(alpha = 0.15f) + } else { + MaterialTheme.colorScheme.error.copy(alpha = 0.15f) + }, + shape = RoundedCornerShape(4.dp) + ) { + Row( + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = if (isSuccess) Icons.Filled.CheckCircle else Icons.Filled.Cancel, + contentDescription = null, + modifier = Modifier.size(12.dp), + tint = if (isSuccess) Color(0xFF4CAF50) else MaterialTheme.colorScheme.error + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = if (isSuccess) "Berhasil" else "Gagal", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = if (isSuccess) Color(0xFF4CAF50) else MaterialTheme.colorScheme.error + ) + } + } +} + +@Composable +fun SyncStatusBadge(isSynced: Boolean) { + Surface( + color = if (isSynced) { + Color(0xFF2196F3).copy(alpha = 0.15f) + } else { + Color(0xFFFF9800).copy(alpha = 0.15f) + }, + shape = RoundedCornerShape(4.dp) + ) { + Row( + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = if (isSynced) Icons.Filled.CloudDone else Icons.Filled.CloudQueue, + contentDescription = null, + modifier = Modifier.size(12.dp), + tint = if (isSynced) Color(0xFF2196F3) else Color(0xFFFF9800) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = if (isSynced) "Tersinkron" else "Pending", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = if (isSynced) Color(0xFF2196F3) else Color(0xFFFF9800) + ) + } + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryViewModel.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryViewModel.kt new file mode 100644 index 0000000..19aec24 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/presentation/history/AttendanceHistoryViewModel.kt @@ -0,0 +1,85 @@ +package id.ac.ubharajaya.sistemakademik.presentation.history + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import id.ac.ubharajaya.sistemakademik.data.local.entity.AttendanceEntity +import id.ac.ubharajaya.sistemakademik.data.repository.AttendanceRepository +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import java.text.SimpleDateFormat +import java.util.* + +data class AttendanceHistoryState( + val attendanceList: List = emptyList(), + val isLoading: Boolean = false, + val error: String? = null, + val pendingCount: Int = 0 +) + +class AttendanceHistoryViewModel( + private val repository: AttendanceRepository +) : ViewModel() { + + private val _state = MutableStateFlow(AttendanceHistoryState()) + val state: StateFlow = _state.asStateFlow() + + init { + loadAttendanceHistory() + loadPendingCount() + } + + private fun loadAttendanceHistory() { + viewModelScope.launch { + _state.value = _state.value.copy(isLoading = true) + + try { + repository.getAllAttendance().collect { attendanceList -> + _state.value = _state.value.copy( + attendanceList = attendanceList, + isLoading = false, + error = null + ) + } + } catch (e: Exception) { + _state.value = _state.value.copy( + isLoading = false, + error = "Gagal memuat riwayat: ${e.message}" + ) + } + } + } + + private fun loadPendingCount() { + viewModelScope.launch { + try { + val count = repository.getPendingAttendanceCount() + _state.value = _state.value.copy(pendingCount = count) + } catch (e: Exception) { + // Ignore error for pending count + } + } + } + + fun refreshHistory() { + loadAttendanceHistory() + loadPendingCount() + } + + fun formatDateTime(timestamp: Long): String { + val sdf = SimpleDateFormat("dd MMM yyyy, HH:mm", Locale("id", "ID")) + return sdf.format(Date(timestamp)) + } + + fun formatDate(timestamp: Long): String { + val sdf = SimpleDateFormat("dd MMM yyyy", Locale("id", "ID")) + return sdf.format(Date(timestamp)) + } + + fun formatTime(timestamp: Long): String { + val sdf = SimpleDateFormat("HH:mm", Locale("id", "ID")) + return sdf.format(Date(timestamp)) + } +} + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Color.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Color.kt new file mode 100644 index 0000000..c75702c --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Color.kt @@ -0,0 +1,11 @@ +package id.ac.ubharajaya.sistemakademik.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Theme.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Theme.kt new file mode 100644 index 0000000..1b2db88 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Theme.kt @@ -0,0 +1,58 @@ +package id.ac.ubharajaya.sistemakademik.ui.theme + +import android.app.Activity +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalContext + +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80 +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40 + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun SistemAkademikTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} \ No newline at end of file diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Type.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Type.kt new file mode 100644 index 0000000..e2982e7 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package id.ac.ubharajaya.sistemakademik.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/ImageUtils.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/ImageUtils.kt new file mode 100644 index 0000000..4dff558 --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/ImageUtils.kt @@ -0,0 +1,64 @@ +package id.ac.ubharajaya.sistemakademik.utils + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.util.Base64 +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.util.* + +object ImageUtils { + fun bitmapToBase64(bitmap: Bitmap): String { + val outputStream = ByteArrayOutputStream() + bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream) + return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP) + } + + /** + * Save bitmap to internal storage and return file path + */ + fun saveBitmapToInternalStorage(context: Context, bitmap: Bitmap, filename: String = UUID.randomUUID().toString()): String { + val directory = File(context.filesDir, "attendance_photos") + if (!directory.exists()) { + directory.mkdirs() + } + + val file = File(directory, "$filename.jpg") + FileOutputStream(file).use { out -> + bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out) + } + + return file.absolutePath + } + + /** + * Load bitmap from internal storage + */ + fun loadBitmapFromInternalStorage(path: String): Bitmap? { + return try { + BitmapFactory.decodeFile(path) + } catch (e: Exception) { + null + } + } + + /** + * Delete image file from internal storage + */ + fun deleteImageFile(path: String): Boolean { + return try { + val file = File(path) + if (file.exists()) { + file.delete() + } else { + false + } + } catch (e: Exception) { + false + } + } +} + + diff --git a/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/NetworkUtils.kt b/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/NetworkUtils.kt new file mode 100644 index 0000000..c647edf --- /dev/null +++ b/app/src/main/java/id/ac/ubharajaya/sistemakademik/utils/NetworkUtils.kt @@ -0,0 +1,28 @@ +package id.ac.ubharajaya.sistemakademik.utils + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Build + +object NetworkUtils { + + fun isNetworkAvailable(context: Context): Boolean { + val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + val network = connectivityManager.activeNetwork ?: return false + val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false + + return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) + } else { + @Suppress("DEPRECATION") + val networkInfo = connectivityManager.activeNetworkInfo + @Suppress("DEPRECATION") + return networkInfo != null && networkInfo.isConnected + } + } +} + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..de92dbc --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Sistem Akademik + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..d515270 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +