Skip to content

DORY is a cognitive support application designed to help people experiencing early to moderate memory decline stay mentally engaged in a non-stressful, non-diagnostic way, while reducing caregiver burden through simple progress tracking and sharing.

Notifications You must be signed in to change notification settings

callanicha/DORY_webapp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dory - Cognitive Care Platform

Dory is a compassionate cognitive care platform designed to bring moments of joy and connection to people living with dementia and their caregivers. The platform provides gentle cognitive activities, mood tracking, progress analytics, and memory lane features to support cognitive health and engagement.

Features

For Patients

  • Interactive Cognitive Games: 12+ game types including image matching, music recognition, proverb completion, memory flip cards (5 themes), simple math (11 games), counting, number comparison, personal questions, yes/no confidence builder, sequence memory, and spot-the-change attention training
  • Personalized Content: Culture-specific content packs (France, US, UK, Germany, Spain, Thailand, Japan) tailored to patient backgrounds
  • Gentle Experience: Calm, distraction-free interface designed for cognitive accessibility with dementia-friendly design principles
  • Mood Tracking: Simple mood recording after each session (Calm, Neutral, Agitated) with visual mood indicators
  • Orientation Support: Daily reminders with checklists, location awareness, and reassurance phrases
  • Mascot Stickers: Friendly mascot characters providing encouragement throughout the experience

For Caregivers

  • Dashboard: Overview of weekly sessions, minutes played, and day streaks with hover animations
  • Progress Tracking: Detailed analytics with charts, mood distribution, activity calendar, and session history
  • Caregiver Report: Comprehensive reports with per-game statistics, mood analytics (distribution and trends), personal preferences tracking, brain activity heatmap, and highlights
    • PIN Protection: Secure access with 4-6 digit PIN required every time (strict one-time verification, no persistence)
    • Rate Limiting: 5 attempts maximum with 10-minute lockout after failed attempts
    • Automatic Reset: Failed attempts counter resets after lockout expires, providing fresh attempts
  • Brain Activity Overview: Visual heatmap showing cognitive activity across brain regions (frontal, temporal, memory, visual) with interactive tooltips explaining each area
  • Personal Preferences Tracking: View patient preferences with "view more/less" functionality and conclusion summaries (most recent and most often answers)
  • Memory Lane: Create and manage memory collections with images, audio, and voice recordings
  • Session History: View past sessions with mood indicators (color-coded gradients) and performance metrics
  • Patient Profile Management: Configure patient information, dementia stage, and cultural preferences
  • Orientation Settings: Manage reminders, location, and reassurance phrases with checklist functionality

Tech Stack

Frontend

  • Framework: Next.js 16 (App Router)
  • Language: TypeScript
  • Styling: Tailwind CSS 4
  • UI Components: Radix UI primitives
  • Charts: Recharts
  • Deployment: Vercel-ready

Backend (Microservices)

  • Architecture: Microservices with API Gateway pattern
  • Services:
    • API Gateway (Port 3008): Routes requests to appropriate services
    • Auth Service (Port 3001): Authentication, user management, subscriptions, report PIN
    • Core Service (Port 3002): Patients, sessions, analytics, memory-lane, orientation
    • Shared Library: Common utilities (JWT, password hashing, Prisma client, middleware)
  • Database: PostgreSQL with Prisma ORM
  • Authentication: JWT (JSON Web Tokens)
  • Containerization: Docker & Docker Compose

For a full breakdown of microservices, API endpoints, and technology choices, see MICROSERVICES_AND_TECH.md.

Prerequisites

  • Node.js v18 or higher
  • npm or pnpm package manager
  • PostgreSQL (installed locally or via Docker)
  • pgAdmin (optional, for database management)

Quick Start

Option A: Frontend Only (Development)

For frontend development without microservices:

1. Clone the Repository

git clone <repository-url>
cd dory-cognitive-game

2. Install Dependencies

npm install

3. Set Up Database

Option A: Using Docker (Recommended)

# Start PostgreSQL container
docker-compose up -d postgres

Option B: Using Local PostgreSQL

Create a database named dory using pgAdmin or psql.

4. Configure Environment Variables

Create a .env file in the root directory:

DATABASE_URL="postgresql://dory:dory@localhost:5432/dory"

For local PostgreSQL, use your credentials:

