Fix notification delivery and settings flows

This commit is contained in:
Dwindi Ramadhana
2026-05-31 20:40:20 +07:00
parent 5195ba19ad
commit 2bd8e3666a
12 changed files with 1419 additions and 435 deletions

View File

@@ -54,6 +54,19 @@
<action android:name="android.intent.action.MEDIA_BUTTON" /> <action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver"
android:exported="false" />
<receiver
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application> </application>
<!-- Required to query activities that can process text, see: <!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and https://developer.android.com/training/package-visibility and

View File

@@ -1,6 +1,7 @@
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart' as geocoding; import 'package:geocoding/geocoding.dart' as geocoding;
import 'package:hive_flutter/hive_flutter.dart'; import 'package:hive_flutter/hive_flutter.dart';
import 'myquran_sholat_service.dart';
import '../local/hive_boxes.dart'; import '../local/hive_boxes.dart';
import '../local/models/app_settings.dart'; import '../local/models/app_settings.dart';
@@ -39,14 +40,13 @@ class LocationService {
} }
/// Get last known location from Hive settings. /// Get last known location from Hive settings.
({double lat, double lng, String? cityName})? getLastKnownLocation() { ({double lat, double lng})? getLastKnownLocation() {
final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings); final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
final settings = settingsBox.get('default'); final settings = settingsBox.get('default');
if (settings?.lastLat != null && settings?.lastLng != null) { if (settings?.lastLat != null && settings?.lastLng != null) {
return ( return (
lat: settings!.lastLat!, lat: settings!.lastLat!,
lng: settings.lastLng!, lng: settings.lastLng!,
cityName: settings.lastCityName,
); );
} }
return null; return null;
@@ -68,6 +68,93 @@ class LocationService {
return '${lat.toStringAsFixed(2)}, ${lng.toStringAsFixed(2)}'; return '${lat.toStringAsFixed(2)}, ${lng.toStringAsFixed(2)}';
} }
Future<({String id, String name})?> resolveMyQuranCityFromPosition(
Position position) async {
return resolveMyQuranCityFromCoordinates(
lat: position.latitude,
lng: position.longitude,
);
}
Future<({String id, String name})?> resolveMyQuranCityFromCoordinates({
required double lat,
required double lng,
}) async {
try {
final placemarks = await geocoding.placemarkFromCoordinates(
lat,
lng,
);
final place = placemarks.isNotEmpty ? placemarks.first : null;
final candidates = <String>{
if (place?.locality?.trim().isNotEmpty == true) place!.locality!.trim(),
if (place?.subAdministrativeArea?.trim().isNotEmpty == true)
place!.subAdministrativeArea!.trim(),
if (place?.administrativeArea?.trim().isNotEmpty == true)
place!.administrativeArea!.trim(),
};
if (candidates.isEmpty) {
final label = await getCityName(lat, lng);
final fallback = label.split(',').first.trim();
if (fallback.isNotEmpty) candidates.add(fallback);
}
Map<String, dynamic>? best;
var bestScore = -1;
for (final raw in candidates) {
final normalizedQuery = _normalizeCityToken(raw);
if (normalizedQuery.isEmpty) continue;
final found = await MyQuranSholatService.instance.searchCity(raw);
for (final entry in found) {
final id = (entry['id'] ?? '').toString().trim();
final name = (entry['lokasi'] ?? '').toString().trim();
if (id.isEmpty || name.isEmpty) continue;
final score = _cityMatchScore(normalizedQuery, name);
if (score > bestScore) {
bestScore = score;
best = {'id': id, 'name': name};
}
}
}
if (best != null && bestScore >= 40) {
return (id: best['id'] as String, name: best['name'] as String);
}
return null;
} catch (_) {
return null;
}
}
String _normalizeCityToken(String input) {
var value = input.toLowerCase().trim();
value = value.replaceAll(RegExp(r'[^a-z0-9\s]'), ' ');
value = value.replaceAll(RegExp(r'\b(kota|kabupaten|city|regency)\b'), ' ');
value = value.replaceAll(RegExp(r'\s+'), ' ').trim();
return value;
}
int _cityMatchScore(String normalizedQuery, String candidateName) {
final normalizedCandidate = _normalizeCityToken(candidateName);
if (normalizedCandidate.isEmpty) return 0;
if (normalizedCandidate == normalizedQuery) return 100;
if (normalizedCandidate.startsWith(normalizedQuery)) return 85;
if (normalizedCandidate.contains(normalizedQuery)) return 70;
final queryWords = normalizedQuery.split(' ').where((w) => w.isNotEmpty);
var matchCount = 0;
for (final word in queryWords) {
if (normalizedCandidate.contains(word)) {
matchCount++;
}
}
if (matchCount == 0) return 0;
return (40 + (matchCount * 10)).clamp(0, 69);
}
/// Save last known position to Hive. /// Save last known position to Hive.
Future<void> _saveLastKnown(double lat, double lng) async { Future<void> _saveLastKnown(double lat, double lng) async {
final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings); final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
@@ -75,11 +162,6 @@ class LocationService {
if (settings != null) { if (settings != null) {
settings.lastLat = lat; settings.lastLat = lat;
settings.lastLng = lng; settings.lastLng = lng;
try {
settings.lastCityName = await getCityName(lat, lng);
} catch (_) {
// Ignore geocoding errors
}
await settings.save(); await settings.save();
} }
} }

