-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
999 lines (851 loc) · 34.6 KB
/
.cursorrules
File metadata and controls
999 lines (851 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
# Qanta Personal Finance App - Cursor Rules
## Project Overview
Qanta is a modern personal finance mobile application built with Flutter, focusing on budget management, expense tracking, investment portfolio, and financial analytics with AI-powered insights.
## Tech Stack
- **Framework**: Flutter 3.8.1+
- **Language**: Dart
- **State Management**: Provider
- **Database**: Supabase
- **Navigation**: GoRouter
- **UI**: Material 3 Design System
- **Fonts**: Google Fonts (Inter)
- **Localization**: flutter_localizations (Turkish/English)
- **Theme**: Light/Dark mode with SharedPreferences
- **Responsive Design**: flutter_screenutil
## Color Palette
- **Primary**: Sophisticated Grey (#6D6D70) - Main brand color
- **Secondary**: Material Green (#4CAF50) - Accent and success color
- **iOS Blue**: (#007AFF) - Interactive elements and buttons
- **Success**: Green (#4CAF50) - Positive actions and income
- **Error**: Red (#FF4C4C) - Negative actions and expenses
- **Warning**: Amber (#FFC300) - Alerts and cautions
- **Info**: Cyan (#00C2FF) - Information and transfers
- **Neutral**: Light Grey (#A0A0A0) - Secondary text and borders
## Project Structure
```
lib/
├── core/
│ ├── theme/ # Theme configuration
│ ├── services/ # External services (Supabase, etc.)
│ └── constants/ # App constants
├── modules/
│ ├── auth/ # Authentication & onboarding
│ ├── home/ # Dashboard & overview
│ ├── transactions/ # Transaction management
│ ├── cards/ # Card management
│ ├── insights/ # AI insights & analytics
│ └── settings/ # Settings & profile
├── shared/
│ ├── widgets/ # Reusable widgets
│ ├── models/ # Data models
│ └── utils/ # Utility functions
├── l10n/ # Localization files
└── routes/ # Navigation configuration
```
## SOLID Principles (MANDATORY)
### Single Responsibility Principle (SRP)
- Each class/widget must have only ONE reason to change
- Separate concerns: UI, business logic, data access
- Create focused, single-purpose classes
- Example: `TransactionFormWidget` only handles form UI, not data validation
### Open/Closed Principle (OCP)
- Open for extension, closed for modification
- Use abstract classes and interfaces
- Implement strategy pattern for different behaviors
- Example: `PaymentMethodStrategy` interface for different payment types
### Liskov Substitution Principle (LSP)
- Subclasses must be substitutable for their base classes
- Maintain contracts and behavior consistency
- Use proper inheritance hierarchies
- Example: All `TransactionType` implementations must behave consistently
### Interface Segregation Principle (ISP)
- Create small, focused interfaces
- Clients should not depend on unused methods
- Split large interfaces into smaller ones
- Example: `IReadable` and `IWritable` instead of one large `IDataAccess`
### Dependency Inversion Principle (DIP)
- Depend on abstractions, not concretions
- Use dependency injection
- Invert dependencies through interfaces
- Example: `IStockService` interface instead of direct `YandexFinanceApiService`
## Clean Architecture Guidelines
### Layer Separation
- **Presentation Layer**: UI widgets, pages, providers
- **Domain Layer**: Business logic, entities, use cases
- **Data Layer**: Repositories, data sources, models
### Dependency Rule
- Dependencies point inward only
- Outer layers can depend on inner layers
- Inner layers must not know about outer layers
## Coding Standards
### Dart/Flutter Best Practices
- Use `const` constructors whenever possible
- Prefer `final` over `var` for immutable variables
- Use meaningful variable and function names
- Follow Dart naming conventions (camelCase for variables, PascalCase for classes)
- Always use `super.key` for widget constructors
- Use `late` keyword appropriately for non-nullable variables
- Implement proper null safety
### Widget Guidelines
- Create reusable widgets in `shared/widgets/`
- Use `StatelessWidget` when possible, `StatefulWidget` only when state is needed
- Implement proper `dispose()` methods for controllers and streams
- Use `Builder` widgets to access context when needed
- Prefer composition over inheritance
- Keep widgets under 200 lines
- Extract complex widgets into separate files
### State Management
- Use Provider for global state (theme, user data)
- Use local state (setState) for simple UI state
- Create separate providers for different concerns
- Use `Consumer` and `Selector` widgets appropriately
- Implement proper error handling in providers
- Follow MVVM pattern with providers
### Navigation
- Use GoRouter for all navigation
- Define routes in `routes/app_router.dart`
- Use named routes instead of direct navigation
- Implement proper route guards for authentication
- Use type-safe navigation with extra parameters
### Styling & Theming
- Use Material 3 design system
- Follow the established color scheme
- Use Google Fonts Inter throughout the app
- Implement responsive design with flutter_screenutil
- Use Theme.of(context) for colors and text styles
- Support both light and dark themes
- Use consistent spacing and sizing
### Localization
- Add all user-facing strings to ARB files
- Use descriptive keys for localization
- Support Turkish and English languages
- Use AppLocalizations.of(context) for translations
- Never hardcode strings in UI
### File Naming
- Use snake_case for file names
- Use descriptive names that reflect functionality
- Group related files in appropriate modules
- Use suffixes: `_page.dart`, `_widget.dart`, `_provider.dart`, `_model.dart`, `_service.dart`
### Code Organization
- Keep files under 300 lines when possible
- Separate business logic from UI
- Use barrel exports (index.dart) for modules
- Group imports: Flutter, packages, relative imports
- Use meaningful comments for complex logic
- Follow single responsibility per file
### Error Handling
- Implement try-catch blocks for async operations
- Show user-friendly error messages
- Log errors appropriately (debugPrint in development)
- Handle network connectivity issues
- Validate user inputs
- Use Result<T> pattern for error handling
### Performance
- Use `const` widgets to reduce rebuilds
- Implement lazy loading for lists
- Optimize images and assets
- Use `ListView.builder` for large lists
- Avoid unnecessary rebuilds with proper state management
- Use `RepaintBoundary` for complex widgets
- Implement proper caching strategies
### Security
- Never commit API keys or sensitive data
- Use environment variables for configuration
- Implement proper input validation
- Follow Supabase security best practices
- Use secure storage for sensitive data
- Implement proper authentication flows
### Testing
- Write unit tests for business logic
- Write widget tests for UI components
- Use meaningful test descriptions
- Mock external dependencies
- Aim for good test coverage
- Test error scenarios
## Finance App Specific Guidelines
### Data Models
- Create models for: User, Transaction, Card, Budget, Category, QuickNote
- Use proper data validation
- Implement serialization methods (toJson/fromJson)
- Use enums for transaction types, categories
- Implement proper equality and hashCode
### Financial Calculations
- Use `Decimal` or `BigDecimal` for precise calculations
- Handle currency formatting properly
- Implement proper rounding for financial values
- Support multiple currencies
- Validate financial inputs
### UI/UX for Finance
- Use clear visual hierarchy for financial data
- Implement proper loading states
- Show confirmation dialogs for important actions
- Use appropriate icons for financial concepts
- Implement pull-to-refresh for data updates
- Use consistent number formatting
### Security for Finance
- Implement biometric authentication
- Use secure storage for sensitive financial data
- Implement session timeouts
- Add transaction confirmation steps
- Log financial operations for audit
- Encrypt sensitive data
## AI Integration Guidelines
- Use clear prompts for AI financial insights
- Implement proper error handling for AI responses
- Show loading states during AI processing
- Cache AI responses when appropriate
- Provide fallback content when AI is unavailable
- Implement proper rate limiting
## Git Workflow
- Use conventional commits (feat:, fix:, docs:, etc.)
- Create feature branches for new functionality
- Write descriptive commit messages
- Keep commits atomic and focused
- Use pull requests for code review
- Follow semantic versioning
## Dependencies Management
- Keep dependencies up to date
- Use specific version numbers in pubspec.yaml
- Document why each dependency is needed
- Prefer official packages over third-party when possible
- Regular security audits of dependencies
- Use dependency injection
## Documentation
- Document complex business logic
- Keep README.md updated
- Document API integrations
- Maintain changelog for releases
- Document deployment procedures
- Use dartdoc for public APIs
## Code Review Checklist
- [ ] Follows SOLID principles
- [ ] Follows Clean Architecture
- [ ] Follows Dart/Flutter best practices
- [ ] Proper error handling implemented
- [ ] Localization strings added
- [ ] Theme support implemented
- [ ] Performance considerations addressed
- [ ] Security guidelines followed
- [ ] Tests written (if applicable)
- [ ] Documentation updated
- [ ] No hardcoded values
- [ ] Proper null safety
- [ ] Responsive design implemented
- [ ] Accessibility considerations
## Quick Notes Specific Rules
- Use bottom sheet for note creation
- Implement proper image handling
- Support text and image notes
- Implement smart analysis for transaction conversion
- Use proper state management for note operations
- Implement proper error handling for media operations
## Stock Management Rules
- Implement proper real-time price updates
- Use proper error handling for API calls
- Implement offline support
- Use proper caching strategies
- Implement proper loading states
- Handle market hours properly
## Savings Goals (Birikimler) Rules
- Implement goal-based savings system with visual progress tracking
- Support multiple savings goals with customizable emojis, colors, and target amounts
- Integrate with existing account system for deposits/withdrawals
- Implement milestone achievements (25%, 50%, 75%, 100%)
- Support auto-transfer and round-up features (Premium)
- Use Firebase for data persistence with proper security rules
- Follow event-driven architecture for balance updates
- Implement smart AI suggestions for savings optimization
- Support goal categories (emergency, vacation, shopping, etc.)
- Provide comprehensive transaction history per goal
- Use animated progress indicators and celebration animations
- Implement proper notification system for milestones and reminders
- Free users: max 3 active goals, Premium: unlimited
- Integrate with Cards screen as 4th tab (Cash, Debit, Credit, Savings)
- Show summary cards on Home screen for quick overview
- Support goal archiving and completion tracking
- Implement proper validation (target > 0, current >= 0)
- Use proper currency formatting and calculations
- Support goal images/photos (Premium feature)
- Implement daily/weekly/monthly progress analytics
### Savings Data Models
- Create `SavingsGoal` model with all properties (name, emoji, target, current, etc.)
- Create `SavingsTransaction` model for deposits/withdrawals
- Create `AutoTransferSettings` for automatic transfers
- Create `RoundUpSettings` for round-up savings
- Create `NotificationSettings` for goal reminders
- Create `Milestone` model for achievement tracking
- Use enums: `SavingsGoalCategory`, `SavingsTransactionType`, `TransferFrequency`
### Savings Services
- `SavingsService`: CRUD operations for goals
- `SavingsTransactionService`: Handle deposits, withdrawals, transfers
- `SavingsCalculatorService`: Calculate daily requirements, AI suggestions
- `SavingsMilestoneService`: Track and award milestones
- `SavingsNotificationService`: Handle reminders and notifications
- Follow existing service patterns (Firebase integration, error handling)
### Savings UI Components
- `SavingsTab`: Main tab in Cards screen
- `SavingsGoalCard`: Individual goal card widget with gradient and progress
- `SavingsGoalDetailScreen`: Detailed view with transactions and analytics
- `AddSavingsGoalForm`: Create new goal form
- `EditSavingsGoalForm`: Edit existing goal
- `SavingsDepositForm`: Deposit money to goal
- `SavingsWithdrawForm`: Withdraw from goal
- `SavingsSummarySection`: Home screen summary widget
- `SavingsMilestoneDialog`: Celebration dialog for achievements
- Use Material 3 design with iOS-style polish
- Implement smooth animations and transitions
- Support both light and dark themes
### Savings Premium Features
- Free: Max 3 active goals, manual deposits only
- Premium: Unlimited goals, auto-transfer, round-up, goal images, advanced analytics
- Implement proper premium gates with upgrade prompts
- Use PremiumService for feature access control
### Savings Events
- Create `SavingsEvents` class following existing event pattern
- Events: GoalCreated, GoalUpdated, GoalDeleted, GoalCompleted
- Events: Deposit, Withdraw, MilestoneAchieved
- Integrate with existing UnifiedProviderV2
### Savings Localization
- Add all savings-related strings to intl_en.arb and intl_tr.arb
- Keys: savingsGoals, addGoal, targetAmount, currentAmount, etc.
- Support plurals for goal counts
- Localize milestone achievements and notifications
## Amazon Gift Card Reward System (Turkey Only)
### Overview
Reward system for Turkish Play Store users:
- **Rewarded Ad Watch**: 0.25 TL Amazon gift card credit
- **Transaction Add**: 0.10 TL Amazon gift card credit
- **Minimum Threshold**: 50 TL accumulated credit triggers automatic Amazon gift card delivery
- **Target Audience**: Only users who installed from Turkish Play Store
- **Delivery**: Automatic email delivery to user's Amazon account when threshold reached
### System Architecture
#### Reward Earning Rules
1. **Rewarded Ad**: User watches rewarded ad → +0.25 TL credit
2. **Transaction**: User adds expense/income → +0.10 TL credit
3. **Accumulation**: Credits accumulate in user's account
4. **Threshold**: When total reaches 50.00 TL → Automatic gift card purchase and delivery
5. **Country Restriction**: Only Turkish Play Store users eligible
#### Data Models
**AmazonRewardCredit Model** (`lib/shared/models/amazon_reward_credit_model.dart`):
```dart
class AmazonRewardCredit {
final String id;
final String userId;
final double amount; // 0.25 or 0.10
final RewardSource source; // rewardedAd or transaction
final String? transactionId; // If from transaction
final String? rewardedAdId; // If from ad
final DateTime earnedAt;
final RewardStatus status; // pending, accumulated, converted
final String? giftCardId; // When converted to gift card
}
enum RewardSource { rewardedAd, transaction }
enum RewardStatus { pending, accumulated, converted }
```
**AmazonGiftCard Model** (`lib/shared/models/amazon_gift_card_model.dart`):
```dart
class AmazonGiftCard {
final String id;
final String userId;
final double amount; // Always 50.00 TL minimum
final String amazonCode; // Gift card code from Amazon
final String amazonClaimCode; // Claim code for user
final DateTime purchasedAt;
final DateTime? sentAt;
final GiftCardStatus status; // purchased, sent, redeemed
final String recipientEmail; // User's email (for Amazon delivery)
final List<String> creditIds; // Which credits were converted
}
enum GiftCardStatus { purchased, sent, redeemed }
```
**AmazonRewardStats Model** (`lib/shared/models/amazon_reward_stats_model.dart`):
```dart
class AmazonRewardStats {
final String userId;
final double totalEarned; // Total credits earned
final double currentBalance; // Current accumulated (not yet converted)
final double totalConverted; // Total converted to gift cards
final int totalGiftCards; // Number of gift cards received
final int rewardedAdCount; // Number of ads watched
final int transactionCount; // Number of transactions rewarded
final DateTime lastEarnedAt;
final DateTime? lastConvertedAt;
}
```
#### Firebase Firestore Structure
```
users/{userId}/
├── amazon_reward_credits/{creditId}
│ {
│ "id": "credit_123",
│ "user_id": "user_456",
│ "amount": 0.25,
│ "source": "rewardedAd",
│ "transaction_id": null,
│ "rewarded_ad_id": "ad_789",
│ "earned_at": "2025-01-20T14:30:00Z",
│ "status": "accumulated",
│ "gift_card_id": null,
│ "created_at": "2025-01-20T14:30:00Z"
│ }
│
├── amazon_gift_cards/{giftCardId}
│ {
│ "id": "gc_123",
│ "user_id": "user_456",
│ "amount": 50.00,
│ "amazon_code": "ABC123XYZ789",
│ "amazon_claim_code": "AMZN-GC-ABC123XYZ789",
│ "purchased_at": "2025-01-20T15:00:00Z",
│ "sent_at": "2025-01-20T15:01:00Z",
│ "status": "sent",
│ "recipient_email": "user@example.com",
│ "credit_ids": ["credit_1", "credit_2", ...],
│ "created_at": "2025-01-20T15:00:00Z"
│ }
│
└── amazon_reward_stats (single document)
{
"user_id": "user_456",
"total_earned": 52.50,
"current_balance": 2.50,
"total_converted": 50.00,
"total_gift_cards": 1,
"rewarded_ad_count": 10,
"transaction_count": 500,
"last_earned_at": "2025-01-20T14:30:00Z",
"last_converted_at": "2025-01-20T15:00:00Z",
"updated_at": "2025-01-20T14:30:00Z"
}
campaigns/amazon_gift_card_rewards (global config)
{
"campaign_id": "amazon_gift_card_rewards",
"is_active": true,
"rewarded_ad_amount": 0.25,
"transaction_amount": 0.10,
"minimum_threshold": 50.00,
"eligible_countries": ["TR"],
"gift_card_amount": 50.00,
"start_date": "2025-01-20T00:00:00Z",
"end_date": null
}
```
#### Services
**AmazonRewardService** (`lib/core/services/amazon_reward_service.dart`):
- `earnRewardFromAd(String userId)`: Add 0.25 TL credit from rewarded ad
- `earnRewardFromTransaction(String userId, String transactionId)`: Add 0.10 TL credit from transaction
- `getCurrentBalance(String userId)`: Get current accumulated balance
- `getRewardStats(String userId)`: Get user's reward statistics
- `checkAndConvertToGiftCard(String userId)`: Check if threshold reached and convert
**AmazonGiftCardService** (`lib/core/services/amazon_gift_card_service.dart`):
- `purchaseGiftCard(double amount, String recipientEmail)`: Purchase gift card from Amazon API
- `sendGiftCardEmail(String giftCardId)`: Send gift card via email
- `getGiftCardHistory(String userId)`: Get user's gift card history
**CountryDetectionService** (`lib/core/services/country_detection_service.dart`):
- `isTurkishPlayStoreUser()`: Check if user installed from Turkish Play Store
- `getUserCountry()`: Get user's country code
- `shouldShowAmazonRewards()`: Determine if Amazon rewards should be visible
#### Cloud Functions
**functions/handlers/amazonRewards.js**:
- `earnRewardFromAd`: Add credit from rewarded ad
- `earnRewardFromTransaction`: Add credit from transaction
- `checkAndConvertToGiftCard`: Check threshold and convert if reached
- `purchaseAmazonGiftCard`: Purchase gift card via Amazon API
- `sendGiftCardEmail`: Send gift card code via email
### Implementation Phases
#### Phase 1: Foundation & Models (Days 1-2)
**Goal**: Create data models and Firebase structure
**Tasks**:
1. Create `AmazonRewardCredit` model with all fields
2. Create `AmazonGiftCard` model with all fields
3. Create `AmazonRewardStats` model with all fields
4. Create enum classes: `RewardSource`, `RewardStatus`, `GiftCardStatus`
5. Add Firebase Firestore security rules for new collections
6. Create test data in Firebase for development
**Concrete Outputs**:
- ✅ `lib/shared/models/amazon_reward_credit_model.dart` file created
- ✅ `lib/shared/models/amazon_gift_card_model.dart` file created
- ✅ `lib/shared/models/amazon_reward_stats_model.dart` file created
- ✅ `firestore.rules` updated with security rules
- ✅ Test data inserted in Firebase
- ✅ Models have proper toJson/fromJson methods
- ✅ Models have proper validation
**Acceptance Criteria**:
- All models compile without errors
- Firebase structure matches specification
- Security rules prevent unauthorized access
- Test data can be created and read
---
#### Phase 2: Country Detection (Days 3-4)
**Goal**: Implement Turkish Play Store detection
**Tasks**:
1. Create `CountryDetectionService` with Play Store country detection
2. Implement device locale detection (tr_TR)
3. Implement Play Store country code detection
4. Add country info to user profile on first login
5. Create country detection UI indicator (optional)
6. Add Remote Config flag for country-based features
**Concrete Outputs**:
- ✅ `lib/core/services/country_detection_service.dart` file created
- ✅ Country detection working for Turkish users
- ✅ User country stored in `users/{userId}/country_info` document
- ✅ `shouldShowAmazonRewards()` method returns correct value
- ✅ Remote Config integration for feature flag
- ✅ Country detection tested with Turkish and non-Turkish devices
**Acceptance Criteria**:
- Turkish Play Store users correctly identified
- Non-Turkish users don't see Amazon rewards
- Country detection persists across app restarts
- Remote Config controls feature visibility
---
#### Phase 3: Reward Earning System (Days 5-7)
**Goal**: Implement reward earning from ads and transactions
**Tasks**:
1. Create `AmazonRewardService` with reward earning methods
2. Integrate with `RewardedAdService` to add 0.25 TL on ad watch
3. Integrate with `UnifiedTransactionService` to add 0.10 TL on transaction
4. Create Cloud Function `earnRewardFromAd`
5. Create Cloud Function `earnRewardFromTransaction`
6. Add reward earning UI feedback (snackbar/toast)
7. Update reward stats after each earning
8. Add duplicate prevention (same transaction/ad can't earn twice)
**Concrete Outputs**:
- ✅ `lib/core/services/amazon_reward_service.dart` file created
- ✅ `RewardedAdService` modified to call Amazon reward on ad watch
- ✅ `UnifiedTransactionService` modified to call Amazon reward on transaction
- ✅ Cloud Functions `earnRewardFromAd` and `earnRewardFromTransaction` deployed
- ✅ Reward credits saved to Firebase
- ✅ Reward stats updated after each earning
- ✅ UI shows "0.25 TL kazandınız!" or "0.10 TL kazandınız!" message
- ✅ Duplicate prevention working (same transaction/ad only earns once)
**Acceptance Criteria**:
- Rewarded ad watch adds 0.25 TL credit
- Transaction add adds 0.10 TL credit
- Credits accumulate correctly
- Stats update in real-time
- Duplicate earnings prevented
- Only Turkish users can earn rewards
---
#### Phase 4: Balance Tracking & UI (Days 8-10)
**Goal**: Show user their current balance and progress
**Tasks**:
1. Create `AmazonRewardProvider` for state management
2. Create reward balance widget for Home screen
3. Create reward progress bar (current balance / 50 TL)
4. Create reward history screen (list of credits earned)
5. Add "Amazon Hediye Kartı" section in Profile screen
6. Implement pull-to-refresh for balance
7. Add loading states for balance fetch
8. Create reward stats display (total earned, gift cards received)
**Concrete Outputs**:
- ✅ `lib/modules/profile/providers/amazon_reward_provider.dart` file created
- ✅ `lib/modules/home/widgets/amazon_reward_balance_card.dart` widget created
- ✅ `lib/modules/profile/pages/amazon_rewards_page.dart` screen created
- ✅ Reward balance visible on Home screen
- ✅ Progress bar shows "X.XX TL / 50.00 TL"
- ✅ Reward history shows all credits with dates and sources
- ✅ Stats show total earned, converted, gift cards received
- ✅ Pull-to-refresh updates balance
**Acceptance Criteria**:
- Balance displays correctly
- Progress bar updates in real-time
- History shows all earned credits
- UI is responsive and follows Material 3 design
- Loading states work properly
- Error handling shows user-friendly messages
---
#### Phase 5: Threshold Detection & Conversion (Days 11-13)
**Goal**: Automatically convert 50 TL to gift card
**Tasks**:
1. Create Cloud Function `checkAndConvertToGiftCard`
2. Implement threshold check logic (balance >= 50.00 TL)
3. Create `AmazonGiftCardService` for gift card operations
4. Integrate Amazon Gift Card API (or manual purchase flow)
5. Update credit statuses to "converted"
6. Create gift card document in Firebase
7. Send conversion notification to user
8. Handle partial conversion (if balance > 50 TL, keep remainder)
**Concrete Outputs**:
- ✅ Cloud Function `checkAndConvertToGiftCard` deployed
- ✅ Threshold check runs after each credit earning
- ✅ `AmazonGiftCardService` created with purchase method
- ✅ Gift card purchased when threshold reached
- ✅ Credits marked as "converted"
- ✅ Gift card document created in Firebase
- ✅ User receives notification: "50 TL Amazon hediye kartınız hazır!"
- ✅ Remaining balance preserved if > 50 TL
**Acceptance Criteria**:
- Automatic conversion works when threshold reached
- Gift card purchased successfully
- Credits properly marked as converted
- Remaining balance handled correctly
- User notified of conversion
---
#### Phase 6: Amazon Gift Card Purchase Integration (Days 14-16)
**Goal**: Integrate with Amazon to purchase gift cards
**Tasks**:
1. Research Amazon Gift Card API options
2. Set up Amazon API credentials (if available)
3. Create Cloud Function `purchaseAmazonGiftCard`
4. Implement gift card purchase flow
5. Handle purchase errors and retries
6. Store gift card codes securely
7. Add purchase logging for debugging
8. Implement fallback: Manual purchase process (if API not available)
**Concrete Outputs**:
- ✅ Amazon API integration working OR manual purchase flow ready
- ✅ Cloud Function `purchaseAmazonGiftCard` deployed
- ✅ Gift card codes stored in Firebase
- ✅ Purchase errors handled gracefully
- ✅ Purchase logs for debugging
- ✅ Fallback manual process documented
**Acceptance Criteria**:
- Gift cards can be purchased automatically (or manually)
- Codes stored securely
- Errors handled properly
- Purchase logs available
---
#### Phase 7: Email Delivery System (Days 17-18)
**Goal**: Send gift card codes via email
**Tasks**:
1. Create Cloud Function `sendGiftCardEmail`
2. Integrate with email service (Firebase Extensions or SendGrid)
3. Create email template for gift card delivery
4. Include gift card code and redemption instructions
5. Send email when gift card purchased
6. Update gift card status to "sent"
7. Add email delivery error handling
8. Add email delivery logs
**Concrete Outputs**:
- ✅ Cloud Function `sendGiftCardEmail` deployed
- ✅ Email service integrated (Firebase Extensions or SendGrid)
- ✅ Email template created with gift card code
- ✅ Email sent automatically when gift card purchased
- ✅ Gift card status updated to "sent"
- ✅ Email delivery errors handled
- ✅ Email logs for debugging
**Acceptance Criteria**:
- Emails sent successfully
- Gift card codes included in email
- Redemption instructions clear
- Error handling works
- Email delivery logged
---
#### Phase 8: Gift Card History & Management (Days 19-20)
**Goal**: Show user their gift card history
**Tasks**:
1. Create gift card history screen
2. Display all gift cards with status (sent, redeemed)
3. Show gift card codes (masked until clicked)
4. Add "Copy Code" functionality
5. Add "Open Amazon" button
6. Show gift card purchase date and amount
7. Add gift card redemption status tracking
8. Create gift card detail view
**Concrete Outputs**:
- ✅ `lib/modules/profile/pages/amazon_gift_card_history_page.dart` screen created
- ✅ Gift card list shows all cards
- ✅ Gift card codes can be copied
- ✅ "Open Amazon" button works
- ✅ Gift card details visible (date, amount, status)
- ✅ Redemption status tracked (if possible)
**Acceptance Criteria**:
- Gift card history displays correctly
- Codes can be copied easily
- Amazon link works
- UI follows Material 3 design
- Loading and error states handled
---
#### Phase 9: Localization & Polish (Days 21-22)
**Goal**: Add Turkish and English translations
**Tasks**:
1. Add all Amazon reward strings to `intl_tr.arb`
2. Add all Amazon reward strings to `intl_en.arb`
3. Localize all UI elements
4. Localize email templates
5. Add proper error messages
6. Add success messages
7. Test with both Turkish and English locales
**Concrete Outputs**:
- ✅ All strings added to `intl_tr.arb`
- ✅ All strings added to `intl_en.arb`
- ✅ All UI elements localized
- ✅ Email templates localized
- ✅ Error messages localized
- ✅ Success messages localized
- ✅ Tested with Turkish and English
**Acceptance Criteria**:
- All text localized
- No hardcoded strings
- Email templates localized
- Proper translations
---
#### Phase 10: Testing & Deployment (Days 23-25)
**Goal**: Comprehensive testing and production deployment
**Tasks**:
1. Unit tests for services
2. Widget tests for UI components
3. Integration tests for reward flow
4. Test with Turkish Play Store account
5. Test with non-Turkish account (should not see rewards)
6. Test threshold conversion
7. Test email delivery
8. Test error scenarios
9. Performance testing
10. Production deployment
**Concrete Outputs**:
- ✅ Unit tests written and passing
- ✅ Widget tests written and passing
- ✅ Integration tests written and passing
- ✅ Tested with Turkish account
- ✅ Tested with non-Turkish account
- ✅ Threshold conversion tested
- ✅ Email delivery tested
- ✅ Error scenarios handled
- ✅ Performance acceptable
- ✅ Deployed to production
**Acceptance Criteria**:
- All tests passing
- No critical bugs
- Performance acceptable
- Production ready
### Integration Points
#### RewardedAdService Integration
```dart
// In RewardedAdService.showRewardedAd()
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) async {
// Existing AI bonus logic...
// NEW: Add Amazon reward (only for Turkish users)
if (await CountryDetectionService().shouldShowAmazonRewards()) {
await AmazonRewardService().earnRewardFromAd(userId);
}
}
```
#### UnifiedTransactionService Integration
```dart
// In UnifiedTransactionService.addTransaction()
// After transaction saved successfully
if (await CountryDetectionService().shouldShowAmazonRewards()) {
await AmazonRewardService().earnRewardFromTransaction(
userId,
transactionId,
);
}
```
### UI Components
#### Home Screen Widget
- `AmazonRewardBalanceCard`: Shows current balance and progress to 50 TL
- Display: "X.XX TL / 50.00 TL Amazon Hediye Kartı"
- Progress bar visualization
- "Detaylar" button to reward history
#### Profile Screen Section
- "Amazon Hediye Kartları" section
- Current balance display
- Link to reward history
- Link to gift card history
#### Reward History Screen
- List of all credits earned
- Show: Date, Amount, Source (Ad/Transaction)
- Total earned summary
- Progress to next gift card
#### Gift Card History Screen
- List of all gift cards received
- Show: Date, Amount, Status, Code
- "Copy Code" button
- "Open Amazon" button
### Error Handling
#### Reward Earning Errors
- Network errors: Retry with exponential backoff
- Duplicate detection: Show "Already earned" message
- Country check failure: Log but don't block user
- Firebase errors: Show user-friendly error message
#### Gift Card Purchase Errors
- API errors: Retry up to 3 times
- Insufficient balance: Queue for manual processing
- Email delivery failure: Retry and log
- Invalid email: Mark for manual review
### Security Considerations
#### Firebase Security Rules
- Users can only read their own reward data
- Users cannot modify reward credits
- Only Cloud Functions can create gift cards
- Only Cloud Functions can update reward stats
#### API Security
- Amazon API credentials stored in Firebase Functions config
- Never expose API keys to client
- Validate all inputs server-side
- Rate limiting on reward earning
### Monitoring & Analytics
#### Key Metrics to Track
- Number of rewards earned (by source)
- Average time to reach 50 TL threshold
- Gift cards purchased per day
- Email delivery success rate
- User engagement with rewards feature
#### Logging
- All reward earnings logged
- Gift card purchases logged
- Email deliveries logged
- Errors logged with stack traces
### Future Enhancements
#### Phase 11+ (Future)
- Multiple gift card providers (Getir, Yemeksepeti)
- Tiered rewards (100 TL = 110 TL gift card)
- Referral bonuses
- Seasonal campaigns
- Premium user bonuses
### Cost & Profit Analysis
#### Revenue Sources
- **AdMob Rewarded Ad Revenue (Turkey)**: 0.40 TL per ad watch (conservative estimate)
- Realistic range: 0.30-0.80 TL per ad
- Factors: User segmentation, ad format, time of day, season
- **Transaction Indirect Revenue**: 0.05 TL per transaction (engagement value)
#### Costs
- **Amazon Gift Card Cost**: 50 TL = 50 TL (direct purchase, no discount assumed)
- **Operational Costs**: 0 TL (Firebase free tier sufficient)
- **Reward Costs**: See pricing below
#### Recommended Pricing (Profit-Optimized)
**Option A: High Profit Margin (RECOMMENDED)**
```
Rewarded Ad Reward: 0.20 TL
├─ Revenue: 0.40 TL per ad
├─ Cost: 0.20 TL per ad
└─ Profit: 0.20 TL per ad (50% margin)
Transaction Reward: 0.03 TL
├─ Revenue: 0.05 TL per transaction (indirect)
├─ Cost: 0.03 TL per transaction
└─ Profit: 0.02 TL per transaction (40% margin)
Minimum Threshold: 50 TL
Daily Limits:
├─ Max ads: 10 ads/user/day
├─ Max transactions: 20 transactions/user/day
└─ Max daily reward: 2.60 TL/user
```
**Profit Projection (1000 Active Users)**
```
Daily:
├─ Ad rewards: 1000 × 2 ads × 0.20 TL = 400 TL
├─ Transaction rewards: 1000 × 5 transactions × 0.03 TL = 150 TL
├─ Total reward cost: 550 TL/day
├─ Ad revenue: 1000 × 2 ads × 0.40 TL = 800 TL
├─ Transaction revenue: 1000 × 5 transactions × 0.05 TL = 250 TL
├─ Total revenue: 1,050 TL/day
└─ Net profit: 500 TL/day ✅
Monthly:
├─ Reward cost: 550 × 30 = 16,500 TL
├─ Revenue: 1,050 × 30 = 31,500 TL
└─ Net profit: 15,000 TL/month ✅
```
#### Risk Management
- **Conservative eCPM**: Use 0.30 TL instead of 0.40 TL for safety
- **Minimum profit margin**: Maintain 20% minimum
- **Dynamic pricing**: Use Remote Config to adjust rewards based on actual eCPM
- **Daily limits**: Prevent abuse (10 ads/day, 20 transactions/day)
- **Fraud detection**: Monitor for bot usage and spam
#### Dynamic Pricing Strategy
- Monitor actual eCPM weekly
- Adjust rewards via Remote Config if profit margin < 20%
- Automatic adjustment algorithm in Cloud Functions
- Real-time cost tracking and alerts
**See detailed analysis in**: `AMAZON_REWARD_COST_ANALYSIS.md`
Remember: Focus on creating a secure, user-friendly, and performant personal finance application that follows SOLID principles and Clean Architecture patterns. Every line of code should be maintainable, testable, and follow these guidelines.