Files
jamshalat-diary/lib/data/services/notification_inbox_service.dart
2026-05-31 20:40:20 +07:00

441 lines
12 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../local/hive_boxes.dart';
import 'notification_analytics_service.dart';
class NotificationInboxItem {
const NotificationInboxItem({
required this.id,
required this.title,
required this.body,
required this.type,
required this.createdAt,
required this.expiresAt,
required this.readAt,
required this.isPinned,
required this.source,
required this.deeplink,
required this.meta,
});
final String id;
final String title;
final String body;
final String type;
final DateTime createdAt;
final DateTime? expiresAt;
final DateTime? readAt;
final bool isPinned;
final String source;
final String? deeplink;
final Map<String, dynamic> meta;
bool get isRead => readAt != null;
bool get isExpired => expiresAt != null && DateTime.now().isAfter(expiresAt!);
Map<String, dynamic> toMap() => {
'id': id,
'title': title,
'body': body,
'type': type,
'createdAt': createdAt.toIso8601String(),
'expiresAt': expiresAt?.toIso8601String(),
'readAt': readAt?.toIso8601String(),
'isPinned': isPinned,
'source': source,
'deeplink': deeplink,
'meta': meta,
};
static NotificationInboxItem fromMap(Map<dynamic, dynamic> map) {
final createdRaw = (map['createdAt'] ?? '').toString();
final expiresRaw = (map['expiresAt'] ?? '').toString();
final readRaw = (map['readAt'] ?? '').toString();
final rawMeta = map['meta'];
return NotificationInboxItem(
id: (map['id'] ?? '').toString(),
title: (map['title'] ?? '').toString(),
body: (map['body'] ?? '').toString(),
type: (map['type'] ?? 'system').toString(),
createdAt: DateTime.tryParse(createdRaw) ??
DateTime.fromMillisecondsSinceEpoch(0),
expiresAt: expiresRaw.isEmpty ? null : DateTime.tryParse(expiresRaw),
readAt: readRaw.isEmpty ? null : DateTime.tryParse(readRaw),
isPinned: map['isPinned'] == true,
source: (map['source'] ?? 'local').toString(),
deeplink: ((map['deeplink'] ?? '').toString().trim().isEmpty)
? null
: (map['deeplink'] ?? '').toString(),
meta: rawMeta is Map
? rawMeta.map((k, v) => MapEntry(k.toString(), v))
: const <String, dynamic>{},
);
}
}
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);
ValueListenable<Box> listenable() => _box.listenable();
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;
}
}).toList()
..sort((a, b) {
if (a.isPinned != b.isPinned) {
return a.isPinned ? -1 : 1;
}
return b.createdAt.compareTo(a.createdAt);
});
// Keep list bounded in UI to avoid overwhelming long histories.
return items.take(_maxVisibleItems).toList();
}
int unreadCount() => allItems().where((e) => !e.isRead).length;
Future<void> addItem({
required String title,
required String body,
required String type,
String source = 'local',
String? deeplink,
String? dedupeKey,
DateTime? expiresAt,
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);
if (existingRaw is Map) {
final existing = NotificationInboxItem.fromMap(existingRaw);
await _box.put(
key,
existing
.copyWith(
title: title,
body: body,
type: type,
source: source,
deeplink: deeplink,
expiresAt: expiresAt ?? existing.expiresAt,
isPinned: isPinned || existing.isPinned,
meta: meta.isEmpty ? existing.meta : meta,
)
.toMap(),
);
}
return;
}
final item = NotificationInboxItem(
id: key,
title: title,
body: body,
type: type,
createdAt: DateTime.now(),
expiresAt: expiresAt,
readAt: null,
isPinned: isPinned,
source: source,
deeplink: deeplink,
meta: meta,
);
await _box.put(key, item.toMap());
await pruneNoise();
await NotificationAnalyticsService.instance.track(
'notif_inbox_created',
dimensions: <String, dynamic>{
'event_type': type,
'source': source,
},
);
}
Future<void> markRead(String id) async {
final raw = _box.get(id);
if (raw is! Map) return;
final item = NotificationInboxItem.fromMap(raw);
if (item.isRead) return;
await _box.put(
id,
item.copyWith(readAt: DateTime.now()).toMap(),
);
await NotificationAnalyticsService.instance.track(
'notif_mark_read',
dimensions: <String, dynamic>{'event_type': item.type},
);
}
Future<void> markUnread(String id) async {
final raw = _box.get(id);
if (raw is! Map) return;
final item = NotificationInboxItem.fromMap(raw);
if (!item.isRead) return;
await _box.put(
id,
item.copyWith(readAt: null).toMap(),
);
await NotificationAnalyticsService.instance.track(
'notif_mark_unread',
dimensions: <String, dynamic>{'event_type': item.type},
);
}
Future<void> markAllRead() async {
final updates = <dynamic, Map<String, dynamic>>{};
for (final key in _box.keys) {
final raw = _box.get(key);
if (raw is! Map) continue;
final item = NotificationInboxItem.fromMap(raw);
if (item.isRead) continue;
updates[key] = item.copyWith(readAt: DateTime.now()).toMap();
}
if (updates.isNotEmpty) {
await _box.putAll(updates);
}
}
Future<void> remove(String id) async {
await _box.delete(id);
}
Future<void> removeByType(String type) 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.type == type) {
keys.add(key);
}
}
if (keys.isNotEmpty) {
await _box.deleteAll(keys);
}
}
Future<void> togglePinned(String id) async {
final raw = _box.get(id);
if (raw is! Map) return;
final item = NotificationInboxItem.fromMap(raw);
await _box.put(
id,
item.copyWith(isPinned: !item.isPinned).toMap(),
);
}
Future<void> removeExpired() async {
final expiredKeys = <dynamic>[];
for (final key in _box.keys) {
final raw = _box.get(key);
if (raw is! Map) continue;
final item = NotificationInboxItem.fromMap(raw);
if (item.isExpired) expiredKeys.add(key);
}
if (expiredKeys.isNotEmpty) {
await _box.deleteAll(expiredKeys);
}
}
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;
for (final rune in seed.runes) {
hash = 31 * hash + rune;
}
return 'inbox_${hash.abs()}';
}
}
extension on NotificationInboxItem {
static const _readAtUnchanged = Object();
NotificationInboxItem copyWith({
String? title,
String? body,
String? type,
DateTime? createdAt,
DateTime? expiresAt,
Object? readAt = _readAtUnchanged,
bool? isPinned,
String? source,
String? deeplink,
Map<String, dynamic>? meta,
}) {
return NotificationInboxItem(
id: id,
title: title ?? this.title,
body: body ?? this.body,
type: type ?? this.type,
createdAt: createdAt ?? this.createdAt,
expiresAt: expiresAt ?? this.expiresAt,
readAt: identical(readAt, _readAtUnchanged)
? this.readAt
: readAt as DateTime?,
isPinned: isPinned ?? this.isPinned,
source: source ?? this.source,
deeplink: deeplink ?? this.deeplink,
meta: meta ?? this.meta,
);
}
}