Fix notification delivery and settings flows
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:geocoding/geocoding.dart' as geocoding;
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
import 'myquran_sholat_service.dart';
|
||||
import '../local/hive_boxes.dart';
|
||||
import '../local/models/app_settings.dart';
|
||||
|
||||
@@ -39,14 +40,13 @@ class LocationService {
|
||||
}
|
||||
|
||||
/// 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 settings = settingsBox.get('default');
|
||||
if (settings?.lastLat != null && settings?.lastLng != null) {
|
||||
return (
|
||||
lat: settings!.lastLat!,
|
||||
lng: settings.lastLng!,
|
||||
cityName: settings.lastCityName,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
@@ -68,6 +68,93 @@ class LocationService {
|
||||
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.
|
||||
Future<void> _saveLastKnown(double lat, double lng) async {
|
||||
final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
|
||||
@@ -75,11 +162,6 @@ class LocationService {
|
||||
if (settings != null) {
|
||||
settings.lastLat = lat;
|
||||
settings.lastLng = lng;
|
||||
try {
|
||||
settings.lastCityName = await getCityName(lat, lng);
|
||||
} catch (_) {
|
||||
// Ignore geocoding errors
|
||||
}
|
||||
await settings.save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +78,8 @@ class NotificationInboxItem {
|
||||
class NotificationInboxService {
|
||||
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);
|
||||
|
||||
@@ -86,16 +88,26 @@ class NotificationInboxService {
|
||||
List<NotificationInboxItem> allItems({
|
||||
String filter = 'all',
|
||||
}) {
|
||||
final now = DateTime.now();
|
||||
final items = _box.values
|
||||
.whereType<Map>()
|
||||
.map((raw) => NotificationInboxItem.fromMap(raw))
|
||||
.where((item) => !item.isExpired)
|
||||
// Curated mode: hide stale read noise while keeping pinned/important.
|
||||
.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) {
|
||||
case 'unread':
|
||||
return !item.isRead;
|
||||
case 'system':
|
||||
return item.type == 'system';
|
||||
case 'critical':
|
||||
return _isCriticalType(item.type);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
@@ -106,7 +118,8 @@ class NotificationInboxService {
|
||||
}
|
||||
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;
|
||||
@@ -122,6 +135,20 @@ class NotificationInboxService {
|
||||
bool isPinned = false,
|
||||
Map<String, dynamic> meta = const <String, dynamic>{},
|
||||
}) 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);
|
||||
if (_box.containsKey(key)) {
|
||||
final existingRaw = _box.get(key);
|
||||
@@ -160,6 +187,7 @@ class NotificationInboxService {
|
||||
meta: meta,
|
||||
);
|
||||
await _box.put(key, item.toMap());
|
||||
await pruneNoise();
|
||||
await NotificationAnalyticsService.instance.track(
|
||||
'notif_inbox_created',
|
||||
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) {
|
||||
final seed = '$type|$title|$body';
|
||||
var hash = 17;
|
||||
|
||||
@@ -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/timezone.dart' as tz;
|
||||
|
||||
import '../../app/router.dart';
|
||||
import '../local/models/app_settings.dart';
|
||||
import 'notification_analytics_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 {
|
||||
const NotificationPermissionStatus({
|
||||
required this.notificationsAllowed,
|
||||
@@ -148,11 +174,37 @@ class NotificationService {
|
||||
macOS: darwinSettings,
|
||||
);
|
||||
|
||||
await _plugin.initialize(settings: settings);
|
||||
await _plugin.initialize(
|
||||
settings: settings,
|
||||
onDidReceiveNotificationResponse: _handleNotificationResponse,
|
||||
onDidReceiveBackgroundNotificationResponse:
|
||||
notificationTapBackgroundHandler,
|
||||
);
|
||||
await _requestPermissions();
|
||||
await _handleLaunchNotification();
|
||||
_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() {
|
||||
final tzId = _resolveTimeZoneIdByOffset(DateTime.now().timeZoneOffset);
|
||||
try {
|
||||
@@ -532,7 +584,10 @@ class NotificationService {
|
||||
final pending = await _plugin.pendingNotificationRequests();
|
||||
for (final request in pending) {
|
||||
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) {
|
||||
await _plugin.cancel(id: id);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user