Skip to main content

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
  • 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 function
    • toto-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 modal
    • toto-bo/src/components/ui/NotificationBell.tsx - Bell icon with badge
    • toto-bo/src/components/ui/NotificationBadge.tsx - Badge component
    • toto-bo/src/components/ui/ToastNotifications.tsx - Toast system
    • toto-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 docs
    • toto-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.ts
    • toto-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 conversations collection (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 users
  • user_engagement_reminder - "We miss you, come back to the app" (after X days inactive)
  • profile_update_required - Reminder to complete profile
  • totitos_balance_update - Periodic balance summary (optional)
  • 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 completed
  • case_urgent_update - Urgent update on case they're following
  • 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)
  • donation_verification_pending - Reminder to submit donation proof (after X days)
  • donation_verification_submitted - Confirmation that proof was received
  • donation_verified - Guardian verified the donation (totitos will be assigned)
  • donation_verification_failed - Verification failed, needs resubmission
  • totitos_assigned - Totitos have been assigned after verification
  • donation_received_by_guardian - Guardian received the donation (confirmation)

5. General/System

  • system_announcement - General announcements for all donors
  • feature_update - New features available
  • maintenance_notice - Scheduled maintenance

🛡️ GUARDIANS (toto-bo)

1. Case Management

  • case_assigned - New case assigned to them
  • case_approval_required - Case pending admin approval
  • case_approved - Case approved by admin
  • case_rejected - Case rejected (with reason)
  • case_update_reminder - Reminder to update case status
  • case_urgent_attention - Case marked as urgent by admin
  • case_funding_milestone - Case reached funding milestone
  • case_funding_complete - Case reached funding goal
  • case_funding_low - Case funding is below expected

2. Donation Management

  • donation_received - New donation received for their case
  • donation_verification_request - Donor submitted proof, needs verification
  • donation_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 review
  • guardian_verification_approved - Verification approved
  • guardian_verification_rejected - Verification rejected (needs resubmission)
  • guardian_profile_update_required - Profile information needs updating
  • banking_alias_updated - Banking alias changed

4. Communication & Engagement

  • new_message_from_donor - New message in case conversation
  • case_comment_received - Comment on case (if comments exist)
  • donor_question - Question from donor about case

5. System & Admin

  • admin_message - Direct message from admin
  • system_maintenance - Scheduled maintenance
  • policy_update - Policy or terms update
  • training_available - New training resources available

👨‍💼 ADMINS (toto-bo)

1. Case Oversight

  • case_submitted_for_approval - New case submitted by guardian
  • case_requires_review - Case flagged for review
  • case_urgent_escalation - Case escalated to urgent
  • case_funding_anomaly - Unusual donation pattern detected
  • case_update_by_guardian - Guardian updated case (for monitoring)

2. User Management

  • guardian_registration - New guardian registered
  • guardian_verification_pending - Guardian verification documents submitted
  • user_report_received - User reported an issue
  • suspicious_activity - Suspicious user activity detected
  • bulk_user_action_required - Bulk action needed (e.g., mass email)

3. Financial & Donations

  • donation_anomaly - Unusual donation pattern
  • donation_verification_dispute - Dispute in donation verification
  • payment_processing_error - Payment processing failed
  • financial_report_ready - Financial report generated
  • funding_goal_analysis - Analysis of funding goals vs actuals

4. System & Operations

  • system_error - System error detected
  • security_alert - Security event detected
  • performance_issue - Performance degradation
  • database_backup_complete - Backup completed
  • scheduled_task_failed - Scheduled task failed
  • api_rate_limit_warning - API rate limit approaching

5. Support & Tickets

  • support_ticket_created - New support ticket
  • support_ticket_escalated - Ticket escalated
  • support_ticket_high_priority - High priority ticket created
  • support_ticket_sla_breach - SLA breach warning

6. Analytics & Reports

  • report_generated - Report ready for review
  • analytics_anomaly - Unusual analytics pattern
  • monthly_summary_ready - Monthly summary available
  • user_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_update notification 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)

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)

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_reminder notification

🏗️ 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 app field or separate by userEmail domain (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)

  1. ✅ Extend notification types to include donor types
  2. ✅ Create notification trigger functions
  3. ✅ Integrate case update notifications
  4. ✅ Integrate donation verification notifications

Phase 2: Donor System (High Priority)

  1. ✅ Create toto-app notification API endpoints
  2. ✅ Create toto-app notification service
  3. ✅ Integrate with existing toto-app notifications screen
  4. ✅ Add real-time hooks for toto-app

Phase 3: Guardian Notifications (Medium Priority)

  1. ✅ Implement guardian-specific notification triggers
  2. ✅ Add case assignment notifications
  3. ✅ Add donation verification workflow notifications

Phase 4: Admin Notifications (Medium Priority)

  1. ✅ Implement admin oversight notifications
  2. ✅ Add system monitoring notifications
  3. ✅ Add analytics/reporting notifications

Phase 5: Engagement & Optimization (Low Priority)

  1. ✅ User engagement reminders
  2. ✅ Notification preferences
  3. ✅ Digest mode
  4. ✅ Push notifications (future)

🚨 Critical Questions to Resolve

  1. Database Separation:

    • Should toto-app and toto-bo use the same notifications collection?
    • Or separate collections with different Firebase projects?
  2. User Identification:

    • Use userEmail as primary identifier (current approach)?
    • Or userId? (More reliable, but requires cross-app user sync)
  3. Notification Delivery:

    • In-app only initially?
    • Email integration needed?
    • Push notifications priority?
  4. Saved Conversations Criteria:

    • Only users who donated?
    • Or all users who saved conversation?
    • What about users who just "liked" a case?
  5. 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 uid across 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-f9d2f Firestore (main app database)
  • toto-bo accesses via existing cross-project pattern
  • Add app field 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
  • userEmail is:
    • ✅ 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 userId where missing
  • Make userId required in schema
  • Keep userEmail for 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_case notification

Future Enhancement:

  • Add explicit "Follow Guardian" button
  • Store in follows collection: { userId, guardianId, type: 'guardian' }
  • Use explicit follows + implicit (conversations) for notifications

📋 IMPLEMENTATION PRIORITY SUMMARY

Immediate Decisions:

  1. Database: Unified collection in toto-f9d2f
  2. User ID: userId (uid) primary, userEmail secondary
  3. Delivery: In-app only for MVP
  4. Conversations: All saved conversations (not just donors)
  5. 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;
}


✅ Next Steps

  1. Review this document and refine notification categories
  2. Answer critical questions above
  3. Prioritize implementation phases
  4. Create detailed implementation plan for Phase 1
  5. Begin implementation with notification type extensions

Last Updated: January 2025
Status: Planning Phase - Awaiting Review