Notification System - Comprehensive Analysis & Planning
Date: January 2025
Purpose: Deep analysis of existing notification infrastructure and planning for comprehensive notification system across toto-app (donors) and toto-bo (guardians, admins)
📋 Executive Summary
The notification system currently exists primarily in toto-bo (backoffice) with a solid foundation:
- ✅ Database schema and API endpoints
- ✅ Notification types system (24 types defined)
- ✅ Real-time hooks and UI components
- ✅ Service layer for creating notifications
Gaps identified:
- ❌ No notification system in toto-app (donors)
- ❌ No actual notification triggers in business logic (case updates, donation verification, etc.)
- ❌ Notification types don't cover donor-specific scenarios
- ❌ No integration between saved conversations and notifications
🔍 Current State Analysis
✅ What Exists and is Current
1. Database & API Layer (toto-bo)
- File:
toto-bo/src/app/api/notifications/route.ts - Status: ✅ Production-ready
- Features:
- GET: Fetch notifications with filtering (userEmail, type, read, priority, limit, offset)
- POST: Create notifications
- PATCH: Update notifications
- DELETE: Delete notifications
- Schema:
{
id: string;
userId?: string;
userEmail: string; // Primary identifier
type: string;
title: string;
message: string;
priority: 'low' | 'medium' | 'high';
metadata?: Record<string, unknown>;
read: boolean;
createdAt: string;
updatedAt: string;
}
2. Notification Types System (toto-bo)
- File:
toto-bo/src/lib/notificationTypes.ts - Status: ✅ Well-structured, but missing donor-specific types
- Current Types (24):
- Case:
case_created,case_updated,case_urgent,case_completed - Donations:
donation_received,donation_failed - Guardians:
guardian_registered,guardian_updated - System:
system_maintenance,security_alert,permission_granted,permission_revoked - Collaborators:
collaborator_invited,collaborator_joined,collaborator_left - Payments:
payment_processed,payment_failed - Support:
support_ticket_created,support_ticket_updated,support_ticket_resolved - Reports:
report_generated,analytics_ready - Audit:
audit_log_created - Partners:
partner_joined
- Case:
- Roles configured:
admin,staff,partner,guardian - Missing: Donor-specific types and roles
3. Service Layer (toto-bo)
- Files:
toto-bo/src/lib/notifications.ts- Simple helper functiontoto-bo/src/lib/notificationService.ts- Full service class (singleton)toto-bo/src/services/notificationService.ts- Duplicate? (needs review)
- Status: ✅ Functional, but not integrated into business logic
- Usage: Currently only used in seeding scripts
4. UI Components (toto-bo)
- Files:
toto-bo/src/components/ui/EnhancedNotificationCenter.tsx- Main notification modaltoto-bo/src/components/ui/NotificationBell.tsx- Bell icon with badgetoto-bo/src/components/ui/NotificationBadge.tsx- Badge componenttoto-bo/src/components/ui/ToastNotifications.tsx- Toast systemtoto-bo/src/hooks/useRealTimeNotifications.ts- Real-time hook
- Status: ✅ Production-ready for toto-bo
5. Documentation
- Files:
toto-docs/app/docs/ecosystem/notification-system.md- Technical docstoto-docs/app/docs/user-guides/notification-system-guide.md- User guide
- Status: ✅ Good documentation, but needs updates for donor notifications
⚠️ What's Old/Unused
1. Legacy Notification UI in toto-app
- File:
toto-app/legacy/pages/notifications.tsx - Status: ⚠️ Legacy code - uses mock data, not connected to backend
- Action: Should be replaced with new implementation
2. Current toto-app Notifications Screen
- File:
toto-app/app/(tabs)/notifications.tsx - Status: ⚠️ UI exists but uses mock data only
- Action: Needs backend integration
3. Seeding Scripts
- File:
toto-bo/src/lib/seeding/notifications.ts - Status: ⚠️ Only for development/testing
- Note: Uses different type system (
'urgent' | 'success' | 'warning' | 'info' | 'case' | 'donation' | 'guardian' | 'system') vs production types - Action: Keep for seeding, but ensure consistency
4. Duplicate Services
- Files:
toto-bo/src/lib/notificationService.tstoto-bo/src/services/notificationService.ts
- Status: ⚠️ Potential duplication - needs review
- Action: Consolidate to single service
❌ What's Missing
1. Notification Triggers in Business Logic
- ❌ No notifications when cases are updated
- ❌ No notifications when donations are verified
- ❌ No notifications when totitos are assigned
- ❌ No notifications for case updates to donors
- ❌ No notifications for guardian actions affecting donors
2. Donor Notification System in toto-app
- ❌ No API endpoints in toto-app
- ❌ No notification service integration
- ❌ No real-time hooks
- ❌ No UI components (except mock screens)
3. Donor-Specific Notification Types
- ❌ Missing:
donation_verified(donor submitted proof, guardian verified) - ❌ Missing:
totitos_assigned(totitos earned after verification) - ❌ Missing:
case_update_for_donor(case they're involved with updated) - ❌ Missing:
guardian_new_case(guardian they follow created new case) - ❌ Missing:
user_engagement(we miss you, come back) - ❌ Missing:
donation_verification_pending(reminder to submit proof)
4. Integration Points
- ❌ No integration with
conversationscollection (saved conversations) - ❌ No integration with case update system
- ❌ No integration with donation verification workflow
- ❌ No integration with totitos assignment
📝 Refined Notification Categories
🎯 DONORS (toto-app)
1. User Engagement & Account
user_welcome- Welcome message for new usersuser_engagement_reminder- "We miss you, come back to the app" (after X days inactive)profile_update_required- Reminder to complete profiletotitos_balance_update- Periodic balance summary (optional)
2. Case-Related (Based on Saved Conversations)
case_update- Case they're involved with (via saved conversation) has been updated- Trigger: When case is updated AND user has saved conversation for that case
- Includes: Medical progress, milestones, recovery status, treatment updates
case_milestone_reached- Case reached funding milestone (50%, 75%, 100%)case_completed- Case they supported has been completedcase_urgent_update- Urgent update on case they're following
3. Guardian-Related
guardian_new_case- Guardian they follow (from previous cases) created a new case- Trigger: Guardian creates new case AND user has saved conversation with previous case from same guardian
guardian_update- Guardian profile or status update (if relevant to donor)
4. Donation-Related
donation_verification_pending- Reminder to submit donation proof (after X days)donation_verification_submitted- Confirmation that proof was receiveddonation_verified- Guardian verified the donation (totitos will be assigned)donation_verification_failed- Verification failed, needs resubmissiontotitos_assigned- Totitos have been assigned after verificationdonation_received_by_guardian- Guardian received the donation (confirmation)
5. General/System
system_announcement- General announcements for all donorsfeature_update- New features availablemaintenance_notice- Scheduled maintenance
🛡️ GUARDIANS (toto-bo)
1. Case Management
case_assigned- New case assigned to themcase_approval_required- Case pending admin approvalcase_approved- Case approved by admincase_rejected- Case rejected (with reason)case_update_reminder- Reminder to update case statuscase_urgent_attention- Case marked as urgent by admincase_funding_milestone- Case reached funding milestonecase_funding_complete- Case reached funding goalcase_funding_low- Case funding is below expected
2. Donation Management
donation_received- New donation received for their casedonation_verification_request- Donor submitted proof, needs verificationdonation_verification_reminder- Reminder to verify pending donations (weekly batch)donation_verification_completed- Successfully verified donation (confirmation)donation_large_received- Large donation received (above threshold)donation_anonymous_received- Anonymous donation received
3. Guardian Account
guardian_verification_pending- Verification documents submitted, pending reviewguardian_verification_approved- Verification approvedguardian_verification_rejected- Verification rejected (needs resubmission)guardian_profile_update_required- Profile information needs updatingbanking_alias_updated- Banking alias changed
4. Communication & Engagement
new_message_from_donor- New message in case conversationcase_comment_received- Comment on case (if comments exist)donor_question- Question from donor about case
5. System & Admin
admin_message- Direct message from adminsystem_maintenance- Scheduled maintenancepolicy_update- Policy or terms updatetraining_available- New training resources available
👨💼 ADMINS (toto-bo)
1. Case Oversight
case_submitted_for_approval- New case submitted by guardiancase_requires_review- Case flagged for reviewcase_urgent_escalation- Case escalated to urgentcase_funding_anomaly- Unusual donation pattern detectedcase_update_by_guardian- Guardian updated case (for monitoring)
2. User Management
guardian_registration- New guardian registeredguardian_verification_pending- Guardian verification documents submitteduser_report_received- User reported an issuesuspicious_activity- Suspicious user activity detectedbulk_user_action_required- Bulk action needed (e.g., mass email)
3. Financial & Donations
donation_anomaly- Unusual donation patterndonation_verification_dispute- Dispute in donation verificationpayment_processing_error- Payment processing failedfinancial_report_ready- Financial report generatedfunding_goal_analysis- Analysis of funding goals vs actuals
4. System & Operations
system_error- System error detectedsecurity_alert- Security event detectedperformance_issue- Performance degradationdatabase_backup_complete- Backup completedscheduled_task_failed- Scheduled task failedapi_rate_limit_warning- API rate limit approaching
5. Support & Tickets
support_ticket_created- New support ticketsupport_ticket_escalated- Ticket escalatedsupport_ticket_high_priority- High priority ticket createdsupport_ticket_sla_breach- SLA breach warning
6. Analytics & Reports
report_generated- Report ready for reviewanalytics_anomaly- Unusual analytics patternmonthly_summary_ready- Monthly summary availableuser_engagement_report- Engagement report ready
🔗 Integration Points
1. Saved Conversations → Notifications
- Location:
toto-app/src/services/conversationService.ts - Trigger: When case is updated, find all users with saved conversations for that case
- Action: Create
case_updatenotification for each user
2. Case Updates → Notifications
- Location:
toto-bo/src/app/api/cases/[id]/route.ts(PUT endpoint) - Current: No notification triggers
- Action: After case update, trigger notifications to:
- Guardians:
case_update_by_guardian(to admin) - Donors:
case_update(to all with saved conversations)
- Guardians:
3. Donation Verification → Notifications
- Location: Donation verification workflow (needs identification)
- Triggers:
- Donor submits proof →
donation_verification_submitted(to donor),donation_verification_request(to guardian) - Guardian verifies →
donation_verified(to donor),donation_verification_completed(to guardian) - Guardian rejects →
donation_verification_failed(to donor) - Totitos assigned →
totitos_assigned(to donor)
- Donor submits proof →
4. Guardian Case Creation → Notifications
- Location: Case creation endpoint
- Trigger: When guardian creates new case
- Action: Find all users with saved conversations from previous cases by same guardian, send
guardian_new_case
5. User Engagement → Notifications
- Location: Background job/cron
- Trigger: Daily check for inactive users (X days since last login)
- Action: Send
user_engagement_remindernotification
🏗️ Architecture Recommendations
1. Unified Notification Service
- Create shared notification service that works for both toto-app and toto-bo
- Use same database collection (
notifications) - Differentiate by
appfield or separate byuserEmaildomain (if different)
2. Notification Triggers as Middleware
- Create notification trigger functions that can be called after business logic
- Example:
// After case update
await notifyCaseUpdate(caseId, updateData);
// After donation verification
await notifyDonationVerification(donationId, status);
3. Background Jobs for Engagement
- Set up scheduled jobs for:
- User engagement reminders
- Donation verification reminders
- Case update summaries (digest mode)
4. Notification Preferences
- Add user preferences for notification types
- Support for: in-app, email, push (future)
- Quiet hours configuration
📊 Priority Implementation Order
Phase 1: Foundation (Critical)
- ✅ Extend notification types to include donor types
- ✅ Create notification trigger functions
- ✅ Integrate case update notifications
- ✅ Integrate donation verification notifications
Phase 2: Donor System (High Priority)
- ✅ Create toto-app notification API endpoints
- ✅ Create toto-app notification service
- ✅ Integrate with existing toto-app notifications screen
- ✅ Add real-time hooks for toto-app
Phase 3: Guardian Notifications (Medium Priority)
- ✅ Implement guardian-specific notification triggers
- ✅ Add case assignment notifications
- ✅ Add donation verification workflow notifications
Phase 4: Admin Notifications (Medium Priority)
- ✅ Implement admin oversight notifications
- ✅ Add system monitoring notifications
- ✅ Add analytics/reporting notifications
Phase 5: Engagement & Optimization (Low Priority)
- ✅ User engagement reminders
- ✅ Notification preferences
- ✅ Digest mode
- ✅ Push notifications (future)
🚨 Critical Questions to Resolve
-
Database Separation:
- Should toto-app and toto-bo use the same
notificationscollection? - Or separate collections with different Firebase projects?
- Should toto-app and toto-bo use the same
-
User Identification:
- Use
userEmailas primary identifier (current approach)? - Or
userId? (More reliable, but requires cross-app user sync)
- Use
-
Notification Delivery:
- In-app only initially?
- Email integration needed?
- Push notifications priority?
-
Saved Conversations Criteria:
- Only users who donated?
- Or all users who saved conversation?
- What about users who just "liked" a case?
-
Guardian "Follow" Logic:
- How to determine if donor "follows" a guardian?
- Based on saved conversations from previous cases?
- Or explicit follow relationship?
💡 RECOMMENDATIONS
1. Database Separation: ✅ UNIFIED COLLECTION
Recommendation: Use shared notifications collection in toto-f9d2f database
Rationale:
- Both apps already share the same Firebase Auth project (
toto-f9d2f) - Users have the same
uidacross both apps - Simpler architecture: one source of truth
- Easier cross-app notification management
- Current toto-bo notifications are already in toto-f9d2f (via API access)
Implementation:
- Store notifications in
toto-f9d2fFirestore (main app database) - toto-bo accesses via existing cross-project pattern
- Add
appfield to distinguish source:'toto-app' | 'toto-bo' - Both apps can read/write to same collection
Alternative (NOT recommended):
- Separate collections would require:
- Duplicate notification logic
- Cross-database queries
- More complex user matching
- Higher maintenance burden
2. User Identification: ✅ HYBRID APPROACH
Recommendation: Use userId (uid) as primary, userEmail as secondary
Rationale:
userId(Firebase uid) is:- ✅ More reliable (never changes)
- ✅ Consistent across both apps
- ✅ Better for queries and indexing
- ✅ Required for security rules
userEmailis:- ✅ Human-readable for debugging
- ✅ Useful for admin operations
- ✅ Good fallback if uid lookup fails
Implementation:
interface Notification {
id: string;
userId: string; // PRIMARY: Firebase uid (required)
userEmail: string; // SECONDARY: Email (required for admin/debugging)
app: 'toto-app' | 'toto-bo'; // NEW: Source app
type: NotificationType;
// ... rest of fields
}
Migration:
- Update existing notifications to include
userIdwhere missing - Make
userIdrequired in schema - Keep
userEmailfor backward compatibility and admin use
3. Notification Delivery: ✅ PHASED APPROACH
Recommendation: Phase 1: In-app only, Phase 2: Email, Phase 3: Push
Phase 1 (MVP - Immediate):
- ✅ In-app notifications only
- ✅ Real-time updates via Firestore listeners
- ✅ Notification center in both apps
- ✅ Badge counts
Phase 2 (Short-term - 2-3 months):
- ✅ Email for critical notifications:
- Donation verification status
- Totitos assigned
- Case milestones
- ✅ Email digest option (daily/weekly summary)
- ✅ User preferences for email types
Phase 3 (Future - 6+ months):
- ✅ Push notifications (mobile)
- ✅ Web push notifications
- ✅ Rich notifications with actions
Rationale:
- Start simple, validate with users
- Email is easier to implement than push
- Push requires additional infrastructure (FCM setup, permissions)
4. Saved Conversations Criteria: ✅ INCLUSIVE APPROACH
Recommendation: All users with saved conversations, not just donors
Rationale:
- Conversations are saved when users interact with cases (chat, ask questions)
- Not all interactions result in donations
- Users who engage deserve updates (builds trust and future donations)
- KB documentation says: "After a user donates to a case, that case's conversation is stored in their inbox" - but conversations can also be saved from interactions
Implementation:
// When case is updated:
1. Query conversations collection: where('caseId', '==', caseId)
2. For each conversation:
- Create case_update notification for that userId
- Include caseId in metadata for deep linking
Edge Cases:
- Users who only "liked" a case: Don't notify (no saved conversation)
- Users who chatted but didn't donate: Do notify (they have saved conversation)
- Users who donated but conversation wasn't saved: Do notify (query donations collection as fallback)
Query Strategy:
// Primary: Saved conversations
const conversations = await db.collection('conversations')
.where('caseId', '==', caseId)
.get();
// Fallback: Donations (if conversation missing)
const donations = await db.collection('donations')
.where('caseId', '==', caseId)
.where('status', '==', 'completed')
.get();
// Combine and deduplicate by userId
const userIds = new Set([
...conversations.docs.map(doc => doc.data().userId),
...donations.docs.map(doc => doc.data().userId)
]);
5. Guardian "Follow" Logic: ✅ IMPLICIT FOLLOW
Recommendation: Implicit follow based on saved conversations from previous cases
Rationale:
- No explicit "follow" feature exists (and may not be needed)
- Users who engaged with a guardian's previous case likely care about new cases
- Simpler UX: automatic, no extra action required
- Can add explicit follow later if needed
Implementation:
// When guardian creates new case:
1. Query conversations collection:
- Find all conversations where case.guardianId == newCase.guardianId
- Group by userId (get unique users)
2. For each unique userId:
- Check if they have active conversation with this guardian
- If yes, create guardian_new_case notification
Logic:
- User has saved conversation with Case A (guardian: John)
- Guardian John creates Case B
- → User gets
guardian_new_casenotification
Future Enhancement:
- Add explicit "Follow Guardian" button
- Store in
followscollection:{ userId, guardianId, type: 'guardian' } - Use explicit follows + implicit (conversations) for notifications
📋 IMPLEMENTATION PRIORITY SUMMARY
Immediate Decisions:
- ✅ Database: Unified collection in toto-f9d2f
- ✅ User ID: userId (uid) primary, userEmail secondary
- ✅ Delivery: In-app only for MVP
- ✅ Conversations: All saved conversations (not just donors)
- ✅ Guardian Follow: Implicit based on conversations
Schema Updates Needed:
interface Notification {
id: string;
userId: string; // REQUIRED: Firebase uid
userEmail: string; // REQUIRED: Email
app: 'toto-app' | 'toto-bo'; // NEW: Source app
type: NotificationType;
title: string;
message: string;
priority: 'low' | 'medium' | 'high' | 'urgent';
metadata?: {
caseId?: string;
donationId?: string;
guardianId?: string;
[key: string]: unknown;
};
read: boolean;
createdAt: string;
updatedAt: string;
}
📚 Related Documentation
- Notification System Technical Docs
- Notification System User Guide
- Data Models
- Donation Verification KB
- Totitos System KB
✅ Next Steps
- Review this document and refine notification categories
- Answer critical questions above
- Prioritize implementation phases
- Create detailed implementation plan for Phase 1
- Begin implementation with notification type extensions
Last Updated: January 2025
Status: Planning Phase - Awaiting Review