DATABASE_URL="postgresql://YOUR_USERNAME:YOUR_PASSWORD@localhost:5432/dory"

5. Initialize Database

# Generate Prisma Client
npm run prisma:generate

# Push schema to database
npm run prisma:push

# Seed with test data
npm run seed

6. Start Development Server

npm run dev

Open http://localhost:3000 in your browser.

Option B: Full Stack with Microservices

For running the complete application with microservices:

1. Set Up Database (Same as above)

2. Start Microservices with Docker

# Build and start all services
docker-compose up -d

# View logs
docker-compose logs -f

Services will be available at:

3. Start Microservices Manually (Development)

# Install service dependencies and build shared library
cd services
./setup.sh

# Start all services
cd ..
./START_SERVICES.sh

# Stop all services
./STOP_SERVICES.sh

4. Test Services

# Run service tests
cd services
./test-services.sh

Test Credentials

After seeding, you can login with:

Email Password Patient
john.smith@test.com password123 Mary Smith (MEDIUM risk)
sarah.johnson@test.com password123 Robert Johnson (LOW risk)
emma.williams@test.com password123 James Williams (HIGH risk)

Project Structure

dory-cognitive-game/
├── app/                    # Next.js App Router pages
│   ├── (main)/            # Main authenticated routes
│   │   ├── home/          # Dashboard
│   │   ├── memories/      # Memory Lane
│   │   ├── orientation/   # Today/Orientation page
│   │   ├── progress/      # Progress tracking
│   │   ├── report/        # Caregiver report
│   │   └── settings/      # Settings
│   ├── session/           # Game session page
│   ├── api/               # API routes
│   └── onboarding/        # Onboarding flow
├── components/             # React components
│   ├── session/          # Game components
│   ├── progress/         # Analytics components
│   ├── report/           # Report components (brain activity map, preference cards)
│   ├── shared/           # Shared UI components
│   └── ui/               # Base UI components
├── lib/                   # Utilities and services
│   ├── api/              # API client
│   ├── auth/             # Authentication
│   ├── context/          # React context
│   ├── models/           # TypeScript types
│   ├── services/         # Business logic
│   └── utils/            # Helper functions
├── services/              # Microservices backend
│   ├── api-gateway/      # API Gateway (port 3008)
│   ├── auth-service/     # Authentication service (port 3001)
│   ├── core-service/     # Core business logic (port 3002)
│   ├── shared/           # Shared library (JWT, Prisma, middleware)
│   ├── setup.sh          # Setup script for IDE support
│   └── test-services.sh  # Service testing script
├── prisma/               # Database schema and migrations
├── public/               # Static assets
│   ├── audio/            # Game audio files
│   ├── brain/            # Brain SVG for activity heatmap
│   ├── comparison/       # Spot-the-change comparison images (A1-A3, B1-B3, C1-C3)
│   ├── mascot/           # Mascot stickers
│   └── mood/             # Mood icons (calm, neutral, agitated)
├── hooks/                # Custom React hooks
├── docker-compose.yml    # Docker Compose configuration
├── START_SERVICES.sh     # Script to start all services manually
├── STOP_SERVICES.sh      # Script to stop all services
├── MICROSERVICES_AND_TECH.md  # Microservices + tech stack documentation
├── QUICK_START.md        # Quick setup commands
├── SETUP.md              # Detailed setup guide
└── TEST_CREDENTIALS.md   # Test user credentials

Game Types

Core Training Games

  1. Image Matching: Match images to questions or categories
  2. Music Recognition: Identify familiar songs and melodies
  3. Proverb Completion: Complete well-known sayings
  4. Memory Flip: Card matching memory game (5 themes: fruits, animals, flowers, vehicles, shoes)
  5. Simple Math: Basic arithmetic exercises (11 games: additions and subtractions)
  6. Counting: Count objects in images (apples, strawberries)
  7. Comparison: Number comparison games ("Which is bigger?", "Which is smaller?")
  8. Yes or No?: Confidence builder with simple yes/no statements
  9. What Comes Next?: Sequence memory game with daily routine sequences
  10. Spot the Change: Attention training with side-by-side image comparison

Personal Engagement

  1. Personal Questions: Preference and memory questions (e.g., favorite food, music, hobbies)
  2. Memory Card Yes/No: Simple recognition questions

