# Appreciation App

A comprehensive appreciation system for sending and tracking appreciation to users and physicians in the PX360 healthcare platform.

## Features

### Core Functionality
- **Send Appreciation**: Users can send appreciation to colleagues and physicians
- **Multi-Recipient Support**: Send to both users and physicians
- **Categories**: Categorize appreciations (Excellent Care, Team Player, Innovation, etc.)
- **Visibility Control**: Private, Department, Hospital, or Public visibility
- **Anonymous Option**: Send appreciations anonymously
- **Multi-Language**: Full English and Arabic support

### Notifications
- Automatic email notifications to recipients
- SMS notifications when phone number is available
- Integration with the notification system

### Gamification
- **Badges System**: Automatically award badges based on achievements
  - First Appreciation (1 appreciation)
  - Rising Star (5 appreciations)
  - Shining Star (10 appreciations)
  - Super Star (25 appreciations)
  - Legendary (50 appreciations)
  - Monthly Champion (10 appreciations in a month)
  - Consistent (4-week streak)
  - Well-Loved (10 different senders)
- **Leaderboard**: Hospital and department rankings
- **Statistics**: Track received, sent, and acknowledged appreciations

### Analytics
- Monthly statistics tracking
- Category breakdown analysis
- Hospital and department rankings
- Appreciation trends over time

## Models

### Appreciation
Main model for tracking appreciation messages.

Fields:
- `sender`: User who sent the appreciation
- `recipient`: Generic foreign key to User or Physician
- `category`: Optional category
- `message_en`: English message
- `message_ar`: Arabic message
- `visibility`: Private, Department, Hospital, or Public
- `is_anonymous`: Whether sender is anonymous
- `status`: Draft, Sent, Acknowledged
- `hospital`: Hospital association
- `department`: Department association
- `sent_at`: When appreciation was sent
- `acknowledged_at`: When appreciation was acknowledged

### AppreciationCategory
Categories for organizing appreciations.

Fields:
- `hospital`: Hospital association (null for system-wide)
- `code`: Unique code
- `name_en`: English name
- `name_ar`: Arabic name
- `icon`: Font Awesome icon
- `color`: Hex color code
- `order`: Display order

### AppreciationBadge
Badges that can be earned.

Fields:
- `hospital`: Hospital association (null for system-wide)
- `code`: Unique code
- `name_en`: English name
- `name_ar`: Arabic name
- `icon`: Font Awesome icon
- `color`: Hex color code
- `criteria_type`: Type of criteria (received_count, received_month, streak_weeks, diverse_senders)
- `criteria_value`: Value required to earn badge

### UserBadge
Tracking badges earned by recipients.

Fields:
- `recipient`: Generic foreign key to User or Physician
- `badge`: Badge earned
- `appreciation_count`: Count when badge was earned
- `earned_at`: When badge was earned

### AppreciationStats
Monthly statistics for recipients.

Fields:
- `recipient`: Generic foreign key to User or Physician
- `hospital`: Hospital association
- `department`: Department association
- `year`: Year
- `month`: Month
- `received_count`: Number of appreciations received
- `sent_count`: Number of appreciations sent
- `acknowledged_count`: Number of appreciations acknowledged
- `category_breakdown`: JSON breakdown by category
- `hospital_rank`: Rank within hospital
- `department_rank`: Rank within department

## API Endpoints

### Appreciations
- `GET /api/v1/appreciation/appreciations/` - List appreciations (filtered by user)
- `POST /api/v1/appreciation/appreciations/` - Create appreciation
- `GET /api/v1/appreciation/appreciations/{id}/` - Get appreciation detail
- `PATCH /api/v1/appreciation/appreciations/{id}/acknowledge/` - Acknowledge appreciation
- `GET /api/v1/appreciation/appreciations/my_appreciations/` - Get appreciations received by current user
- `GET /api/v1/appreciation/appreciations/sent_by_me/` - Get appreciations sent by current user
- `GET /api/v1/appreciation/appreciations/summary/` - Get summary statistics

### Categories
- `GET /api/v1/appreciation/categories/` - List categories
- `POST /api/v1/appreciation/categories/` - Create category (admin only)
- `GET /api/v1/appreciation/categories/{id}/` - Get category detail
- `PUT /api/v1/appreciation/categories/{id}/` - Update category (admin only)
- `DELETE /api/v1/appreciation/categories/{id}/` - Delete category (admin only)

### Badges
- `GET /api/v1/appreciation/badges/` - List badges
- `GET /api/v1/appreciation/user-badges/` - Get badges earned by current user
- `GET /api/v1/appreciation/user-badges/{id}/` - Get user badge detail

### Leaderboard
- `GET /api/v1/appreciation/leaderboard/` - Get hospital leaderboard
- `GET /api/v1/appreciation/leaderboard/?department_id={id}` - Get department leaderboard

