Initial commit: SubManager Flutter App
주요 구현 완료 기능: - 구독 관리 (추가/편집/삭제/카테고리 분류) - 이벤트 할인 시스템 (기본값 자동 설정) - SMS 자동 스캔 및 구독 정보 추출 - 알림 시스템 (타임존 처리 안정화) - 환율 변환 지원 (KRW/USD) - 반응형 UI 및 애니메이션 - 다국어 지원 (한국어/영어) 버그 수정: - NotificationService tz.local 초기화 오류 해결 - MainScreenSummaryCard 레이아웃 오버플로우 수정 - 구독 추가 시 LateInitializationError 완전 해결 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
171
lib/providers/app_lock_provider.dart
Normal file
171
lib/providers/app_lock_provider.dart
Normal file
@@ -0,0 +1,171 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:local_auth/local_auth.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import '../services/notification_service.dart';
|
||||
import '../providers/subscription_provider.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
|
||||
class AppLockProvider extends ChangeNotifier {
|
||||
final Box<bool> _appLockBox;
|
||||
final LocalAuthentication _localAuth = LocalAuthentication();
|
||||
final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();
|
||||
static const String _isEnabledKey = 'app_lock_enabled';
|
||||
|
||||
bool _isEnabled = false;
|
||||
bool _isLocked = false;
|
||||
bool _isBiometricEnabled = false;
|
||||
bool _isBiometricAvailable = false;
|
||||
|
||||
AppLockProvider(this._appLockBox) {
|
||||
_init();
|
||||
}
|
||||
|
||||
bool get isEnabled => _isEnabled;
|
||||
bool get isLocked => _isLocked;
|
||||
bool get isBiometricEnabled => _isBiometricEnabled;
|
||||
bool get isBiometricAvailable => _isBiometricAvailable;
|
||||
|
||||
Future<void> _init() async {
|
||||
if (!kIsWeb) {
|
||||
_isBiometricAvailable = await _localAuth.canCheckBiometrics;
|
||||
} else {
|
||||
_isBiometricAvailable = false;
|
||||
}
|
||||
_isLocked = _appLockBox.get('isLocked', defaultValue: false) ?? false;
|
||||
await _loadState();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _loadState() async {
|
||||
final value = await _secureStorage.read(key: _isEnabledKey);
|
||||
_isEnabled = value == 'true';
|
||||
_isLocked = _appLockBox.get('isLocked', defaultValue: false) ?? false;
|
||||
await _loadSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _loadSettings() async {
|
||||
try {
|
||||
final biometricEnabled =
|
||||
await _secureStorage.read(key: 'biometric_enabled');
|
||||
_isBiometricEnabled = biometricEnabled == 'true';
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('설정 로드 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> authenticate() async {
|
||||
if (kIsWeb) {
|
||||
_isLocked = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
final canCheck = await _checkBiometrics();
|
||||
if (!canCheck) {
|
||||
_isLocked = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
final authenticated = await _localAuth.authenticate(
|
||||
localizedReason: '생체 인증을 사용하여 앱 잠금을 해제하세요.',
|
||||
options: const AuthenticationOptions(
|
||||
stickyAuth: true,
|
||||
biometricOnly: true,
|
||||
),
|
||||
);
|
||||
|
||||
if (authenticated) {
|
||||
_isLocked = false;
|
||||
await _appLockBox.put('isLocked', false);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
return authenticated;
|
||||
} catch (e) {
|
||||
_isLocked = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _checkBiometrics() async {
|
||||
if (kIsWeb) return false;
|
||||
try {
|
||||
return await _localAuth.canCheckBiometrics;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> toggleBiometricAuth() async {
|
||||
if (kIsWeb) {
|
||||
_isBiometricEnabled = false;
|
||||
await _appLockBox.put('biometric_enabled', false);
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final canCheck = await _checkBiometrics();
|
||||
if (!canCheck) {
|
||||
_isBiometricEnabled = false;
|
||||
await _appLockBox.put('biometric_enabled', false);
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
_isBiometricEnabled = !_isBiometricEnabled;
|
||||
await _secureStorage.write(
|
||||
key: 'biometric_enabled',
|
||||
value: _isBiometricEnabled.toString(),
|
||||
);
|
||||
await _appLockBox.put('biometric_enabled', _isBiometricEnabled);
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
_isBiometricEnabled = false;
|
||||
await _appLockBox.put('biometric_enabled', false);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void lock() {
|
||||
if (_isBiometricEnabled) {
|
||||
_isLocked = true;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> unlock() async {
|
||||
_isLocked = false;
|
||||
await _appLockBox.put('isLocked', false);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> enable() async {
|
||||
_isEnabled = true;
|
||||
await _secureStorage.write(key: _isEnabledKey, value: 'true');
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> disable() async {
|
||||
_isEnabled = false;
|
||||
await _secureStorage.write(key: _isEnabledKey, value: 'false');
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> refreshNotifications(BuildContext context) async {
|
||||
final subscriptionProvider = Provider.of<SubscriptionProvider>(
|
||||
context,
|
||||
listen: false,
|
||||
);
|
||||
for (var subscription in subscriptionProvider.subscriptions) {
|
||||
await NotificationService.scheduleSubscriptionNotification(subscription);
|
||||
}
|
||||
}
|
||||
}
|
||||
86
lib/providers/category_provider.dart
Normal file
86
lib/providers/category_provider.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import '../models/category_model.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
class CategoryProvider extends ChangeNotifier {
|
||||
List<CategoryModel> _categories = [];
|
||||
late Box<CategoryModel> _categoryBox;
|
||||
|
||||
List<CategoryModel> get categories => _categories;
|
||||
|
||||
Future<void> init() async {
|
||||
_categoryBox = await Hive.openBox<CategoryModel>('categories');
|
||||
_categories = _categoryBox.values.toList();
|
||||
|
||||
// 카테고리가 비어있으면 기본 카테고리 추가
|
||||
if (_categories.isEmpty) {
|
||||
await _initDefaultCategories();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// 기본 카테고리 초기화
|
||||
Future<void> _initDefaultCategories() async {
|
||||
final defaultCategories = [
|
||||
{'name': 'OTT 서비스', 'color': '#3B82F6', 'icon': 'live_tv'},
|
||||
{'name': '음악 서비스', 'color': '#EC4899', 'icon': 'music_note'},
|
||||
{'name': 'AI 서비스', 'color': '#8B5CF6', 'icon': 'psychology'},
|
||||
{'name': '프로그래밍/개발', 'color': '#10B981', 'icon': 'code'},
|
||||
{'name': '오피스/협업 툴', 'color': '#F59E0B', 'icon': 'business_center'},
|
||||
{'name': '기타 서비스', 'color': '#6B7280', 'icon': 'more_horiz'},
|
||||
];
|
||||
|
||||
for (final category in defaultCategories) {
|
||||
final newCategory = CategoryModel(
|
||||
id: const Uuid().v4(),
|
||||
name: category['name']!,
|
||||
color: category['color']!,
|
||||
icon: category['icon']!,
|
||||
);
|
||||
|
||||
await _categoryBox.put(newCategory.id, newCategory);
|
||||
_categories.add(newCategory);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addCategory({
|
||||
required String name,
|
||||
required String color,
|
||||
required String icon,
|
||||
}) async {
|
||||
final newCategory = CategoryModel(
|
||||
id: const Uuid().v4(),
|
||||
name: name,
|
||||
color: color,
|
||||
icon: icon,
|
||||
);
|
||||
await _categoryBox.put(newCategory.id, newCategory);
|
||||
_categories.add(newCategory);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> updateCategory(CategoryModel updated) async {
|
||||
await _categoryBox.put(updated.id, updated);
|
||||
int index = _categories.indexWhere((cat) => cat.id == updated.id);
|
||||
if (index != -1) {
|
||||
_categories[index] = updated;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteCategory(String id) async {
|
||||
await _categoryBox.delete(id);
|
||||
_categories.removeWhere((cat) => cat.id == id);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
CategoryModel? getCategoryById(String id) {
|
||||
try {
|
||||
return _categories.firstWhere((cat) => cat.id == id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
22
lib/providers/locale_provider.dart
Normal file
22
lib/providers/locale_provider.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
|
||||
class LocaleProvider extends ChangeNotifier {
|
||||
late Box<String> _localeBox;
|
||||
Locale _locale = const Locale('ko');
|
||||
|
||||
Locale get locale => _locale;
|
||||
|
||||
Future<void> init() async {
|
||||
_localeBox = await Hive.openBox<String>('locale');
|
||||
final savedLocale = _localeBox.get('locale', defaultValue: 'ko');
|
||||
_locale = Locale(savedLocale ?? 'ko');
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> setLocale(String languageCode) async {
|
||||
_locale = Locale(languageCode);
|
||||
await _localeBox.put('locale', languageCode);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
263
lib/providers/notification_provider.dart
Normal file
263
lib/providers/notification_provider.dart
Normal file
@@ -0,0 +1,263 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../services/notification_service.dart';
|
||||
import '../providers/subscription_provider.dart';
|
||||
|
||||
class NotificationProvider extends ChangeNotifier {
|
||||
final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();
|
||||
static const String _paymentNotificationKey = 'payment_notification_enabled';
|
||||
static const String _unusedServiceNotificationKey =
|
||||
'unused_service_notification_enabled';
|
||||
static const String _reminderDaysKey = 'reminder_days';
|
||||
static const String _reminderHourKey = 'reminder_hour';
|
||||
static const String _reminderMinuteKey = 'reminder_minute';
|
||||
static const String _dailyReminderKey = 'daily_reminder_enabled';
|
||||
|
||||
bool _isEnabled = false;
|
||||
bool _isPaymentEnabled = false;
|
||||
bool _isUnusedServiceNotificationEnabled = false;
|
||||
int _reminderDays = 3; // 기본값: 3일 전
|
||||
int _reminderHour = 10; // 기본값: 오전 10시
|
||||
int _reminderMinute = 0; // 기본값: 0분
|
||||
bool _isDailyReminderEnabled = false; // 기본값: 반복 알림 비활성화
|
||||
|
||||
// 웹 플랫폼 여부 확인 (웹에서는 알림이 지원되지 않음)
|
||||
bool get _isWeb => kIsWeb;
|
||||
|
||||
// SubscriptionProvider 인스턴스 (알림 재예약 시 사용)
|
||||
SubscriptionProvider? _subscriptionProvider;
|
||||
|
||||
bool get isEnabled => _isEnabled;
|
||||
bool get isPaymentEnabled => _isPaymentEnabled;
|
||||
bool get isUnusedServiceNotificationEnabled =>
|
||||
_isUnusedServiceNotificationEnabled;
|
||||
int get reminderDays => _reminderDays;
|
||||
int get reminderHour => _reminderHour;
|
||||
int get reminderMinute => _reminderMinute;
|
||||
bool get isDailyReminderEnabled => _isDailyReminderEnabled;
|
||||
|
||||
NotificationProvider() {
|
||||
_loadSettings();
|
||||
}
|
||||
|
||||
// SubscriptionProvider 설정 (알림 재예약 시 사용)
|
||||
void setSubscriptionProvider(SubscriptionProvider provider) {
|
||||
_subscriptionProvider = provider;
|
||||
}
|
||||
|
||||
Future<void> _loadSettings() async {
|
||||
final paymentValue =
|
||||
await _secureStorage.read(key: _paymentNotificationKey);
|
||||
final unusedValue =
|
||||
await _secureStorage.read(key: _unusedServiceNotificationKey);
|
||||
final reminderDaysValue = await _secureStorage.read(key: _reminderDaysKey);
|
||||
final reminderHourValue = await _secureStorage.read(key: _reminderHourKey);
|
||||
final reminderMinuteValue =
|
||||
await _secureStorage.read(key: _reminderMinuteKey);
|
||||
final dailyReminderValue =
|
||||
await _secureStorage.read(key: _dailyReminderKey);
|
||||
|
||||
_isPaymentEnabled = paymentValue == 'true';
|
||||
_isUnusedServiceNotificationEnabled = unusedValue == 'true';
|
||||
_reminderDays =
|
||||
reminderDaysValue != null ? int.tryParse(reminderDaysValue) ?? 3 : 3;
|
||||
_reminderHour =
|
||||
reminderHourValue != null ? int.tryParse(reminderHourValue) ?? 10 : 10;
|
||||
_reminderMinute = reminderMinuteValue != null
|
||||
? int.tryParse(reminderMinuteValue) ?? 0
|
||||
: 0;
|
||||
_isDailyReminderEnabled = dailyReminderValue == 'true';
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
try {
|
||||
_isEnabled = await NotificationService.isNotificationEnabled();
|
||||
_isPaymentEnabled =
|
||||
await NotificationService.isPaymentNotificationEnabled();
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('알림 설정 초기화 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool value) async {
|
||||
try {
|
||||
_isEnabled = value;
|
||||
await NotificationService.setNotificationEnabled(value);
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('알림 활성화 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setPaymentEnabled(bool value) async {
|
||||
try {
|
||||
// 설정값이 변경된 경우에만 처리
|
||||
if (_isPaymentEnabled != value) {
|
||||
_isPaymentEnabled = value;
|
||||
await NotificationService.setPaymentNotificationEnabled(value);
|
||||
|
||||
// 웹에서는 알림 기능 비활성화
|
||||
if (_isWeb) {
|
||||
debugPrint('웹 플랫폼에서는 알림 기능이 지원되지 않습니다.');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
// 알림이 활성화된 경우에만 알림 재예약 (비활성화 시에는 필요 없음)
|
||||
if (value) {
|
||||
// 알림 설정 변경 시 모든 구독의 알림 재예약
|
||||
// 지연 실행으로 UI 응답성 향상
|
||||
Future.microtask(() => _rescheduleNotificationsIfNeeded());
|
||||
} else {
|
||||
// 알림이 비활성화되면 모든 알림 취소
|
||||
try {
|
||||
await NotificationService.cancelAllNotifications();
|
||||
} catch (e) {
|
||||
debugPrint('알림 취소 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('결제 알림 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUnusedServiceNotificationEnabled(bool value) async {
|
||||
try {
|
||||
_isUnusedServiceNotificationEnabled = value;
|
||||
await _secureStorage.write(
|
||||
key: _unusedServiceNotificationKey,
|
||||
value: value.toString(),
|
||||
);
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('미사용 서비스 알림 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 알림 시점 설정 (1일전, 2일전, 3일전)
|
||||
Future<void> setReminderDays(int days) async {
|
||||
try {
|
||||
// 값이 변경된 경우에만 처리
|
||||
if (_reminderDays != days) {
|
||||
_reminderDays = days;
|
||||
await _secureStorage.write(
|
||||
key: _reminderDaysKey,
|
||||
value: days.toString(),
|
||||
);
|
||||
|
||||
// 웹에서는 알림 기능 비활성화
|
||||
if (_isWeb) {
|
||||
debugPrint('웹 플랫폼에서는 알림 기능이 지원되지 않습니다.');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
// 1일 전으로 설정되면 반복 알림 자동 비활성화
|
||||
if (days == 1 && _isDailyReminderEnabled) {
|
||||
await setDailyReminderEnabled(false);
|
||||
} else if (_isPaymentEnabled) {
|
||||
// 알림이 활성화된 경우에만 처리
|
||||
// 알림 설정 변경 시 모든 구독의 알림 재예약 (백그라운드에서 처리)
|
||||
Future.microtask(() => _rescheduleNotificationsIfNeeded());
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('알림 시점 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 알림 시간 설정
|
||||
Future<void> setReminderTime(int hour, int minute) async {
|
||||
try {
|
||||
// 값이 변경된 경우에만 처리
|
||||
if (_reminderHour != hour || _reminderMinute != minute) {
|
||||
_reminderHour = hour;
|
||||
_reminderMinute = minute;
|
||||
await _secureStorage.write(
|
||||
key: _reminderHourKey,
|
||||
value: hour.toString(),
|
||||
);
|
||||
await _secureStorage.write(
|
||||
key: _reminderMinuteKey,
|
||||
value: minute.toString(),
|
||||
);
|
||||
|
||||
// 웹에서는 알림 기능 비활성화
|
||||
if (_isWeb) {
|
||||
debugPrint('웹 플랫폼에서는 알림 기능이 지원되지 않습니다.');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
// 알림이 활성화된 경우에만 처리
|
||||
if (_isPaymentEnabled) {
|
||||
// 알림 설정 변경 시 모든 구독의 알림 재예약 (백그라운드에서 처리)
|
||||
Future.microtask(() => _rescheduleNotificationsIfNeeded());
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('알림 시간 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 반복 알림 설정
|
||||
Future<void> setDailyReminderEnabled(bool value) async {
|
||||
try {
|
||||
// 값이 변경된 경우에만 처리
|
||||
if (_isDailyReminderEnabled != value) {
|
||||
_isDailyReminderEnabled = value;
|
||||
await _secureStorage.write(
|
||||
key: _dailyReminderKey,
|
||||
value: value.toString(),
|
||||
);
|
||||
|
||||
// 웹에서는 알림 기능 비활성화
|
||||
if (_isWeb) {
|
||||
debugPrint('웹 플랫폼에서는 알림 기능이 지원되지 않습니다.');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
// 알림이 활성화된 경우에만 처리
|
||||
if (_isPaymentEnabled) {
|
||||
// 알림 설정 변경 시 모든 구독의 알림 재예약 (백그라운드에서 처리)
|
||||
Future.microtask(() => _rescheduleNotificationsIfNeeded());
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('반복 알림 설정 중 오류 발생: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 알림 설정 변경 시 모든 구독의 알림 일정 재예약
|
||||
Future<void> _rescheduleNotificationsIfNeeded() async {
|
||||
try {
|
||||
// 웹 플랫폼에서는 지원하지 않음
|
||||
if (_isWeb) {
|
||||
debugPrint('웹 플랫폼에서는 알림 기능이 지원되지 않습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 구독 목록을 가져올 수 있고, 알림이 활성화된 경우에만 재예약
|
||||
if (_subscriptionProvider != null && _isPaymentEnabled) {
|
||||
final subscriptions = _subscriptionProvider!.subscriptions;
|
||||
await NotificationService.reschedulAllNotifications(subscriptions);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('알림 재예약 중 오류 발생: $e');
|
||||
// 오류가 발생해도 앱 동작에 영향을 주지 않도록 처리
|
||||
}
|
||||
}
|
||||
}
|
||||
246
lib/providers/subscription_provider.dart
Normal file
246
lib/providers/subscription_provider.dart
Normal file
@@ -0,0 +1,246 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/subscription_model.dart';
|
||||
import '../services/notification_service.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'notification_provider.dart';
|
||||
import '../navigator_key.dart';
|
||||
|
||||
class SubscriptionProvider extends ChangeNotifier {
|
||||
late Box<SubscriptionModel> _subscriptionBox;
|
||||
List<SubscriptionModel> _subscriptions = [];
|
||||
bool _isLoading = true;
|
||||
|
||||
List<SubscriptionModel> get subscriptions => _subscriptions;
|
||||
bool get isLoading => _isLoading;
|
||||
|
||||
double get totalMonthlyExpense {
|
||||
return _subscriptions.fold(
|
||||
0.0,
|
||||
(sum, subscription) => sum + subscription.currentPrice, // 이벤트 가격 반영
|
||||
);
|
||||
}
|
||||
|
||||
/// 월간 총 비용을 반환합니다.
|
||||
double getTotalMonthlyCost() {
|
||||
return totalMonthlyExpense;
|
||||
}
|
||||
|
||||
/// 이벤트로 인한 총 절약액을 반환합니다.
|
||||
double get totalEventSavings {
|
||||
return _subscriptions.fold(
|
||||
0.0,
|
||||
(sum, subscription) => sum + subscription.eventSavings,
|
||||
);
|
||||
}
|
||||
|
||||
/// 현재 이벤트 중인 구독 목록을 반환합니다.
|
||||
List<SubscriptionModel> get activeEventSubscriptions {
|
||||
return _subscriptions.where((sub) => sub.isCurrentlyInEvent).toList();
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
try {
|
||||
_isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
_subscriptionBox = await Hive.openBox<SubscriptionModel>('subscriptions');
|
||||
await refreshSubscriptions();
|
||||
|
||||
// 앱 시작 시 이벤트 상태 확인
|
||||
await checkAndUpdateEventStatus();
|
||||
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('구독 초기화 중 오류 발생: $e');
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> refreshSubscriptions() async {
|
||||
try {
|
||||
_subscriptions = _subscriptionBox.values.toList()
|
||||
..sort((a, b) => a.nextBillingDate.compareTo(b.nextBillingDate));
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('구독 목록 새로고침 중 오류 발생: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addSubscription({
|
||||
required String serviceName,
|
||||
required double monthlyCost,
|
||||
required String billingCycle,
|
||||
required DateTime nextBillingDate,
|
||||
String? websiteUrl,
|
||||
String? categoryId,
|
||||
bool isAutoDetected = false,
|
||||
int repeatCount = 1,
|
||||
DateTime? lastPaymentDate,
|
||||
String currency = 'KRW',
|
||||
bool isEventActive = false,
|
||||
DateTime? eventStartDate,
|
||||
DateTime? eventEndDate,
|
||||
double? eventPrice,
|
||||
}) async {
|
||||
try {
|
||||
final subscription = SubscriptionModel(
|
||||
id: const Uuid().v4(),
|
||||
serviceName: serviceName,
|
||||
monthlyCost: monthlyCost,
|
||||
billingCycle: billingCycle,
|
||||
nextBillingDate: nextBillingDate,
|
||||
websiteUrl: websiteUrl,
|
||||
categoryId: categoryId,
|
||||
isAutoDetected: isAutoDetected,
|
||||
repeatCount: repeatCount,
|
||||
lastPaymentDate: lastPaymentDate,
|
||||
currency: currency,
|
||||
isEventActive: isEventActive,
|
||||
eventStartDate: eventStartDate,
|
||||
eventEndDate: eventEndDate,
|
||||
eventPrice: eventPrice,
|
||||
);
|
||||
|
||||
await _subscriptionBox.put(subscription.id, subscription);
|
||||
await refreshSubscriptions();
|
||||
|
||||
// 이벤트가 활성화된 경우 알림 스케줄 재설정
|
||||
if (isEventActive && eventEndDate != null) {
|
||||
await _scheduleEventEndNotification(subscription);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('구독 추가 중 오류 발생: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateSubscription(SubscriptionModel subscription) async {
|
||||
try {
|
||||
notifyListeners();
|
||||
|
||||
await _subscriptionBox.put(subscription.id, subscription);
|
||||
|
||||
// 이벤트 관련 알림 업데이트
|
||||
if (subscription.isEventActive && subscription.eventEndDate != null) {
|
||||
await _scheduleEventEndNotification(subscription);
|
||||
} else {
|
||||
// 이벤트가 비활성화된 경우 이벤트 종료 알림 취소
|
||||
await NotificationService.cancelNotification(
|
||||
'${subscription.id}_event_end'.hashCode,
|
||||
);
|
||||
}
|
||||
|
||||
await refreshSubscriptions();
|
||||
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('구독 업데이트 중 오류 발생: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteSubscription(String id) async {
|
||||
try {
|
||||
await _subscriptionBox.delete(id);
|
||||
await refreshSubscriptions();
|
||||
} catch (e) {
|
||||
debugPrint('구독 삭제 중 오류 발생: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _scheduleNotifications() async {
|
||||
final BuildContext? context = navigatorKey.currentContext;
|
||||
if (context == null) return;
|
||||
|
||||
final notificationProvider = Provider.of<NotificationProvider>(
|
||||
context,
|
||||
listen: false,
|
||||
);
|
||||
|
||||
if (!notificationProvider.isEnabled ||
|
||||
!notificationProvider.isPaymentEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final subscription in _subscriptions) {
|
||||
final notificationDate = subscription.nextBillingDate.subtract(
|
||||
const Duration(days: 3),
|
||||
);
|
||||
|
||||
if (notificationDate.isAfter(DateTime.now())) {
|
||||
await NotificationService.scheduleNotification(
|
||||
id: subscription.id.hashCode,
|
||||
title: '구독 결제 예정 알림',
|
||||
body: '${subscription.serviceName}의 결제가 3일 후 예정되어 있습니다.',
|
||||
scheduledDate: notificationDate,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clearAllSubscriptions() async {
|
||||
_isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
// 모든 알림 취소
|
||||
for (var subscription in _subscriptions) {
|
||||
await NotificationService.cancelSubscriptionNotification(subscription);
|
||||
}
|
||||
|
||||
// 모든 데이터 삭제
|
||||
await _subscriptionBox.clear();
|
||||
_subscriptions = [];
|
||||
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('모든 구독 정보 삭제 중 오류 발생: $e');
|
||||
rethrow;
|
||||
} finally {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 이벤트 종료 알림을 스케줄링합니다.
|
||||
Future<void> _scheduleEventEndNotification(SubscriptionModel subscription) async {
|
||||
if (subscription.eventEndDate != null &&
|
||||
subscription.eventEndDate!.isAfter(DateTime.now())) {
|
||||
await NotificationService.scheduleNotification(
|
||||
id: '${subscription.id}_event_end'.hashCode,
|
||||
title: '이벤트 종료 알림',
|
||||
body: '${subscription.serviceName}의 할인 이벤트가 종료되었습니다.',
|
||||
scheduledDate: subscription.eventEndDate!,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 모든 구독의 이벤트 상태를 확인하고 업데이트합니다.
|
||||
Future<void> checkAndUpdateEventStatus() async {
|
||||
bool hasChanges = false;
|
||||
|
||||
for (var subscription in _subscriptions) {
|
||||
// 이벤트가 종료되었지만 아직 활성화되어 있는 경우
|
||||
if (subscription.isEventActive &&
|
||||
subscription.eventEndDate != null &&
|
||||
subscription.eventEndDate!.isBefore(DateTime.now())) {
|
||||
|
||||
subscription.isEventActive = false;
|
||||
await _subscriptionBox.put(subscription.id, subscription);
|
||||
hasChanges = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
await refreshSubscriptions();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user