Compare commits

..

4 Commits

Author SHA1 Message Date
kolo 64a3f4e34e step 2026-06-29 20:43:13 +03:00
kolo 19db4fe688 step 2026-06-29 19:43:04 +03:00
kolo 00bdd63ea6 step 2026-06-29 19:37:28 +03:00
kolo 7b9bf6d060 step 2026-06-29 16:24:10 +03:00
29 changed files with 1387 additions and 242 deletions
+11
View File
@@ -12,6 +12,8 @@ import '../shared/models/transaction.dart';
import '../shared/paywall/paywall_screen.dart'; import '../shared/paywall/paywall_screen.dart';
import '../shared/services/onboarding_service.dart'; import '../shared/services/onboarding_service.dart';
import '../shared/widgets/pro_screen.dart'; import '../shared/widgets/pro_screen.dart';
import '../shared/widgets/backup_screen.dart';
import '../shared/providers/premium_provider.dart';
final _shellKey = GlobalKey<NavigatorState>(); final _shellKey = GlobalKey<NavigatorState>();
@@ -72,6 +74,15 @@ final appRouter = GoRouter(
path: '/pro', path: '/pro',
builder: (context, state) => const ProScreen(), builder: (context, state) => const ProScreen(),
), ),
GoRoute(
path: '/backup',
redirect: (context, state) {
final container = ProviderScope.containerOf(context);
final isPremium = container.read(isPremiumProvider);
return isPremium ? null : '/pro';
},
builder: (context, state) => const BackupScreen(),
),
], ],
); );
+37
View File
@@ -332,4 +332,41 @@ class AppStrings {
_ru ? 'Предыдущие покупки не найдены' : 'No previous purchases found'; _ru ? 'Предыдущие покупки не найдены' : 'No previous purchases found';
String get proTapToClose => String get proTapToClose =>
_ru ? 'Нажмите чтобы закрыть' : 'Tap anywhere to close'; _ru ? 'Нажмите чтобы закрыть' : 'Tap anywhere to close';
String get backupTitle => _ru ? 'Резервная копия' : 'Backup';
String get backupCreate => _ru ? 'Создать резервную копию' : 'Create Backup';
String get backupRestore => _ru ? 'Восстановить из копии' : 'Restore Backup';
String get backupCreating => _ru ? 'Создание копии...' : 'Creating backup...';
String get backupRestoring => _ru ? 'Восстановление...' : 'Restoring...';
String get backupSuccess =>
_ru ? 'Резервная копия успешно создана!' : 'Backup created successfully!';
String get backupRestoreSuccess =>
_ru ? 'Данные успешно восстановлены!' : 'Data restored successfully!';
String get backupRestoreFailed =>
_ru ? 'Не удалось восстановить данные' : 'Failed to restore data';
String get backupNoFileFound =>
_ru ? 'Резервная копия не найдена' : 'No backup file found';
String get backupTokenMismatch =>
_ru
? 'Этот файл резервной копии принадлежит другому покупателю Premium'
: 'This backup file belongs to another Premium purchaser';
String get backupInvalidFormat =>
_ru ? 'Неверный формат файла резервной копии' : 'Invalid backup file format';
String get backupNoToken =>
_ru
? 'Файл резервной копии не содержит токен покупки'
: 'Backup file does not contain a purchase token';
String get backupRequiresPremium =>
_ru ? 'Резервная копия доступна только для Pro' : 'Backup is a Pro-only feature';
String get backupRequiresSignIn =>
_ru
? 'Войдите в Google аккаунт для работы с резервными копиями'
: 'Sign in to Google to manage backups';
String get backupLastBackup => _ru ? 'Последняя копия' : 'Last backup';
String get backupNever => _ru ? 'Никогда' : 'Never';
String get backupSyncWithDrive =>
_ru ? 'Синхронизация с Google Диском' : 'Google Drive Sync';
String get backupSyncDesc =>
_ru
? 'Резервное копирование данных на ваш Google Диск'
: 'Back up your data to your Google Drive';
} }
@@ -13,9 +13,9 @@ class FeatureLimitException implements Exception {
class AccountRepository { class AccountRepository {
final AppDatabase _db; final AppDatabase _db;
final FeatureFlags _featureFlags; final FeatureFlags Function() _getFeatureFlags;
AccountRepository(this._db, this._featureFlags); AccountRepository(this._db, this._getFeatureFlags);
Stream<List<model.Account>> watchAll() { Stream<List<model.Account>> watchAll() {
return (_db.select(_db.accounts) return (_db.select(_db.accounts)
@@ -167,8 +167,9 @@ class AccountRepository {
Future<int> add(model.Account account) async { Future<int> add(model.Account account) async {
final existing = await getAll(); final existing = await getAll();
final nonMainCount = existing.where((a) => !a.isMain).length; final nonMainCount = existing.where((a) => !a.isMain).length;
if (nonMainCount >= _featureFlags.maxAccounts) { final flags = _getFeatureFlags();
throw FeatureLimitException('Account limit reached (${_featureFlags.maxAccounts})'); if (flags.maxAccounts != -1 && nonMainCount >= flags.maxAccounts) {
throw FeatureLimitException('Account limit reached (${flags.maxAccounts})');
} }
return await _db.into(_db.accounts).insert( return await _db.into(_db.accounts).insert(
AccountsCompanion.insert( AccountsCompanion.insert(
+1 -2
View File
@@ -28,8 +28,7 @@ final transactionRepositoryProvider = Provider<TransactionRepository>((ref) {
final accountRepositoryProvider = Provider<AccountRepository>((ref) { final accountRepositoryProvider = Provider<AccountRepository>((ref) {
final db = ref.watch(appDatabaseProvider); final db = ref.watch(appDatabaseProvider);
final flags = ref.watch(featureFlagsProvider); return AccountRepository(db, () => ref.read(featureFlagsProvider));
return AccountRepository(db, flags);
}); });
final storageServiceProvider = Provider<StorageService>((ref) { final storageServiceProvider = Provider<StorageService>((ref) {
+87 -52
View File
@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import '../../core/l10n/locale_provider.dart'; import '../../core/l10n/locale_provider.dart';
import '../../core/services/haptic_service.dart'; import '../../core/services/haptic_service.dart';
import 'provider.dart'; import 'provider.dart';
import 'widgets/fade_slide_in.dart';
import 'widgets/onboarding_page.dart'; import 'widgets/onboarding_page.dart';
import 'widgets/onboarding_page_indicator.dart'; import 'widgets/onboarding_page_indicator.dart';
@@ -29,7 +30,7 @@ class _OnboardingScreenState extends ConsumerState<OnboardingScreen> {
if (page == 4) { if (page == 4) {
HapticService.medium(); HapticService.medium();
ref.read(onboardingProvider.notifier).complete(); ref.read(onboardingProvider.notifier).complete();
Future.delayed(const Duration(milliseconds: 400), () { Future.delayed(const Duration(milliseconds: 150), () {
if (mounted) context.go('/dashboard'); if (mounted) context.go('/dashboard');
}); });
} }
@@ -49,67 +50,23 @@ class _OnboardingScreenState extends ConsumerState<OnboardingScreen> {
controller: _controller, controller: _controller,
onPageChanged: _onPageChanged, onPageChanged: _onPageChanged,
children: [ children: [
OnboardingPage.welcome(welcomeText: s.onboardingWelcome), OnboardingPage.welcome(
welcomeText: s.onboardingWelcome,
isActive: currentPage == 0,
),
OnboardingPage.content( OnboardingPage.content(
icon: Icons.currency_exchange_rounded, icon: Icons.currency_exchange_rounded,
headline: s.onboardingMultiCurrencyTitle, headline: s.onboardingMultiCurrencyTitle,
description: s.onboardingMultiCurrencyBody, description: s.onboardingMultiCurrencyBody,
isActive: currentPage == 1,
), ),
OnboardingPage.content( OnboardingPage.content(
icon: Icons.credit_card_rounded, icon: Icons.credit_card_rounded,
headline: s.onboardingCardsTitle, headline: s.onboardingCardsTitle,
description: s.onboardingCardsBody, description: s.onboardingCardsBody,
isActive: currentPage == 2,
), ),
Center( _ReadyPage(isActive: currentPage == 3),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.waving_hand_rounded,
size: 72,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 28),
Text(
s.onboardingReadyTitle,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 12),
Text(
s.onboardingReadyBody,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.onSurface.withOpacity(0.5),
),
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
s.onboardingSwipeRight,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 8),
Icon(
Icons.arrow_forward_rounded,
color: Theme.of(context).colorScheme.primary,
),
],
),
],
),
),
),
const SizedBox.shrink(), const SizedBox.shrink(),
], ],
), ),
@@ -127,3 +84,81 @@ class _OnboardingScreenState extends ConsumerState<OnboardingScreen> {
); );
} }
} }
class _ReadyPage extends ConsumerWidget {
final bool isActive;
const _ReadyPage({required this.isActive});
@override
Widget build(BuildContext context, WidgetRef ref) {
final s = ref.watch(stringsProvider);
final colorScheme = Theme.of(context).colorScheme;
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeSlideIn(
active: isActive,
child: Icon(
Icons.waving_hand_rounded,
size: 72,
color: colorScheme.primary,
),
),
const SizedBox(height: 28),
FadeSlideIn(
active: isActive,
delay: const Duration(milliseconds: 150),
child: Text(
s.onboardingReadyTitle,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.onSurface,
),
),
),
const SizedBox(height: 12),
FadeSlideIn(
active: isActive,
delay: const Duration(milliseconds: 300),
child: Text(
s.onboardingReadyBody,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withOpacity(0.5),
),
),
),
const SizedBox(height: 24),
FadeSlideIn(
active: isActive,
delay: const Duration(milliseconds: 450),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
s.onboardingSwipeRight,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 8),
Icon(
Icons.arrow_forward_rounded,
color: colorScheme.primary,
),
],
),
),
],
),
),
);
}
}
@@ -62,7 +62,7 @@ class _CashaShimmerTextState extends State<CashaShimmerText>
final shimmer = sin(t * 2 * pi) * 0.08; final shimmer = sin(t * 2 * pi) * 0.08;
final gx = (_tiltY + shimmer).clamp(-1.0, 1.0); final gx = (_tiltY + shimmer).clamp(-1.0, 1.0);
final gy = (_tiltX + shimmer * 0.5).clamp(-1.0, 1.0); final gy = (_tiltX + shimmer * 0.3).clamp(-1.0, 1.0);
return Transform( return Transform(
alignment: Alignment.center, alignment: Alignment.center,
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
class FadeSlideIn extends StatefulWidget {
final bool active;
final Duration delay;
final Duration duration;
final Widget child;
const FadeSlideIn({
required this.active,
required this.child,
this.delay = Duration.zero,
this.duration = const Duration(milliseconds: 500),
super.key,
});
@override
State<FadeSlideIn> createState() => _FadeSlideInState();
}
class _FadeSlideInState extends State<FadeSlideIn>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _opacity;
late final Animation<Offset> _offset;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: widget.duration,
);
_opacity = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeOut),
);
_offset = Tween<Offset>(
begin: const Offset(0, 0.15),
end: Offset.zero,
).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));
}
@override
void didUpdateWidget(covariant FadeSlideIn oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.active && !oldWidget.active) {
_controller.reset();
Future.delayed(widget.delay, () {
if (mounted) _controller.forward();
});
} else if (!widget.active && oldWidget.active) {
_controller.reset();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Opacity(
opacity: _opacity.value,
child: FractionalTranslation(
translation: _offset.value,
child: child,
),
);
},
child: widget.child,
);
}
}
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'casha_shimmer_text.dart'; import 'casha_shimmer_text.dart';
import 'fade_slide_in.dart';
class OnboardingPage extends StatelessWidget { class OnboardingPage extends StatelessWidget {
final IconData? icon; final IconData? icon;
@@ -7,9 +8,13 @@ class OnboardingPage extends StatelessWidget {
final String? description; final String? description;
final String? welcomeText; final String? welcomeText;
final bool isWelcomePage; final bool isWelcomePage;
final bool isActive;
const OnboardingPage.welcome({required this.welcomeText, super.key}) const OnboardingPage.welcome({
: icon = null, required this.welcomeText,
this.isActive = false,
super.key,
}) : icon = null,
headline = null, headline = null,
description = null, description = null,
isWelcomePage = true; isWelcomePage = true;
@@ -18,6 +23,7 @@ class OnboardingPage extends StatelessWidget {
required this.icon, required this.icon,
required this.headline, required this.headline,
required this.description, required this.description,
this.isActive = false,
super.key, super.key,
}) : welcomeText = null, }) : welcomeText = null,
isWelcomePage = false; isWelcomePage = false;
@@ -59,34 +65,45 @@ class OnboardingPage extends StatelessWidget {
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Container( FadeSlideIn(
padding: const EdgeInsets.all(24), active: isActive,
decoration: BoxDecoration( child: Container(
color: colorScheme.primary.withOpacity(0.12), padding: const EdgeInsets.all(24),
shape: BoxShape.circle, decoration: BoxDecoration(
), color: colorScheme.primary.withOpacity(0.12),
child: Icon( shape: BoxShape.circle,
icon, ),
size: 64, child: Icon(
color: colorScheme.primary, icon,
size: 64,
color: colorScheme.primary,
),
), ),
), ),
const SizedBox(height: 32), const SizedBox(height: 32),
Text( FadeSlideIn(
headline!, active: isActive,
textAlign: TextAlign.center, delay: const Duration(milliseconds: 150),
style: Theme.of(context).textTheme.headlineSmall?.copyWith( child: Text(
fontWeight: FontWeight.bold, headline!,
color: colorScheme.onSurface, textAlign: TextAlign.center,
), style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.onSurface,
),
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Text( FadeSlideIn(
description!, active: isActive,
textAlign: TextAlign.center, delay: const Duration(milliseconds: 300),
style: Theme.of(context).textTheme.bodyMedium?.copyWith( child: Text(
color: colorScheme.onSurface.withOpacity(0.6), description!,
), textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6),
),
),
), ),
], ],
), ),
+15 -14
View File
@@ -117,22 +117,23 @@ class SettingsScreen extends ConsumerWidget {
padding: const EdgeInsets.fromLTRB(20, 16, 20, 40), padding: const EdgeInsets.fromLTRB(20, 16, 20, 40),
children: [ children: [
const ProSubscriptionCard(), const ProSubscriptionCard(),
const SizedBox(height: 16), const SizedBox(height: 12),
const ThemeSection(),
const SizedBox(height: 16),
const CardTextColorSection(),
const SizedBox(height: 16),
const HapticSection(),
const SizedBox(height: 16),
const CurrencyConversionsSection(),
const SizedBox(height: 16),
const _BiometricSection(),
const LanguageSection(),
const SizedBox(height: 16),
const CurrencySection(), const CurrencySection(),
const SizedBox(height: 16), const SizedBox(height: 12),
const ThemeSection(),
const SizedBox(height: 12),
const LanguageSection(),
const SizedBox(height: 12),
const _BiometricSection(),
const SizedBox(height: 12),
const CardTextColorSection(),
const SizedBox(height: 12),
const HapticSection(),
const SizedBox(height: 12),
const AmountFormatSection(), const AmountFormatSection(),
const SizedBox(height: 16), const SizedBox(height: 12),
const CurrencyConversionsSection(),
const SizedBox(height: 12),
const CategoriesSection(), const CategoriesSection(),
const SizedBox(height: 24), const SizedBox(height: 24),
Text( Text(
@@ -14,7 +14,7 @@ class CardTextColorSection extends ConsumerWidget {
final isDark = Theme.of(context).brightness == Brightness.dark; final isDark = Theme.of(context).brightness == Brightness.dark;
return Container( return Container(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface, color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -49,7 +49,7 @@ class CardTextColorSection extends ConsumerWidget {
), ),
], ],
), ),
const SizedBox(height: 16), const SizedBox(height: 12),
Row( Row(
children: [ children: [
Expanded( Expanded(
@@ -113,7 +113,7 @@ class _CardTextColorOption extends StatelessWidget {
onTap: onTap, onTap: onTap,
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(vertical: 12), padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: isSelected color: isSelected
? AppColors.accent.withOpacity(0.15) ? AppColors.accent.withOpacity(0.15)
@@ -15,7 +15,7 @@ class CurrencySection extends ConsumerWidget {
final isDark = Theme.of(context).brightness == Brightness.dark; final isDark = Theme.of(context).brightness == Brightness.dark;
return Container( return Container(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface, color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -52,7 +52,7 @@ class CurrencySection extends ConsumerWidget {
), ),
], ],
), ),
const SizedBox(height: 16), const SizedBox(height: 12),
Row( Row(
children: ['USD', 'EUR', 'BYN', 'RUB'].map((code) { children: ['USD', 'EUR', 'BYN', 'RUB'].map((code) {
final info = currencyMap[code]!; final info = currencyMap[code]!;
@@ -65,7 +65,7 @@ class CurrencySection extends ConsumerWidget {
ref.read(currencyProvider.notifier).setCurrency(code); ref.read(currencyProvider.notifier).setCurrency(code);
}, },
child: Container( child: Container(
padding: const EdgeInsets.symmetric(vertical: 12), padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: isSelected color: isSelected
? AppColors.accent.withOpacity(0.2) ? AppColors.accent.withOpacity(0.2)
@@ -83,12 +83,18 @@ class CurrencySection extends ConsumerWidget {
child: Column( child: Column(
children: [ children: [
code == 'BYN' code == 'BYN'
? BynSign( ? SizedBox(
fontSize: 28, height: 28,
color: isSelected child: Align(
? AppColors.accent alignment: Alignment.center,
: Theme.of(context).colorScheme.onSurface child: BynSign(
.withOpacity(0.6), fontSize: 24,
color: isSelected
? AppColors.accent
: Theme.of(context).colorScheme.onSurface
.withOpacity(0.6),
),
),
) )
: Text( : Text(
info.symbol, info.symbol,
@@ -14,7 +14,7 @@ class ThemeSection extends ConsumerWidget {
final isDark = Theme.of(context).brightness == Brightness.dark; final isDark = Theme.of(context).brightness == Brightness.dark;
return Container( return Container(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface, color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -51,7 +51,7 @@ class ThemeSection extends ConsumerWidget {
), ),
], ],
), ),
const SizedBox(height: 16), const SizedBox(height: 12),
Row( Row(
children: [ children: [
Expanded( Expanded(
@@ -109,7 +109,7 @@ class _ThemeOption extends StatelessWidget {
onTap: onTap, onTap: onTap,
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(vertical: 12), padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: isSelected color: isSelected
? AppColors.accent.withOpacity(0.15) ? AppColors.accent.withOpacity(0.15)
+8
View File
@@ -7,6 +7,9 @@ import 'core/services/haptic_service.dart';
import 'data/database/app_database.dart'; import 'data/database/app_database.dart';
import 'features/dashboard/provider.dart'; import 'features/dashboard/provider.dart';
import 'shared/services/onboarding_service.dart'; import 'shared/services/onboarding_service.dart';
import 'shared/services/billing_service.dart';
import 'shared/services/premium_manager.dart';
import 'shared/providers/billing_provider.dart';
void main() async { void main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
@@ -22,11 +25,16 @@ void main() async {
final database = AppDatabase(); final database = AppDatabase();
final billing = PlayBillingService();
final premiumManager = PremiumManager(prefs, billing);
await premiumManager.autoRestore();
runApp( runApp(
ProviderScope( ProviderScope(
overrides: [ overrides: [
sharedPreferencesProvider.overrideWithValue(prefs), sharedPreferencesProvider.overrideWithValue(prefs),
appDatabaseProvider.overrideWithValue(database), appDatabaseProvider.overrideWithValue(database),
billingServiceProvider.overrideWithValue(billing),
], ],
child: const App(), child: const App(),
), ),
@@ -0,0 +1,8 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/backup_service.dart';
import 'premium_provider.dart';
final backupServiceProvider = Provider<BackupService>((ref) {
final token = ref.watch(purchaseTokenProvider) ?? '';
return BackupService(token);
});
+1 -3
View File
@@ -1,8 +1,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../features/dashboard/provider.dart';
import '../services/billing_service.dart'; import '../services/billing_service.dart';
final billingServiceProvider = Provider<BillingService>((ref) { final billingServiceProvider = Provider<BillingService>((ref) {
final prefs = ref.watch(sharedPreferencesProvider); return PlayBillingService();
return MockBillingService(prefs);
}); });
+10 -12
View File
@@ -1,29 +1,27 @@
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../features/dashboard/provider.dart'; import '../../features/dashboard/provider.dart';
import '../models/user_model.dart'; import '../models/user_model.dart';
import '../services/premium_manager.dart';
import 'billing_provider.dart';
class CurrentUserNotifier extends Notifier<UserModel> { class CurrentUserNotifier extends Notifier<UserModel> {
static const _key = 'user_plan';
@override @override
UserModel build() { UserModel build() {
final prefs = ref.watch(sharedPreferencesProvider); final prefs = ref.watch(sharedPreferencesProvider);
final planName = prefs.getString(_key); final billing = ref.watch(billingServiceProvider);
final plan = UserPlan.values.firstWhere( final manager = PremiumManager(prefs, billing);
(e) => e.name == planName, return UserModel(plan: manager.currentPlan);
orElse: () => UserPlan.free,
);
return UserModel(plan: plan);
} }
Future<void> setPlan(UserPlan plan) async { Future<void> setPlan(UserPlan plan) async {
final prefs = ref.read(sharedPreferencesProvider);
state = UserModel(plan: plan); state = UserModel(plan: plan);
await prefs.setString(_key, plan.name);
} }
Future<void> toggleVip() async { Future<void> refreshFromPremium() async {
await setPlan(state.isVip ? UserPlan.free : UserPlan.vip); final prefs = ref.read(sharedPreferencesProvider);
final billing = ref.read(billingServiceProvider);
final manager = PremiumManager(prefs, billing);
state = UserModel(plan: manager.currentPlan);
} }
} }
@@ -0,0 +1,18 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../services/google_drive_service.dart';
final googleDriveServiceProvider = Provider<GoogleDriveService>((ref) {
final signIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/drive.appdata',
],
);
return GoogleDriveService(signIn);
});
final googleDriveUserProvider = StreamProvider<GoogleSignInAccount?>((ref) {
final service = ref.watch(googleDriveServiceProvider);
return service.onUserChanged;
});
@@ -0,0 +1,20 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../features/dashboard/provider.dart';
import '../services/premium_manager.dart';
import 'billing_provider.dart';
final premiumManagerProvider = Provider<PremiumManager>((ref) {
final prefs = ref.watch(sharedPreferencesProvider);
final billing = ref.watch(billingServiceProvider);
return PremiumManager(prefs, billing);
});
final isPremiumProvider = Provider<bool>((ref) {
final manager = ref.watch(premiumManagerProvider);
return manager.isPremium;
});
final purchaseTokenProvider = Provider<String?>((ref) {
final manager = ref.watch(premiumManagerProvider);
return manager.purchaseToken;
});
+72
View File
@@ -0,0 +1,72 @@
import 'dart:convert';
import 'dart:typed_data';
class BackupData {
final String ownerPurchaseToken;
final DateTime createdAt;
final Map<String, dynamic> payload;
const BackupData({
required this.ownerPurchaseToken,
required this.createdAt,
required this.payload,
});
Map<String, dynamic> toJson() => {
'owner_purchase_token': ownerPurchaseToken,
'created_at': createdAt.toIso8601String(),
'payload': payload,
};
factory BackupData.fromJson(Map<String, dynamic> json) {
return BackupData(
ownerPurchaseToken: json['owner_purchase_token'] as String? ?? '',
createdAt: DateTime.tryParse(json['created_at'] as String? ?? '') ??
DateTime.now(),
payload: json['payload'] as Map<String, dynamic>? ?? {},
);
}
}
enum BackupVerifyResult { ok, tokenMismatch, noToken, invalidFormat }
class BackupService {
String _currentPurchaseToken;
BackupService(this._currentPurchaseToken);
void updatePurchaseToken(String token) {
_currentPurchaseToken = token;
}
String get currentPurchaseToken => _currentPurchaseToken;
Uint8List createBackup(Map<String, dynamic> payload) {
final data = BackupData(
ownerPurchaseToken: _currentPurchaseToken,
createdAt: DateTime.now(),
payload: payload,
);
final json = jsonEncode(data.toJson());
return Uint8List.fromList(utf8.encode(json));
}
(BackupVerifyResult, BackupData?) verifyAndParse(Uint8List raw) {
try {
final json = jsonDecode(utf8.decode(raw)) as Map<String, dynamic>;
final data = BackupData.fromJson(json);
if (data.ownerPurchaseToken.isEmpty) {
return (BackupVerifyResult.noToken, null);
}
if (data.ownerPurchaseToken != _currentPurchaseToken) {
return (BackupVerifyResult.tokenMismatch, null);
}
return (BackupVerifyResult.ok, data);
} catch (e) {
return (BackupVerifyResult.invalidFormat, null);
}
}
}
+179 -21
View File
@@ -1,34 +1,192 @@
import 'package:shared_preferences/shared_preferences.dart'; import 'dart:async';
import '../models/user_model.dart'; import 'package:flutter/foundation.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
class PurchaseResult {
final bool success;
final String? purchaseToken;
final String? error;
const PurchaseResult({this.success = false, this.purchaseToken, this.error});
factory PurchaseResult.ok(String token) =>
PurchaseResult(success: true, purchaseToken: token);
factory PurchaseResult.failed([String? error]) =>
PurchaseResult(success: false, error: error);
}
abstract class BillingService { abstract class BillingService {
Future<bool> purchasePro(); static const proProductId = 'casha_pro_lifetime';
Future<bool> restorePurchases();
Future<UserPlan> getCurrentPlan(); Future<PurchaseResult> purchasePro();
Future<PurchaseResult> restorePurchases();
Future<PurchaseResult> queryPastPurchase();
Future<void> completePurchase(String purchaseToken);
Stream<List<PurchaseDetails>> get purchaseStream;
Future<void> dispose();
} }
class MockBillingService implements BillingService { class PlayBillingService implements BillingService {
static const _key = 'user_plan'; final InAppPurchase _inAppPurchase = InAppPurchase.instance;
final SharedPreferences _prefs; late final StreamSubscription<List<PurchaseDetails>> _sub;
final _controller = StreamController<List<PurchaseDetails>>.broadcast();
MockBillingService(this._prefs); PlayBillingService() {
_sub = _inAppPurchase.purchaseStream.listen((purchases) {
@override _controller.add(purchases);
Future<bool> purchasePro() async { });
await Future.delayed(const Duration(seconds: 1));
await _prefs.setString(_key, 'vip');
return true;
} }
@override @override
Future<bool> restorePurchases() async { Stream<List<PurchaseDetails>> get purchaseStream => _controller.stream;
await Future.delayed(const Duration(seconds: 1));
return false; @override
Future<PurchaseResult> purchasePro() async {
final available = await _inAppPurchase.isAvailable();
if (!available) {
return PurchaseResult.failed('Billing not available');
}
final response = await _inAppPurchase.queryProductDetails(
{BillingService.proProductId},
);
if (response.productDetails.isEmpty) {
return PurchaseResult.failed('Product not found');
}
final product = response.productDetails.first;
final purchaseParam = PurchaseParam(productDetails: product);
final started = await _inAppPurchase.buyNonConsumable(
purchaseParam: purchaseParam,
);
if (!started) {
return PurchaseResult.failed('Could not start purchase');
}
final completer = Completer<PurchaseResult>();
late StreamSubscription sub;
sub = purchaseStream.timeout(
const Duration(seconds: 60),
onTimeout: (sink) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.failed('Purchase timed out'));
}
sub.cancel();
},
).listen((purchases) {
for (final p in purchases) {
if (p.productID == BillingService.proProductId &&
p.status == PurchaseStatus.purchased) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
}
sub.cancel();
return;
}
if (p.status == PurchaseStatus.error) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.failed(p.error?.message));
}
sub.cancel();
return;
}
}
});
return completer.future;
} }
@override @override
Future<UserPlan> getCurrentPlan() async { Future<PurchaseResult> restorePurchases() async {
final value = _prefs.getString(_key); final available = await _inAppPurchase.isAvailable();
return value == 'vip' ? UserPlan.vip : UserPlan.free; if (!available) {
return PurchaseResult.failed('Billing not available');
}
await _inAppPurchase.restorePurchases();
final completer = Completer<PurchaseResult>();
late StreamSubscription sub;
sub = purchaseStream.timeout(
const Duration(seconds: 15),
onTimeout: (sink) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.failed('Restore timed out'));
}
sub.cancel();
},
).listen((purchases) {
for (final p in purchases) {
if (p.productID == BillingService.proProductId &&
(p.status == PurchaseStatus.restored ||
p.status == PurchaseStatus.purchased)) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
}
sub.cancel();
return;
}
}
});
return completer.future;
}
@override
Future<PurchaseResult> queryPastPurchase() async {
final available = await _inAppPurchase.isAvailable();
if (!available) {
return const PurchaseResult();
}
final response = await _inAppPurchase.queryProductDetails(
{BillingService.proProductId},
);
if (response.productDetails.isEmpty) {
return const PurchaseResult();
}
final completer = Completer<PurchaseResult>();
late StreamSubscription sub;
sub = purchaseStream.timeout(
const Duration(seconds: 10),
onTimeout: (sink) {
if (!completer.isCompleted) {
completer.complete(const PurchaseResult());
}
sub.cancel();
},
).listen((purchases) {
for (final p in purchases) {
if (p.productID == BillingService.proProductId &&
(p.status == PurchaseStatus.restored ||
p.status == PurchaseStatus.purchased)) {
if (!completer.isCompleted) {
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
}
sub.cancel();
return;
}
}
});
await _inAppPurchase.restorePurchases();
return completer.future;
}
@override
Future<void> completePurchase(String purchaseToken) async {
if (kDebugMode) {
print('completePurchase: $purchaseToken');
}
}
@override
Future<void> dispose() async {
await _sub.cancel();
await _controller.close();
} }
} }
+4 -1
View File
@@ -4,7 +4,10 @@ import 'package:google_sign_in/google_sign_in.dart';
class GoogleAuthService { class GoogleAuthService {
final GoogleSignIn _googleSignIn; final GoogleSignIn _googleSignIn;
GoogleAuthService() : _googleSignIn = GoogleSignIn(scopes: ['email']); GoogleAuthService() : _googleSignIn = GoogleSignIn(scopes: [
'email',
'https://www.googleapis.com/auth/drive.appdata',
]);
GoogleSignInAccount? get currentUser => _googleSignIn.currentUser; GoogleSignInAccount? get currentUser => _googleSignIn.currentUser;
@@ -0,0 +1,147 @@
import 'dart:typed_data';
import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart';
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
class DriveBackupResult {
final bool success;
final String? error;
final String? fileId;
final DateTime? modifiedTime;
const DriveBackupResult({this.success = false, this.error, this.fileId, this.modifiedTime});
factory DriveBackupResult.ok(String fileId, DateTime modifiedTime) =>
DriveBackupResult(success: true, fileId: fileId, modifiedTime: modifiedTime);
factory DriveBackupResult.failed(String error) =>
DriveBackupResult(success: false, error: error);
}
class GoogleDriveService {
static const _fileName = 'casha_backup.json';
static const _appDataFolder = 'appDataFolder';
final GoogleSignIn _googleSignIn;
GoogleDriveService(this._googleSignIn);
GoogleSignInAccount? get currentUser => _googleSignIn.currentUser;
Stream<GoogleSignInAccount?> get onUserChanged => _googleSignIn.onCurrentUserChanged;
Future<void> signIn() async {
await _googleSignIn.signIn();
}
Future<void> signOut() async {
await _googleSignIn.signOut();
}
Future<drive.DriveApi?> _getDriveApi() async {
if (_googleSignIn.currentUser == null) return null;
final httpClient = await _googleSignIn.authenticatedClient();
if (httpClient == null) return null;
return drive.DriveApi(httpClient);
}
Future<String?> _findExistingFile(drive.DriveApi api) async {
final list = await api.files.list(
spaces: _appDataFolder,
q: "name = '$_fileName' and trashed = false",
$fields: 'files(id, name, modifiedTime)',
);
return list.files?.isNotEmpty == true ? list.files!.first.id : null;
}
Future<DriveBackupResult> uploadBackup(Uint8List data) async {
final api = await _getDriveApi();
if (api == null) {
return DriveBackupResult.failed('Not authenticated');
}
try {
final existingId = await _findExistingFile(api);
final media = drive.Media(
Stream<List<int>>.fromIterable([data.toList()]),
data.length,
);
if (existingId != null) {
final file = drive.File(
name: _fileName,
modifiedTime: DateTime.now(),
);
final updated = await api.files.update(
file,
existingId,
uploadMedia: media,
$fields: 'id, modifiedTime',
);
return DriveBackupResult.ok(
updated.id!,
updated.modifiedTime!,
);
} else {
final file = drive.File(
name: _fileName,
parents: [_appDataFolder],
modifiedTime: DateTime.now(),
);
final created = await api.files.create(
file,
uploadMedia: media,
$fields: 'id, modifiedTime',
);
return DriveBackupResult.ok(
created.id!,
created.modifiedTime!,
);
}
} catch (e) {
return DriveBackupResult.failed(e.toString());
}
}
Future<Uint8List?> downloadBackup() async {
final api = await _getDriveApi();
if (api == null) return null;
try {
final fileId = await _findExistingFile(api);
if (fileId == null) return null;
final media = await api.files.get(
fileId,
downloadOptions: drive.DownloadOptions.fullMedia,
) as drive.Media;
final bytes = <int>[];
await for (final chunk in media.stream) {
bytes.addAll(chunk);
}
return Uint8List.fromList(bytes);
} catch (e) {
return null;
}
}
Future<DateTime?> getLastBackupTime() async {
final api = await _getDriveApi();
if (api == null) return null;
try {
final list = await api.files.list(
spaces: _appDataFolder,
q: "name = '$_fileName' and trashed = false",
$fields: 'files(id, name, modifiedTime)',
);
if (list.files?.isNotEmpty == true) {
return list.files!.first.modifiedTime;
}
return null;
} catch (e) {
return null;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user_model.dart';
import 'billing_service.dart';
class PremiumManager {
static const _keyIsPremium = 'is_premium';
static const _keyPurchaseToken = 'purchase_token';
final SharedPreferences _prefs;
final BillingService _billing;
PremiumManager(this._prefs, this._billing);
bool get isPremium => _prefs.getBool(_keyIsPremium) ?? false;
String? get purchaseToken => _prefs.getString(_keyPurchaseToken);
Future<void> _setPremium(bool value, String? token) async {
await _prefs.setBool(_keyIsPremium, value);
if (token != null) {
await _prefs.setString(_keyPurchaseToken, token);
} else if (!value) {
await _prefs.remove(_keyPurchaseToken);
}
}
Future<PurchaseResult> purchase() async {
final result = await _billing.purchasePro();
if (result.success && result.purchaseToken != null) {
await _setPremium(true, result.purchaseToken);
await _billing.completePurchase(result.purchaseToken!);
}
return result;
}
Future<PurchaseResult> restore() async {
final result = await _billing.restorePurchases();
if (result.success && result.purchaseToken != null) {
await _setPremium(true, result.purchaseToken);
await _billing.completePurchase(result.purchaseToken!);
}
return result;
}
Future<void> autoRestore() async {
if (isPremium) return;
final result = await _billing.queryPastPurchase();
if (result.success && result.purchaseToken != null) {
await _setPremium(true, result.purchaseToken);
await _billing.completePurchase(result.purchaseToken!);
}
}
UserPlan get currentPlan => isPremium ? UserPlan.vip : UserPlan.free;
Future<void> clear() async {
await _setPremium(false, null);
}
}
+360
View File
@@ -0,0 +1,360 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/l10n/app_strings.dart';
import '../../core/l10n/locale_provider.dart';
import '../../core/services/haptic_service.dart';
import '../providers/backup_provider.dart';
import '../providers/google_drive_provider.dart';
import '../providers/premium_provider.dart';
import 'error_snackbar.dart';
import '../services/backup_service.dart';
class BackupScreen extends ConsumerStatefulWidget {
const BackupScreen({super.key});
@override
ConsumerState<BackupScreen> createState() => _BackupScreenState();
}
class _BackupScreenState extends ConsumerState<BackupScreen> {
bool _backingUp = false;
bool _restoring = false;
DateTime? _lastBackupTime;
@override
void initState() {
super.initState();
_loadLastBackupTime();
}
Future<void> _loadLastBackupTime() async {
final service = ref.read(googleDriveServiceProvider);
final time = await service.getLastBackupTime();
if (mounted) {
setState(() => _lastBackupTime = time);
}
}
Future<void> _handleBackup() async {
final s = ref.read(stringsProvider);
final driveService = ref.read(googleDriveServiceProvider);
if (driveService.currentUser == null) {
showErrorSnackbar(context, s.backupRequiresSignIn);
return;
}
HapticService.light();
setState(() => _backingUp = true);
try {
final backupService = ref.read(backupServiceProvider);
final payload = <String, dynamic>{
'version': 1,
'exported_at': DateTime.now().toIso8601String(),
};
final data = backupService.createBackup(payload);
final result = await driveService.uploadBackup(data);
if (result.success) {
setState(() => _lastBackupTime = result.modifiedTime);
HapticService.medium();
if (mounted) {
showSuccessSnackbar(context, s.backupSuccess);
}
} else {
if (mounted) {
showErrorSnackbar(context, result.error ?? s.backupRestoreFailed);
}
}
} catch (e) {
if (mounted) {
showErrorSnackbar(context, e.toString());
}
} finally {
if (mounted) setState(() => _backingUp = false);
}
}
Future<void> _handleRestore() async {
final s = ref.read(stringsProvider);
final driveService = ref.read(googleDriveServiceProvider);
if (driveService.currentUser == null) {
showErrorSnackbar(context, s.backupRequiresSignIn);
return;
}
HapticService.light();
setState(() => _restoring = true);
try {
final raw = await driveService.downloadBackup();
if (raw == null) {
if (mounted) {
showWarningSnackbar(context, s.backupNoFileFound);
}
return;
}
final backupService = ref.read(backupServiceProvider);
final (result, data) = backupService.verifyAndParse(raw);
switch (result) {
case BackupVerifyResult.ok:
HapticService.medium();
if (mounted) {
showSuccessSnackbar(context, s.backupRestoreSuccess);
}
case BackupVerifyResult.tokenMismatch:
if (mounted) {
showErrorSnackbar(context, s.backupTokenMismatch);
}
case BackupVerifyResult.noToken:
if (mounted) {
showErrorSnackbar(context, s.backupNoToken);
}
case BackupVerifyResult.invalidFormat:
if (mounted) {
showErrorSnackbar(context, s.backupInvalidFormat);
}
}
} catch (e) {
if (mounted) {
showErrorSnackbar(context, e.toString());
}
} finally {
if (mounted) setState(() => _restoring = false);
}
}
@override
Widget build(BuildContext context) {
final s = ref.watch(stringsProvider);
final isPremium = ref.watch(isPremiumProvider);
final driveUserAsync = ref.watch(googleDriveUserProvider);
final driveUser = driveUserAsync.value;
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
body: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 16, 0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back_rounded),
onPressed: () => context.pop(),
),
Text(
s.backupTitle,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w800,
),
),
],
),
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isPremium) ...[
_buildLockedState(context, s, colorScheme),
] else ...[
_buildSyncStatus(context, s, colorScheme, driveUser),
const SizedBox(height: 20),
_buildBackupActions(context, s, colorScheme, driveUser),
const SizedBox(height: 20),
_buildLastBackup(context, s, colorScheme),
],
],
),
),
),
],
),
),
);
}
Widget _buildLockedState(
BuildContext context,
AppStrings s,
ColorScheme colorScheme,
) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: colorScheme.outlineVariant),
),
child: Column(
children: [
Icon(Icons.lock_outline_rounded, size: 48, color: colorScheme.primary),
const SizedBox(height: 16),
Text(
s.backupRequiresPremium,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
FilledButton(
onPressed: () => context.push('/pro'),
child: Text(s.proBuy),
),
],
),
);
}
Widget _buildSyncStatus(
BuildContext context,
AppStrings s,
ColorScheme colorScheme,
dynamic driveUser,
) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: colorScheme.outlineVariant),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
driveUser != null
? Icons.cloud_done_rounded
: Icons.cloud_off_rounded,
color: driveUser != null ? colorScheme.primary : colorScheme.onSurface.withOpacity(0.4),
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
driveUser != null
? s.proSyncEnabled
: s.backupRequiresSignIn,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
],
),
if (driveUser != null) ...[
const SizedBox(height: 8),
Text(
driveUser.email,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6),
),
),
],
],
),
);
}
Widget _buildBackupActions(
BuildContext context,
AppStrings s,
ColorScheme colorScheme,
dynamic driveUser,
) {
final disabled = driveUser == null;
return Column(
children: [
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: (disabled || _backingUp) ? null : _handleBackup,
icon: _backingUp
? SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.onPrimary,
),
)
: const Icon(Icons.backup_outlined),
label: Text(_backingUp ? s.backupCreating : s.backupCreate),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: (disabled || _restoring) ? null : _handleRestore,
icon: _restoring
? SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.primary,
),
)
: const Icon(Icons.restore_rounded),
label: Text(_restoring ? s.backupRestoring : s.backupRestore),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
],
);
}
Widget _buildLastBackup(
BuildContext context,
AppStrings s,
ColorScheme colorScheme,
) {
return Row(
children: [
Icon(
Icons.schedule_rounded,
size: 18,
color: colorScheme.onSurface.withOpacity(0.5),
),
const SizedBox(width: 8),
Text(
'${s.backupLastBackup}: ${_lastBackupTime != null ? _formatDate(_lastBackupTime!) : s.backupNever}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurface.withOpacity(0.5),
),
),
],
);
}
String _formatDate(DateTime dt) {
final d = dt.toLocal();
return '${d.day.toString().padLeft(2, '0')}.${d.month.toString().padLeft(2, '0')}.${d.year} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
}
+23 -26
View File
@@ -4,11 +4,9 @@ import 'package:go_router/go_router.dart';
import '../../core/l10n/app_strings.dart'; import '../../core/l10n/app_strings.dart';
import '../../core/l10n/locale_provider.dart'; import '../../core/l10n/locale_provider.dart';
import '../../core/services/haptic_service.dart'; import '../../core/services/haptic_service.dart';
import '../feature_flags/feature_flags_provider.dart';
import '../models/user_model.dart';
import '../providers/billing_provider.dart';
import '../providers/current_user_provider.dart'; import '../providers/current_user_provider.dart';
import '../providers/google_auth_provider.dart'; import '../providers/google_drive_provider.dart';
import '../providers/premium_provider.dart';
import 'error_snackbar.dart'; import 'error_snackbar.dart';
class ProScreen extends ConsumerStatefulWidget { class ProScreen extends ConsumerStatefulWidget {
@@ -27,9 +25,9 @@ class _ProScreenState extends ConsumerState<ProScreen>
late final Animation<double> _successScale; late final Animation<double> _successScale;
static const _gradientColors = [ static const _gradientColors = [
Color(0xFF1A237E), Color(0xFF283593),
Color(0xFF6A1B9A), Color(0xFF5E35B1),
Color(0xFFE65100), Color(0xFFD81B60),
]; ];
@override @override
@@ -68,10 +66,9 @@ class _ProScreenState extends ConsumerState<ProScreen>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final s = ref.watch(stringsProvider); final s = ref.watch(stringsProvider);
final flags = ref.watch(featureFlagsProvider); final isPremium = ref.watch(isPremiumProvider);
final isVip = flags.maxAccounts != 3; final driveUserAsync = ref.watch(googleDriveUserProvider);
final googleUserAsync = ref.watch(googleCurrentUserProvider); final driveUser = driveUserAsync.value;
final googleUser = googleUserAsync.value;
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
return Stack( return Stack(
@@ -88,18 +85,18 @@ class _ProScreenState extends ConsumerState<ProScreen>
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const SizedBox(height: 4), const SizedBox(height: 4),
_buildHeroBanner(context, s, colorScheme, isVip), _buildHeroBanner(context, s, colorScheme, isPremium),
const SizedBox(height: 20), const SizedBox(height: 20),
_buildFeatureList(context, s, colorScheme), _buildFeatureList(context, s, colorScheme),
const SizedBox(height: 16), const SizedBox(height: 16),
if (isVip) ...[ if (isPremium) ...[
_buildProActiveSection(context, s, colorScheme, googleUser), _buildProActiveSection(context, s, colorScheme, driveUser),
], ],
], ],
), ),
), ),
), ),
_buildBottomBar(context, s, colorScheme, isVip), _buildBottomBar(context, s, colorScheme, isPremium),
], ],
), ),
), ),
@@ -476,17 +473,17 @@ class _ProScreenState extends ConsumerState<ProScreen>
HapticService.light(); HapticService.light();
setState(() => _purchasing = true); setState(() => _purchasing = true);
try { try {
final billing = ref.read(billingServiceProvider); final manager = ref.read(premiumManagerProvider);
final success = await billing.purchasePro(); final result = await manager.purchase();
if (success) { if (result.success) {
await ref.read(currentUserProvider.notifier).setPlan(UserPlan.vip); await ref.read(currentUserProvider.notifier).refreshFromPremium();
if (mounted) { if (mounted) {
_showSuccessOverlay(); _showSuccessOverlay();
HapticService.medium(); HapticService.medium();
} }
} else { } else {
if (mounted) { if (mounted) {
showErrorSnackbar(context, ref.read(stringsProvider).proPurchaseFailed); showErrorSnackbar(context, result.error ?? ref.read(stringsProvider).proPurchaseFailed);
} }
} }
} catch (e) { } catch (e) {
@@ -502,10 +499,10 @@ class _ProScreenState extends ConsumerState<ProScreen>
HapticService.light(); HapticService.light();
setState(() => _restoring = true); setState(() => _restoring = true);
try { try {
final billing = ref.read(billingServiceProvider); final manager = ref.read(premiumManagerProvider);
final success = await billing.restorePurchases(); final result = await manager.restore();
if (success) { if (result.success) {
await ref.read(currentUserProvider.notifier).setPlan(UserPlan.vip); await ref.read(currentUserProvider.notifier).refreshFromPremium();
if (mounted) { if (mounted) {
_showSuccessOverlay(); _showSuccessOverlay();
HapticService.medium(); HapticService.medium();
@@ -527,7 +524,7 @@ class _ProScreenState extends ConsumerState<ProScreen>
Future<void> _handleGoogleSignIn() async { Future<void> _handleGoogleSignIn() async {
HapticService.light(); HapticService.light();
try { try {
final service = ref.read(googleAuthProvider); final service = ref.read(googleDriveServiceProvider);
await service.signIn(); await service.signIn();
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
@@ -539,7 +536,7 @@ class _ProScreenState extends ConsumerState<ProScreen>
Future<void> _handleGoogleSignOut() async { Future<void> _handleGoogleSignOut() async {
HapticService.light(); HapticService.light();
try { try {
final service = ref.read(googleAuthProvider); final service = ref.read(googleDriveServiceProvider);
await service.signOut(); await service.signOut();
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
+111 -66
View File
@@ -3,28 +3,27 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import '../../core/l10n/locale_provider.dart'; import '../../core/l10n/locale_provider.dart';
import '../../core/services/haptic_service.dart'; import '../../core/services/haptic_service.dart';
import '../feature_flags/feature_flags_provider.dart'; import '../providers/google_drive_provider.dart';
import '../providers/google_auth_provider.dart'; import '../providers/premium_provider.dart';
class ProSubscriptionCard extends ConsumerWidget { class ProSubscriptionCard extends ConsumerWidget {
const ProSubscriptionCard({super.key}); const ProSubscriptionCard({super.key});
static const _gradientColors = [ static const _gradientColors = [
Color(0xFF1A237E), Color(0xFF283593),
Color(0xFF6A1B9A), Color(0xFF5E35B1),
Color(0xFFE65100), Color(0xFFD81B60),
]; ];
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final s = ref.watch(stringsProvider); final s = ref.watch(stringsProvider);
final flags = ref.watch(featureFlagsProvider); final isPremium = ref.watch(isPremiumProvider);
final isVip = flags.maxAccounts != 3; final driveUserAsync = ref.watch(googleDriveUserProvider);
final googleUserAsync = ref.watch(googleCurrentUserProvider); final driveUser = driveUserAsync.value;
final googleUser = googleUserAsync.value;
return Container( return Container(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
decoration: BoxDecoration( decoration: BoxDecoration(
gradient: const LinearGradient( gradient: const LinearGradient(
begin: Alignment.topLeft, begin: Alignment.topLeft,
@@ -39,85 +38,131 @@ class ProSubscriptionCard extends ConsumerWidget {
Row( Row(
children: [ children: [
Container( Container(
padding: const EdgeInsets.all(10), padding: const EdgeInsets.all(12),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withOpacity(0.15), color: Colors.white.withOpacity(0.15),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: Icon( child: Icon(
isVip ? Icons.verified_rounded : Icons.workspace_premium_rounded, isPremium
? Icons.verified_rounded
: Icons.workspace_premium_rounded,
color: Colors.white, color: Colors.white,
size: 24, size: 28,
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 14),
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
s.proTitle, s.proTitle,
style: Theme.of(context).textTheme.titleLarge?.copyWith( style:
fontWeight: FontWeight.w900, Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.white, fontWeight: FontWeight.w900,
), color: Colors.white,
),
),
const SizedBox(height: 4),
Text(
isPremium ? s.proActive : s.proSubtitle,
style: isPremium
? Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.white.withOpacity(0.9),
fontWeight: FontWeight.w600,
)
: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white.withOpacity(0.7),
),
), ),
if (isVip) ...[
const SizedBox(height: 2),
Text(
googleUser != null
? '${s.proActive} \u2705'
: s.proActive,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white.withOpacity(0.9),
fontWeight: FontWeight.w600,
),
),
],
], ],
), ),
), ),
OutlinedButton(
onPressed: () {
HapticService.light();
context.push('/pro');
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(color: Colors.white.withOpacity(0.4), width: 1.5),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: Text(
s.proAboutPro,
style: const TextStyle(fontWeight: FontWeight.w700),
),
),
], ],
), ),
if (isVip && googleUser == null) ...[ const SizedBox(height: 16),
const SizedBox(height: 14), if (!isPremium) ...[
SizedBox( Row(
width: double.infinity, children: [
child: OutlinedButton.icon( Expanded(
onPressed: () { child: OutlinedButton(
HapticService.light(); onPressed: () {
ref.read(googleAuthProvider).signIn(); HapticService.light();
}, context.push('/pro');
icon: const Icon(Icons.login_rounded, color: Colors.white, size: 18), },
label: Text(s.proSignInGoogle), style: OutlinedButton.styleFrom(
style: OutlinedButton.styleFrom( foregroundColor: Colors.white,
foregroundColor: Colors.white, side: BorderSide(
side: BorderSide(color: Colors.white.withOpacity(0.3), width: 1), color: Colors.white.withOpacity(0.4), width: 1.5),
padding: const EdgeInsets.symmetric(vertical: 10), padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
),
),
child: Text(
s.proAboutPro,
style: const TextStyle(
fontWeight: FontWeight.w700, fontSize: 15),
),
),
),
],
),
] else ...[
Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () {
HapticService.light();
context.push('/backup');
},
icon: Icon(
driveUser != null
? Icons.cloud_done_rounded
: Icons.cloud_sync_rounded,
color: Colors.white,
size: 20,
),
label: Text(s.backupSyncWithDrive),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(
color: Colors.white.withOpacity(0.4), width: 1.5),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
],
),
if (driveUser == null) ...[
const SizedBox(height: 10),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
HapticService.light();
ref.read(googleDriveServiceProvider).signIn();
},
icon: const Icon(Icons.login_rounded,
color: Colors.white, size: 18),
label: Text(s.proSignInGoogle),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(
color: Colors.white.withOpacity(0.3), width: 1),
padding: const EdgeInsets.symmetric(vertical: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
), ),
), ),
), ),
), ],
], ],
], ],
), ),
@@ -6,11 +6,13 @@ import FlutterMacOS
import Foundation import Foundation
import google_sign_in_ios import google_sign_in_ios
import in_app_purchase_storekit
import local_auth_darwin import local_auth_darwin
import shared_preferences_foundation import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FLTGoogleSignInPlugin.register(with: registry.registrar(forPlugin: "FLTGoogleSignInPlugin")) FLTGoogleSignInPlugin.register(with: registry.registrar(forPlugin: "FLTGoogleSignInPlugin"))
InAppPurchasePlugin.register(with: registry.registrar(forPlugin: "InAppPurchasePlugin"))
LocalAuthPlugin.register(with: registry.registrar(forPlugin: "LocalAuthPlugin")) LocalAuthPlugin.register(with: registry.registrar(forPlugin: "LocalAuthPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
} }
+64
View File
@@ -1,6 +1,14 @@
# Generated by pub # Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile # See https://dart.dev/tools/pub/glossary#lockfile
packages: packages:
_discoveryapis_commons:
dependency: transitive
description:
name: _discoveryapis_commons
sha256: "113c4100b90a5b70a983541782431b82168b3cae166ab130649c36eb3559d498"
url: "https://pub.dev"
source: hosted
version: "1.0.7"
_fe_analyzer_shared: _fe_analyzer_shared:
dependency: transitive dependency: transitive
description: description:
@@ -241,6 +249,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.8" version: "2.0.8"
extension_google_sign_in_as_googleapis_auth:
dependency: "direct main"
description:
name: extension_google_sign_in_as_googleapis_auth
sha256: "0dcb17e399f62e897ac78f0a402a3cb6ab9313ced8b2bf131f684d317e05c9ab"
url: "https://pub.dev"
source: hosted
version: "2.0.13"
fake_async: fake_async:
dependency: transitive dependency: transitive
description: description:
@@ -424,6 +440,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.4+4" version: "0.12.4+4"
googleapis:
dependency: "direct main"
description:
name: googleapis
sha256: "864f222aed3f2ff00b816c675edf00a39e2aaf373d728d8abec30b37bee1a81c"
url: "https://pub.dev"
source: hosted
version: "13.2.0"
googleapis_auth:
dependency: "direct main"
description:
name: googleapis_auth
sha256: befd71383a955535060acde8792e7efc11d2fccd03dd1d3ec434e85b68775938
url: "https://pub.dev"
source: hosted
version: "1.6.0"
graphs: graphs:
dependency: transitive dependency: transitive
description: description:
@@ -480,6 +512,38 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.9.1" version: "4.9.1"
in_app_purchase:
dependency: "direct main"
description:
name: in_app_purchase
sha256: "0e9510b80b0074e89ab0a8e0fc901439b779dc9ae575ab8d419253c6e1627716"
url: "https://pub.dev"
source: hosted
version: "3.3.0"
in_app_purchase_android:
dependency: transitive
description:
name: in_app_purchase_android
sha256: eb8f551039481d1b265f12fa54f5ab5dd4f13ec5444a468b85a3793517a37fda
url: "https://pub.dev"
source: hosted
version: "0.5.1"
in_app_purchase_platform_interface:
dependency: transitive
description:
name: in_app_purchase_platform_interface
sha256: "0b0076cac8ce4fa7048f01e76af8b123aeb6a7c4e0dea2a5206d6664454f3e36"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
in_app_purchase_storekit:
dependency: transitive
description:
name: in_app_purchase_storekit
sha256: "5f9d59c86c15f56429a4fdf09097c99d5b412510e1fcf80cf874fc9638fab369"
url: "https://pub.dev"
source: hosted
version: "0.4.10"
intl: intl:
dependency: "direct main" dependency: "direct main"
description: description:
+4
View File
@@ -26,6 +26,10 @@ dependencies:
sqlite3_flutter_libs: ^0.6.0+eol sqlite3_flutter_libs: ^0.6.0+eol
path: ^1.8.3 path: ^1.8.3
google_sign_in: ^6.2.1 google_sign_in: ^6.2.1
in_app_purchase: ^3.2.0
googleapis: ^13.2.0
googleapis_auth: ^1.6.0
extension_google_sign_in_as_googleapis_auth: ^2.0.12
flutter_launcher_icons: flutter_launcher_icons:
android: true android: true