View File

@@ -78,6 +78,8 @@ class NotificationInboxItem {
class NotificationInboxService { class NotificationInboxService {
NotificationInboxService._(); NotificationInboxService._();
static final NotificationInboxService instance = NotificationInboxService._(); static final NotificationInboxService instance = NotificationInboxService._();
static const Duration _nonCriticalReadRetention = Duration(days: 7);
static const int _maxVisibleItems = 120;
Box get _box => Hive.box(HiveBoxes.notificationInbox); Box get _box => Hive.box(HiveBoxes.notificationInbox);
@@ -86,16 +88,26 @@ class NotificationInboxService {
List<NotificationInboxItem> allItems({ List<NotificationInboxItem> allItems({
String filter = 'all', String filter = 'all',
}) { }) {
final now = DateTime.now();
final items = _box.values final items = _box.values
.whereType<Map>() .whereType<Map>()
.map((raw) => NotificationInboxItem.fromMap(raw)) .map((raw) => NotificationInboxItem.fromMap(raw))
.where((item) => !item.isExpired) .where((item) => !item.isExpired)
// Curated mode: hide stale read noise while keeping pinned/important.
.where((item) { .where((item) {
if (item.isPinned) return true;
if (_isCriticalType(item.type)) return true;
if (!item.isRead) return true;
final age = now.difference(item.createdAt);
return age <= _nonCriticalReadRetention;
}).where((item) {
switch (filter) { switch (filter) {
case 'unread': case 'unread':
return !item.isRead; return !item.isRead;
case 'system': case 'system':
return item.type == 'system'; return item.type == 'system';
case 'critical':
return _isCriticalType(item.type);
default: default:
return true; return true;
} }
@@ -106,7 +118,8 @@ class NotificationInboxService {
} }
return b.createdAt.compareTo(a.createdAt); return b.createdAt.compareTo(a.createdAt);
}); });
return items; // Keep list bounded in UI to avoid overwhelming long histories.
return items.take(_maxVisibleItems).toList();
} }
int unreadCount() => allItems().where((e) => !e.isRead).length; int unreadCount() => allItems().where((e) => !e.isRead).length;
@@ -122,6 +135,20 @@ class NotificationInboxService {
bool isPinned = false, bool isPinned = false,
Map<String, dynamic> meta = const <String, dynamic>{}, Map<String, dynamic> meta = const <String, dynamic>{},
}) async { }) async {
await _upsertGroupedIfNeeded(
title: title,
body: body,
type: type,
source: source,
isPinned: isPinned,
expiresAt: expiresAt,
meta: meta,
);
if (_shouldAggregate(type: type, source: source, isPinned: isPinned)) {
await pruneNoise();
return;
}
final key = dedupeKey ?? _defaultKey(type, title, body); final key = dedupeKey ?? _defaultKey(type, title, body);
if (_box.containsKey(key)) { if (_box.containsKey(key)) {
final existingRaw = _box.get(key); final existingRaw = _box.get(key);
@@ -160,6 +187,7 @@ class NotificationInboxService {
meta: meta, meta: meta,
); );
await _box.put(key, item.toMap()); await _box.put(key, item.toMap());
await pruneNoise();
await NotificationAnalyticsService.instance.track( await NotificationAnalyticsService.instance.track(
'notif_inbox_created', 'notif_inbox_created',
dimensions: <String, dynamic>{ dimensions: <String, dynamic>{
@@ -255,6 +283,119 @@ class NotificationInboxService {
} }
} }
Future<void> clearNonCritical() async {
final keys = <dynamic>[];
for (final key in _box.keys) {
final raw = _box.get(key);
if (raw is! Map) continue;
final item = NotificationInboxItem.fromMap(raw);
if (item.isPinned) continue;
if (_isCriticalType(item.type)) continue;
keys.add(key);
}
if (keys.isNotEmpty) {
await _box.deleteAll(keys);
}
}
Future<void> pruneNoise() async {
final now = DateTime.now();
final keys = <dynamic>[];
for (final key in _box.keys) {
final raw = _box.get(key);
if (raw is! Map) continue;
final item = NotificationInboxItem.fromMap(raw);
if (item.isPinned || _isCriticalType(item.type)) continue;
if (item.isRead &&
now.difference(item.createdAt) > _nonCriticalReadRetention) {
keys.add(key);
}
}
if (keys.isNotEmpty) {
await _box.deleteAll(keys);
}
}
bool _shouldAggregate({
required String type,
required String source,
required bool isPinned,
}) {
if (isPinned) return false;
if (_isCriticalType(type)) return false;
return source == 'remote' || type == 'content' || type == 'system';
}
bool _isCriticalType(String type) {
return type == 'streak_risk' || type == 'summary' || type == 'prayer';
}
Future<void> _upsertGroupedIfNeeded({
required String title,
required String body,
required String type,
required String source,
required bool isPinned,
required DateTime? expiresAt,
required Map<String, dynamic> meta,
}) async {
if (!_shouldAggregate(type: type, source: source, isPinned: isPinned)) {
return;
}
final dayKey = _dateKey(DateTime.now());
final groupKey = 'group.$source.$type.$dayKey';
final currentRaw = _box.get(groupKey);
final currentCount = (currentRaw is Map
? (NotificationInboxItem.fromMap(currentRaw).meta['groupCount']
as num?)
: null)
?.toInt();
final nextCount = (currentCount ?? 0) + 1;
final groupedTitle = _groupTitle(type);
final groupedBody = nextCount <= 1
? body
: '$nextCount notifikasi serupa hari ini. Terbaru: $body';
final nextMeta = <String, dynamic>{
...meta,
'groupCount': nextCount,
'isGrouped': true,
'lastTitle': title,
};
final item = NotificationInboxItem(
id: groupKey,
title: groupedTitle,
body: groupedBody,
type: type,
createdAt: DateTime.now(),
expiresAt: expiresAt,
readAt: null,
isPinned: false,
source: source,
deeplink: null,
meta: nextMeta,
);
await _box.put(groupKey, item.toMap());
}
String _groupTitle(String type) {
switch (type) {
case 'content':
return 'Update Konten';
case 'system':
return 'Update Sistem';
default:
return 'Notifikasi';
}
}
String _dateKey(DateTime value) {
final mm = value.month.toString().padLeft(2, '0');
final dd = value.day.toString().padLeft(2, '0');
return '${value.year}$mm$dd';
}
String _defaultKey(String type, String title, String body) { String _defaultKey(String type, String title, String body) {
final seed = '$type|$title|$body'; final seed = '$type|$title|$body';
var hash = 17; var hash = 17;

View File

@@ -4,10 +4,36 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz_data; import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz; import 'package:timezone/timezone.dart' as tz;
import '../../app/router.dart';
import '../local/models/app_settings.dart'; import '../local/models/app_settings.dart';
import 'notification_analytics_service.dart'; import 'notification_analytics_service.dart';
import 'notification_runtime_service.dart'; import 'notification_runtime_service.dart';
@pragma('vm:entry-point')
void notificationTapBackgroundHandler(NotificationResponse response) {
// Background isolates cannot safely drive GoRouter. Foreground/cold-start
// taps are handled by NotificationService after the app is initialized.
}
String? routeForNotificationPayload(String? payload) {
final type = (payload ?? '').split('|').first.trim().toLowerCase();
switch (type) {
case 'report':
case 'checklist':
return '/checklist';
case 'adhan':
case 'iqamah':
return '/';
case 'remote':
case 'content':
case 'streak_risk':
case 'system':
return '/notifications';
default:
return null;
}
}
class NotificationPermissionStatus { class NotificationPermissionStatus {
const NotificationPermissionStatus({ const NotificationPermissionStatus({
required this.notificationsAllowed, required this.notificationsAllowed,
@@ -148,11 +174,37 @@ class NotificationService {
macOS: darwinSettings, macOS: darwinSettings,
); );
await _plugin.initialize(settings: settings); await _plugin.initialize(
settings: settings,
onDidReceiveNotificationResponse: _handleNotificationResponse,
onDidReceiveBackgroundNotificationResponse:
notificationTapBackgroundHandler,
);
await _requestPermissions(); await _requestPermissions();
await _handleLaunchNotification();
_initialized = true; _initialized = true;
} }
Future<void> _handleLaunchNotification() async {
final details = await _plugin.getNotificationAppLaunchDetails();
final response = details?.notificationResponse;
if (response == null) return;
_routeFromPayload(response.payload);
}
void _handleNotificationResponse(NotificationResponse response) {
_routeFromPayload(response.payload);
}
void _routeFromPayload(String? payload) {
final route = routeForNotificationPayload(payload);
if (route == null) return;
Future<void>.delayed(Duration.zero, () {
appRouter.go(route);
});
}
void _configureLocalTimeZone() { void _configureLocalTimeZone() {
final tzId = _resolveTimeZoneIdByOffset(DateTime.now().timeZoneOffset); final tzId = _resolveTimeZoneIdByOffset(DateTime.now().timeZoneOffset);
try { try {
@@ -532,7 +584,10 @@ class NotificationService {
final pending = await _plugin.pendingNotificationRequests(); final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) { for (final request in pending) {
final id = request.id; final id = request.id;
final isPrayerSchedule = id >= 100000 && id < 900000; // Adhan IDs: 100000..799999
// Iqamah IDs: 800000..1499999
// Report IDs: 700000..789999
final isPrayerSchedule = id >= 100000 && id < 1500000;
if (isPrayerSchedule) { if (isPrayerSchedule) {
await _plugin.cancel(id: id); await _plugin.cancel(id: id);
} }

View File

@@ -117,7 +117,7 @@ final selectedCityIdProvider = StateProvider<String>((ref) {
/// Provider for today's prayer times using myQuran API. /// Provider for today's prayer times using myQuran API.
final prayerTimesProvider = FutureProvider<DaySchedule?>((ref) async { final prayerTimesProvider = FutureProvider<DaySchedule?>((ref) async {
final cityId = ref.watch(selectedCityIdProvider); final cityId = await _resolveCityIdWithAutoDetect(ref);
final today = DateFormat('yyyy-MM-dd').format(DateTime.now()); final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
DaySchedule? schedule; DaySchedule? schedule;
@@ -202,6 +202,42 @@ final prayerTimesProvider = FutureProvider<DaySchedule?>((ref) async {
return fallbackSchedule; return fallbackSchedule;
}); });
Future<String> _resolveCityIdWithAutoDetect(Ref ref) async {
final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
final settings = settingsBox.get('default') ?? AppSettings();
final stored = settings.lastCityName ?? '';
if (stored.contains('|')) {
return stored.split('|').last;
}
final position = await LocationService.instance.getCurrentLocation();
final fallbackLocation =
position == null ? LocationService.instance.getLastKnownLocation() : null;
final lat = position?.latitude ?? fallbackLocation?.lat;
final lng = position?.longitude ?? fallbackLocation?.lng;
if (lat != null && lng != null) {
try {
final resolved = await LocationService.instance
.resolveMyQuranCityFromCoordinates(lat: lat, lng: lng);
if (resolved != null) {
settings.lastCityName = '${resolved.name}|${resolved.id}';
if (settings.isInBox) {
await settings.save();
} else {
await settingsBox.put('default', settings);
}
ref.read(selectedCityIdProvider.notifier).state = resolved.id;
return resolved.id;
}
} catch (_) {
// Non-fatal: fallback to default city id.
}
}
return _defaultCityId;
}
Future<void> _syncAdhanNotifications( Future<void> _syncAdhanNotifications(
String cityId, DaySchedule schedule) async { String cityId, DaySchedule schedule) async {
try { try {

View File

@@ -16,6 +16,8 @@ import '../../../data/local/hive_boxes.dart';
import '../../../data/local/models/app_settings.dart'; import '../../../data/local/models/app_settings.dart';
import '../../../data/local/models/daily_worship_log.dart'; import '../../../data/local/models/daily_worship_log.dart';
import '../../../data/local/models/quran_bookmark.dart'; import '../../../data/local/models/quran_bookmark.dart';
import '../../../data/services/location_service.dart';
import '../../../data/services/myquran_sholat_service.dart';
import '../../../data/services/notification_service.dart'; import '../../../data/services/notification_service.dart';
import '../data/prayer_times_provider.dart'; import '../data/prayer_times_provider.dart';
@@ -75,6 +77,307 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
setState(() {}); setState(() {});
} }
void _showAdhanControlInfo() {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Tombol Sound mengatur notifikasi adzan semua waktu shalat (Subuh, Dzuhur, Ashar, Maghrib, Isya).',
),
duration: Duration(seconds: 3),
),
);
}
void _showQuickLocationDialog(BuildContext context) {
final searchCtrl = TextEditingController();
bool isSearching = false;
bool isDetecting = false;
String? currentCityLabel;
String? currentCityId;
String? currentCityError;
List<Map<String, dynamic>> results = [];
Timer? debounce;
showDialog(
context: context,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setDialogState) => AlertDialog(
insetPadding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
title: const Text('Ganti Kota'),
content: SizedBox(
width: MediaQuery.of(context).size.width * 0.85,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.primary.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: AppColors.primary.withValues(alpha: 0.2),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(
LucideIcons.mapPin,
size: 16,
color: AppColors.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
currentCityLabel == null
? 'Deteksi lokasi saat ini'
: 'Anda di $currentCityLabel',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
if (isDetecting)
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
),
if (currentCityError != null) ...[
const SizedBox(height: 6),
Text(
currentCityError!,
style: const TextStyle(
fontSize: 12,
color: Colors.red,
),
),
],
const SizedBox(height: 8),
Row(
children: [
TextButton(
onPressed: isDetecting
? null
: () async {
setDialogState(() {
isDetecting = true;
currentCityError = null;
});
try {
final pos = await LocationService.instance
.getCurrentLocation();
final fallbackLocation = pos == null
? LocationService.instance
.getLastKnownLocation()
: null;
final lat = pos?.latitude ??
fallbackLocation?.lat;
final lng = pos?.longitude ??
fallbackLocation?.lng;
if (lat == null || lng == null) {
setDialogState(() {
currentCityError =
'Lokasi tidak tersedia. Pastikan izin lokasi aktif.';
currentCityLabel = null;
currentCityId = null;
});
return;
}
final detectedLabel =
(await LocationService.instance
.getCityName(lat, lng))
.split(',')
.first
.trim();
final resolved = await LocationService
.instance
.resolveMyQuranCityFromCoordinates(
lat: lat,
lng: lng,
);
if (resolved == null) {
setDialogState(() {
final fallbackCity =
detectedLabel.isEmpty
? 'lokasi saat ini'
: detectedLabel;
currentCityError =
'Lokasi Anda terdeteksi di $fallbackCity. Kami belum menemukan ID kota yang cocok di data jadwal. Silakan cari manual kota terdekat.';
currentCityLabel = null;
currentCityId = null;
});
return;
}
setDialogState(() {
currentCityId = resolved.id;
currentCityLabel = resolved.name;
currentCityError = null;
});
} catch (_) {
setDialogState(() {
currentCityError =
'Deteksi lokasi gagal. Coba lagi.';
currentCityLabel = null;
currentCityId = null;
});
} finally {
if (ctx.mounted) {
setDialogState(() {
isDetecting = false;
});
}
}
},
child: const Text('Deteksi Lokasi'),
),
const SizedBox(width: 8),
if (currentCityId != null && currentCityLabel != null)
FilledButton(
onPressed: () {
final cityName = currentCityLabel!;
final cityId = currentCityId!;
final box =
Hive.box<AppSettings>(HiveBoxes.settings);
final settings =
box.get('default') ?? AppSettings();
settings.lastCityName = '$cityName|$cityId';
unawaited(settings.save());
ref.invalidate(cityNameProvider);
ref.invalidate(prayerTimesProvider);
unawaited(ref.read(prayerTimesProvider.future));
Navigator.pop(ctx);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Lokasi diubah ke $cityName'),
),
);
},
child: const Text('Gunakan Lokasi Ini'),
),
],
),
],
),
),
const SizedBox(height: 10),
TextField(
controller: searchCtrl,
decoration: const InputDecoration(
hintText: 'Cari kota/kabupaten...',
border: OutlineInputBorder(),
),
autofocus: true,
onChanged: (q) {
debounce?.cancel();
debounce =
Timer(const Duration(milliseconds: 350), () async {
final query = q.trim();
if (query.length < 2) {
setDialogState(() {
results = [];
});
return;
}
setDialogState(() {
isSearching = true;
});
try {
final found =
await MyQuranSholatService.instance.searchCity(
query,
);
if (!ctx.mounted) return;
setDialogState(() {
results = found;
isSearching = false;
});
} catch (_) {
if (!ctx.mounted) return;
setDialogState(() {
results = [];
isSearching = false;
});
}
});
},
),
const SizedBox(height: 10),
if (isSearching)
const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: CircularProgressIndicator(),
)
else if (results.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Text(
'Ketik minimal 2 huruf untuk mencari kota.',
style: TextStyle(fontSize: 12),
),
)
else
SizedBox(
height: 260,
child: ListView.separated(
itemCount: results.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (_, i) {
final city = results[i];
final cityName = city['lokasi']?.toString() ?? '';
final cityId = city['id']?.toString() ?? '';
return ListTile(
dense: true,
title: Text(cityName),
onTap: () {
if (cityName.isEmpty || cityId.isEmpty) return;
final box =
Hive.box<AppSettings>(HiveBoxes.settings);
final settings =
box.get('default') ?? AppSettings();
settings.lastCityName = '$cityName|$cityId';
unawaited(settings.save());
ref.invalidate(cityNameProvider);
ref.invalidate(prayerTimesProvider);
unawaited(ref.read(prayerTimesProvider.future));
Navigator.pop(ctx);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Lokasi diubah ke $cityName'),
),
);
},
);
},
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Tutup'),
),
],
),
),
).whenComplete(() {
debounce?.cancel();
searchCtrl.dispose();
});
}
@override @override
void dispose() { void dispose() {
_countdownTimer?.cancel(); _countdownTimer?.cancel();
@@ -620,8 +923,26 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
GestureDetector(
onTap: () => _showQuickLocationDialog(context),
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
shape: BoxShape.circle,
),
child: const Icon(
LucideIcons.mapPin,
color: AppColors.onPrimary,
size: 20,
),
),
),
const SizedBox(width: 12),
GestureDetector( GestureDetector(
onTap: _toggleAdhanFromHero, onTap: _toggleAdhanFromHero,
onLongPress: _showAdhanControlInfo,
child: Container( child: Container(
width: 48, width: 48,
height: 48, height: 48,

View File

@@ -124,6 +124,14 @@ class _DzikirScreenState extends ConsumerState<DzikirScreen>
return _todayKey; return _todayKey;
} }
bool _isFocusMode(String mode) {
return mode == 'focus' || mode == 'slide';
}
bool _useCircleCounterButton(String position) {
return position == 'fabCircle' || position == 'circle';
}
Future<void> _loadData() async { Future<void> _loadData() async {
_refreshTodayScope(); _refreshTodayScope();
setState(() { setState(() {
@@ -658,7 +666,7 @@ class _DzikirScreenState extends ConsumerState<DzikirScreen>
.listenable(keys: ['default']), .listenable(keys: ['default']),
builder: (_, settingsBox, __) { builder: (_, settingsBox, __) {
final settings = settingsBox.get('default') ?? AppSettings(); final settings = settingsBox.get('default') ?? AppSettings();
final isFocusMode = settings.dzikirDisplayMode == 'focus'; final isFocusMode = _isFocusMode(settings.dzikirDisplayMode);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
@@ -1172,7 +1180,9 @@ class _DzikirScreenState extends ConsumerState<DzikirScreen>
); );
}, },
), ),
if (settings.dzikirCounterButtonPosition == 'fabCircle') if (_useCircleCounterButton(
settings.dzikirCounterButtonPosition,
))
Positioned( Positioned(
right: 8, right: 8,
bottom: 12, bottom: 12,

View File

@@ -10,6 +10,19 @@ import '../../../data/services/notification_analytics_service.dart';
import '../../../data/services/notification_inbox_service.dart'; import '../../../data/services/notification_inbox_service.dart';
import '../../../data/services/notification_service.dart'; import '../../../data/services/notification_service.dart';
int _todayUpcomingAlarmCount(List<NotificationPendingAlert> alarms) {
final now = DateTime.now();
final todayStart = DateTime(now.year, now.month, now.day);
final todayEnd = todayStart.add(const Duration(days: 1));
return alarms.where((alarm) {
final when = alarm.scheduledAt;
if (when == null) return false;
return !when.isBefore(now) &&
!when.isBefore(todayStart) &&
when.isBefore(todayEnd);
}).length;
}
class NotificationCenterScreen extends StatefulWidget { class NotificationCenterScreen extends StatefulWidget {
const NotificationCenterScreen({super.key}); const NotificationCenterScreen({super.key});
@@ -56,6 +69,14 @@ class _NotificationCenterScreenState extends State<NotificationCenterScreen>
); );
} }
Future<void> _clearNonCritical() async {
await NotificationInboxService.instance.clearNonCritical();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Notifikasi non-kritis dibersihkan.')),
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark; final isDark = Theme.of(context).brightness == Brightness.dark;
@@ -91,10 +112,19 @@ class _NotificationCenterScreenState extends State<NotificationCenterScreen>
builder: (context, _, __) { builder: (context, _, __) {
final unread = final unread =
NotificationInboxService.instance.unreadCount(); NotificationInboxService.instance.unreadCount();
if (unread <= 0) return const SizedBox.shrink(); return Row(
return TextButton( mainAxisSize: MainAxisSize.min,
onPressed: _markAllRead, children: [
child: const Text('Tandai semua'), TextButton(
onPressed: _clearNonCritical,
child: const Text('Bersihkan'),
),
if (unread > 0)
TextButton(
onPressed: _markAllRead,
child: const Text('Tandai semua'),
),
],
); );
}, },
); );
@@ -113,7 +143,9 @@ class _NotificationCenterScreenState extends State<NotificationCenterScreen>
FutureBuilder<List<NotificationPendingAlert>>( FutureBuilder<List<NotificationPendingAlert>>(
future: _alarmsFuture, future: _alarmsFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
final count = snapshot.data?.length ?? 0; final count = _todayUpcomingAlarmCount(
snapshot.data ?? const <NotificationPendingAlert>[],
);
return Tab(text: count > 0 ? 'Alarm ($count)' : 'Alarm'); return Tab(text: count > 0 ? 'Alarm ($count)' : 'Alarm');
}, },
), ),
@@ -170,13 +202,21 @@ class _AlarmTabState extends State<_AlarmTab> {
final alarms = snapshot.data ?? const <NotificationPendingAlert>[]; final alarms = snapshot.data ?? const <NotificationPendingAlert>[];
final now = DateTime.now(); final now = DateTime.now();
final upcoming = alarms final todayStart = DateTime(now.year, now.month, now.day);
.where((alarm) => final todayEnd = todayStart.add(const Duration(days: 1));
alarm.scheduledAt == null || !alarm.scheduledAt!.isBefore(now)) final upcoming = alarms.where((alarm) {
.toList(); final when = alarm.scheduledAt;
if (when == null) return false;
return !when.isBefore(now) &&
!when.isBefore(todayStart) &&
when.isBefore(todayEnd);
}).toList();
final passed = alarms final passed = alarms
.where((alarm) => .where((alarm) =>
alarm.scheduledAt != null && alarm.scheduledAt!.isBefore(now)) alarm.scheduledAt != null &&
alarm.scheduledAt!.isBefore(now) &&
!alarm.scheduledAt!.isBefore(todayStart) &&
alarm.scheduledAt!.isBefore(todayEnd))
.toList(); .toList();
final visible = _alarmFilter == 'past' ? passed : upcoming; final visible = _alarmFilter == 'past' ? passed : upcoming;
@@ -254,7 +294,7 @@ class _AlarmTabState extends State<_AlarmTab> {
), ),
child: Text( child: Text(
_alarmFilter == 'upcoming' _alarmFilter == 'upcoming'
? 'Tidak ada alarm akan datang.' ? 'Tidak ada alarm tersisa untuk hari ini.'
: 'Belum ada alarm sudah lewat.', : 'Belum ada alarm sudah lewat.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith( style: Theme.of(context).textTheme.bodyMedium?.copyWith(
@@ -368,9 +408,7 @@ class _AlarmTabState extends State<_AlarmTab> {
runSpacing: 8, runSpacing: 8,
children: [ children: [
_FilterChip( _FilterChip(
label: upcomingCount > 0 label: upcomingCount > 0 ? 'Hari Ini ($upcomingCount)' : 'Hari Ini',
? 'Akan Datang ($upcomingCount)'
: 'Akan Datang',
selected: _alarmFilter == 'upcoming', selected: _alarmFilter == 'upcoming',
isDark: isDark, isDark: isDark,
onTap: () => setState(() => _alarmFilter = 'upcoming'), onTap: () => setState(() => _alarmFilter = 'upcoming'),
@@ -627,6 +665,16 @@ class _InboxTabState extends State<_InboxTab> {
label: _inboxLabel(item.type), label: _inboxLabel(item.type),
color: accent, color: accent,
), ),
if ((item.meta['isGrouped'] == true) &&
(item.meta['groupCount'] is num))
Padding(
padding: const EdgeInsets.only(left: 8),
child: _TypeBadge(
label:
'${(item.meta['groupCount'] as num).toInt()} item',
color: AppColors.sage,
),
),
const SizedBox(width: 8), const SizedBox(width: 8),
Text( Text(
_formatInboxTime(item.createdAt), _formatInboxTime(item.createdAt),
@@ -694,6 +742,12 @@ class _InboxTabState extends State<_InboxTab> {
isDark: isDark, isDark: isDark,
onTap: () => setState(() => _filter = 'system'), onTap: () => setState(() => _filter = 'system'),
), ),
_FilterChip(
label: 'Kritis',
selected: _filter == 'critical',
isDark: isDark,
onTap: () => setState(() => _filter = 'critical'),
),
], ],
); );
} }

File diff suppressed because it is too large Load Diff

View File

@@ -273,6 +273,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.7" version: "3.0.7"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.9"
custom_lint: custom_lint:
dependency: transitive dependency: transitive
description: description:

View File

@@ -1,7 +1,7 @@
name: jamshalat_diary name: jamshalat_diary
description: Islamic worship companion app description: Islamic worship companion app
publish_to: 'none' publish_to: 'none'
version: 1.0.0+1 version: 1.0.8+9
environment: environment:
sdk: '>=3.0.0 <4.0.0' sdk: '>=3.0.0 <4.0.0'
@@ -36,6 +36,7 @@ dependencies:
workmanager: ^0.9.0+3 workmanager: ^0.9.0+3
firebase_core: ^4.1.1 firebase_core: ^4.1.1
firebase_messaging: ^16.0.1 firebase_messaging: ^16.0.1
cupertino_icons: ^1.0.8
# Audio # Audio
just_audio: ^0.10.5 just_audio: ^0.10.5

View File

@@ -1,30 +1,15 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:jamshalat_diary/main.dart'; import 'package:jamshalat_diary/app/app.dart';
void main() { void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async { testWidgets('App smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame. await tester.pumpWidget(
await tester.pumpWidget(const MyApp()); const ProviderScope(
child: App(),
),
);
// Verify that our counter starts at 0. expect(find.byType(App), findsOneWidget);
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
}); });
} }