Session Structure

  • Each session contains exactly 5 questions:
    • 1 personal preference question
    • 4 training questions (each game type appears only once per session)
  • Questions are randomized but ensure variety
  • Each game type can only appear once per session (whether answered correctly, incorrectly, or skipped)

Key Pages

Home Dashboard

  • Weekly summary (sessions, minutes, streak)
  • Quick actions (Start Session, View Progress, Settings)
  • Next session card with suggested duration

Progress Page

  • Daily performance charts
  • Weekly line charts
  • Monthly activity calendar
  • Recent sessions with mood indicators
  • Clickable session details

Caregiver Report

  • PIN Protection:
    • Secure access requiring 4-6 digit PIN for every report access
    • Strict one-time verification: PIN must be entered each time (no "remember me" or session persistence)
    • PIN creation: Mandatory modal appears if no PIN exists when accessing report
    • Rate limiting: Maximum 5 failed attempts before 10-minute lockout
    • Lockout recovery: Failed attempts counter automatically resets after lockout expires
    • Real-time countdown: Visual timer shows remaining lockout time
    • Error handling: User-friendly error messages without breaking the UI
  • Last 4 weeks performance: Weekly line charts showing trends
  • Per-game statistics: Detailed breakdown (excluding personal questions)
  • Mood analytics: Distribution, most common mood, recent mood history with visual progress bars
  • Brain Activity Overview:
    • Interactive heatmap visualization of cognitive activity across brain regions
    • Color-coded regions: Strong (teal/blue), Needs Attention (yellow), Often Skipped (coral/red)
    • Hover tooltips with anatomical brain part names, descriptions, and metrics
    • This week vs Overall progress comparison
    • Legend with "How to read this" explanation
  • Personal Preferences Tracking:
    • View more/less functionality (shows first 3, expandable to all)
    • Conclusion summary per question: Most recent answer and Most often answer
    • Questions grouped by topic with date tracking
  • Highlights and insights: Key performance indicators
  • Loading animation: Smooth loader with "Preparing the report..." message

Memory Lane

  • Create memory collections
  • Add images, audio, and voice recordings
  • View and manage memories
  • Track engagement metrics

Orientation (Today)

  • Time of day display with custom sun/moon icons
  • Settings icon integrated into day/night box (top right)
  • Location and reassurance phrase (customizable)
  • Daily reminders with interactive checklists
  • Automatic midnight reset: All reminder checkmarks reset at midnight for fresh daily tracking
  • Reminder sorting (unfinished items first, completed below)
  • Reminder editing and management