### Statistics
- `GET /api/v1/appreciation/stats/` - Get statistics
- `GET /api/v1/appreciation/stats/{year}/{month}/` - Get statistics for specific month
- `GET /api/v1/appreciation/stats/trends/` - Get trends over time

## Setup

### 1. Add app to INSTALLED_APPS

```python
INSTALLED_APPS = [
    # ... other apps
    'apps.appreciation',
]
```

### 2. Run migrations

```bash
python manage.py makemigrations appreciation
python manage.py migrate appreciation
```

### 3. Seed initial data

```bash
python manage.py seed_appreciation_data
```

This will create default categories and badges.

### 4. Add URLs to main URL configuration

The URLs are automatically included through the app's URL configuration.

## Usage

### Sending an Appreciation

```python
from apps.appreciation.models import Appreciation, AppreciationCategory
from django.contrib.auth import get_user_model

User = get_user_model()

# Get users
sender = User.objects.get(username='sender')
recipient = User.objects.get(username='recipient')
category = AppreciationCategory.objects.get(code='excellent_care')

# Create appreciation
appreciation = Appreciation.objects.create(
    sender=sender,
    recipient_content_type=ContentType.objects.get_for_model(User),
    recipient_object_id=recipient.id,
    category=category,
    message_en='Thank you for your excellent care!',
    message_ar='شكراً لرعايتك المتميزة!',
    visibility='public',
    is_anonymous=False,
    hospital=sender.hospital,
    department=sender.department,
    status=Appreciation.AppreciationStatus.SENT,
)
```

### Awarding Badges

Badges are automatically awarded when appreciations are sent. The signal handler checks badge criteria and awards badges when conditions are met.

```python
from apps.appreciation.signals import check_and_award_badges

# Manually check for badges (usually done automatically)
check_and_award_badges(appreciation)
```

### Viewing Leaderboard

```python
from apps.appreciation.views import LeaderboardView

# Get hospital leaderboard
view = LeaderboardView()
leaderboard = view.get_queryset()
for entry in leaderboard:
    print(f"{entry.rank}: {entry.recipient_name} - {entry.received_count}")
```

## Customization

### Adding Custom Categories

```python
from apps.appreciation.models import AppreciationCategory

category = AppreciationCategory.objects.create(
    hospital=hospital,  # or None for system-wide
    code='custom_category',
    name_en='Custom Category',
    name_ar='فئة مخصصة',
    description_en='Description',
    description_ar='الوصف',
    icon='fa-star',
    color='#FF5733',
    order=10,
)
```

### Adding Custom Badges

```python
from apps.appreciation.models import AppreciationBadge

badge = AppreciationBadge.objects.create(
    hospital=hospital,  # or None for system-wide
    code='custom_badge',
    name_en='Custom Badge',
    name_ar='شارة مخصصة',
    icon='fa-medal',
    color='#FFD700',
    criteria_type='received_count',
    criteria_value=100,
)
```

## UI Templates

The app includes a comprehensive UI template at `templates/appreciation/appreciation_list.html`.

Features:
- Dashboard with statistics cards
- Tabbed interface for different views
- Send appreciation modal
- Appreciation detail modal
- Leaderboard display
- Badge gallery
- Responsive design

Access the appreciation page at: `/appreciation/`

## Admin Interface

The app includes a comprehensive admin interface for managing:
- Appreciations
- Categories
- Badges
- User badges
- Statistics

All models are registered in `admin.py` with filters and search functionality.

## Signals

The app uses Django signals to handle:

1. **post_save** on Appreciation:
   - Send notifications to recipients
   - Update statistics
   - Check and award badges

## Permissions

- **Create**: Any authenticated user can send appreciation
- **View**: Users can view their own appreciations
- **Admin**: Admin users can view all appreciations
- **Category Management**: Admin only
- **Badge Management**: Admin only

## Best Practices

1. **Use Categories**: Always select an appropriate category when sending appreciation
2. **Be Specific**: Write detailed messages explaining why the appreciation is being sent
3. **Respect Privacy**: Use appropriate visibility settings
4. **Regular Review**: Regularly check and acknowledge received appreciations
5. **Celebrate Achievements**: Use the leaderboard and badges to celebrate top performers

## Troubleshooting

### Notifications not sending
- Check that the notification system is configured
- Verify recipient email/phone numbers are correct
- Check logs for errors in signals.py

### Badges not awarding
- Run `python manage.py check_badges` to manually trigger badge checks
- Verify criteria are met
- Check that badges are active

### Statistics not updating
- Check that signals are connected
- Verify AppreciationStatus is set to SENT
- Manually trigger statistics recalculation if needed

## Support

For issues or questions, please refer to the main PX360 documentation or contact the development team.