Design System

  • Theme: Dark mode with soft gradients and glass-morphism effects
  • Colors:
    • Primary: Blue (#1694F9)
    • Secondary: Yellow (#FACE68)
    • Success: Green
    • Accent: Coral
  • Visual Effects:
    • Yellow gradient glow frames for important cards (session start, graphs, profiles)
    • Blue gradient glow for modals and pop-ups
    • Soft gradient overlays for mood indicators
    • Radial gradient glows for session intro page
  • Typography: Clean, readable fonts optimized for accessibility
  • Components: Custom Dory components with consistent styling (DoryCard, DoryButton, etc.)
  • Animations: Subtle, calm transitions respecting prefers-reduced-motion
  • Loading States: Liquid loader animation with configurable labels
  • Mascot Integration: Friendly mascot stickers throughout the experience

Development

Available Scripts

Frontend Scripts

# Development
npm run dev              # Start development server
npm run build            # Build for production
npm run start            # Start production server

# Database
npm run prisma:generate  # Generate Prisma Client
npm run prisma:push      # Push schema to database
npm run prisma:migrate   # Run migrations
npm run prisma:studio    # Open Prisma Studio
npm run seed             # Seed database with test data

# Code Quality
npm run lint             # Run ESLint

Microservices Scripts

# Service Management
./START_SERVICES.sh      # Start all microservices manually
./STOP_SERVICES.sh       # Stop all microservices
cd services && ./setup.sh # Setup services for IDE support
cd services && ./test-services.sh # Test all services

# Docker Management
docker-compose up -d     # Start all services in Docker
docker-compose down      # Stop all services
docker-compose logs -f   # View service logs
docker-compose restart   # Restart all services

Database Management

Using Prisma Studio:

npm run prisma:studio

Using Docker:

# Start PostgreSQL only
docker-compose up -d postgres

# Start all services (PostgreSQL + Microservices)
docker-compose up -d

# Stop PostgreSQL
docker-compose stop postgres

# Stop all services
docker-compose down

# View logs
docker-compose logs postgres
docker-compose logs -f  # Follow all service logs

# Reset database (removes all data)
docker-compose down -v

Microservices Architecture

The application uses a microservices architecture with an API Gateway pattern. For detailed documentation (architecture diagram, endpoints, configuration, and tech choices), see MICROSERVICES_AND_TECH.md.

Summary:

Service Port Role
API Gateway 3008 Single entry point; proxies to Auth and Core services
Auth Service 3001 Login, register, caregiver, subscriptions, report PIN
Core Service 3002 Patients, sessions, analytics, memory-lane, orientation
Shared Library JWT, password hashing, Prisma client, auth middleware

Service communication: Frontend → API Gateway → Auth/Core (HTTP/REST). All services use the shared library and a single PostgreSQL database.

Configuration

Environment Variables

Frontend (.env in root)

Create a .env file in the root directory:

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/dory"

# JWT Secret (for production)
JWT_SECRET="your-secret-key-here"

Microservices (docker-compose.yml)

The microservices use environment variables defined in docker-compose.yml:

environment:
  DATABASE_URL: "postgresql://postgres:password@host.docker.internal:5433/DORY_webapp"
  JWT_SECRET: ${JWT_SECRET:-dory-jwt-secret-change-in-production}
  AUTH_SERVICE_PORT: 3001
  CORE_SERVICE_PORT: 3002
  API_GATEWAY_PORT: 3000
  NODE_ENV: ${NODE_ENV:-production}

Note: For local development, you can override these by creating a .env file or setting environment variables before running docker-compose up.

Customization

  • Content Packs: Modify lib/services/content-service.ts to add custom game content
  • Comparison Images: Add new comparison pairs in public/comparison/ following naming pattern (X1.jpg, X2.jpg, X3.jpg) and update lib/utils/comparison-pairs.ts
  • Styling: Update app/globals.css for theme customization
  • Game Types: Add new game types in components/session/ and register in app/session/page.tsx
  • Mascot Stickers: Add new mascot images to public/mascot/ (exclude mascot_glasses.png from random selection)
  • Mood Icons: Replace mood images in public/mood/ (calm.PNG, neutral.png, agitated.png)

Features in Detail

Report PIN Protection

  • Security Model: One-time verification using URL query parameters (no cookies or sessionStorage persistence)
  • PIN Creation:
    • First-time setup: Mandatory modal appears when accessing report without a PIN
    • 4-6 digit numeric PIN required
    • PIN confirmation step to prevent typos
    • Secure hashing: PINs are hashed using bcrypt before storage
  • PIN Verification Flow:
    1. User enters PIN on /report/pin page
    2. Server verifies PIN and returns success
    3. Client redirects to /report/loading?verified=1
    4. Loading page validates query parameter and redirects to /report?verified=1
    5. Report page validates parameter, strips it from URL, and allows access
  • Rate Limiting:
    • Maximum 5 failed attempts per user
    • After 5 failures: 10-minute lockout period
    • Lockout UI: Shows countdown timer with remaining time
    • Automatic recovery: Failed attempts counter resets after lockout expires
  • User Experience:
    • Clear error messages: "Incorrect PIN. X attempt(s) remaining."
    • Lockout notification: "Account temporarily locked" with countdown
    • No error overlays: Errors displayed inline without breaking the UI
    • Smooth transitions: Loading page provides natural flow between verification and report

Mood Tracking

  • Visual mood indicators with color-coded gradients (Calm=Green, Neutral=Yellow, Agitated=Red)
  • Mood images from public/mood/ folder
  • Mood analytics in caregiver reports (distribution, trends, most common)
  • Session history with mood indicators and gradient overlays
  • Mood color blending into session cards for visual clarity

Progress Analytics

  • Stacked bar charts for daily performance
  • Line charts for weekly trends
  • Activity calendar for session consistency
  • Detailed session breakdowns

Memory Lane

  • Multiple content types (image, audio, voice)
  • Priority-based sorting
  • Engagement tracking
  • Rich media support

Spot the Change Game

  • Comparison Images System: Uses images from public/comparison/ folder
  • Pairing Logic:
    • Files ending with 1.jpg are always Image A (base)
    • Files ending with 2.jpg or 3.jpg are Image B (comparison)
    • Valid pairs: A1→A2, A1→A3, B1→B2, B1→B3, C1→C2, C1→C3
    • Never pairs 2↔3 directly
  • Side-by-Side Display: Both images shown simultaneously (no memory required)
  • Visual Assistance:
    • Forgiving tap detection (4x radius multiplier)
    • Encouraging feedback messages
    • Hint text after failed attempts
    • No visual circles (clean interface)
  • Extremely Easy Mode: Designed for dementia-friendly cognitive training

Orientation Support

  • Time-aware greetings with custom sun/moon icons
  • Settings icon integrated into day/night display box
  • Customizable location and reassurance phrases (persisted to database)
  • Reminder system with interactive checklists (custom checkbox design)
  • Automatic daily reset: All reminder checkmarks automatically reset at midnight
  • Reminder sorting: unfinished items on top, completed below
  • Reminder editing: modify label, description, and time
  • Daily orientation information display

Brain Activity Overview

  • Visual Heatmap: Side-view brain SVG with color-coded regions showing cognitive activity
  • Region Mapping:
    • Frontal (Prefrontal Cortex): Decision-making & Confidence
    • Temporal (Temporal Lobes): Music & Emotion
    • Memory (Hippocampus): Memory & Recall
    • Visual (Occipital Lobe): Visual Recognition
  • Score Calculation: Based on game performance (accuracy minus skip penalties)
  • Interactive Tooltips: Hover/tap to see:
    • Functional name and anatomical brain part name
    • Description of what the area focuses on
    • This week percentage (primary metric)
    • Overall percentage (lifetime average, secondary metric)
  • Color Scheme:
    • Strong (80-100%): Calm teal/blue gradient
    • Needs Attention (50-79%): Soft yellow gradient
    • Often Skipped (0-49%): Muted coral/red gradient
  • Smooth Visuals: Soft blended gradients with blur effects, no harsh edges
  • Legend: Collapsible legend with "How to read this" explanation

Personal Preferences Tracking

  • Question Grouping: Preferences grouped by question text
  • View More/Less: Shows first 3 most recent answers, expandable to view all
  • Conclusion Summary: Always visible per question:
    • Most recent answer (newest response)
    • Most often answer (mode, with tie-breaking: most recent among ties, then lexicographical)
  • Date Tracking: Each answer shows when it was recorded
  • Numbering: Answers numbered from newest (#total) to oldest (#1)

Troubleshooting

Database Connection Issues

Error: "Connection refused"

  • Ensure PostgreSQL is running: docker-compose up -d postgres
  • Verify DATABASE_URL in .env is correct
  • Check PostgreSQL port (default: 5432)

Error: "Database does not exist"

  • Create database: psql -U username -c "CREATE DATABASE dory;"
  • Or use pgAdmin to create the database

Prisma Issues

Error: "Prisma schema validation error"

  • Run npm run prisma:generate again
  • Check prisma/schema.prisma for syntax errors

Port Conflicts

Port 3000 already in use

  • Kill the process: lsof -ti:3000 | xargs kill
  • Or change port in package.json

Architecture Overview

Frontend (Next.js)

  • Single-page application with App Router
  • Client-side routing and state management
  • Direct API calls to backend services (or via API Gateway)
  • Server-side rendering for improved performance

Backend (Microservices)

  • API Gateway Pattern: Single entry point for all API requests (see MICROSERVICES_AND_TECH.md)
  • Service Separation: Auth and Core services handle different domains
  • Shared Library: Common code shared across services (JWT, Prisma, auth middleware)
  • Database: Single PostgreSQL database shared by all services (can be split in production)

Deployment Options

  1. Frontend Only: Deploy Next.js app to Vercel/Netlify
  2. Full Stack: Deploy all services using Docker Compose
  3. Hybrid: Frontend on Vercel, backend services on cloud providers (AWS, GCP, Azure)

Additional Documentation

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

Private - For use with Dory Cognitive Care platform only.

About

DORY is a cognitive support application designed to help people experiencing early to moderate memory decline stay mentally engaged in a non-stressful, non-diagnostic way, while reducing caregiver burden through simple progress tracking and sharing.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •