# Feature Spec: Communications and Notifications

**Domain**: Communications  
**Status**: Draft  
**Version**: 0.1.0  
**Last Updated**: 2025-12-08

---

## Overview

The Communications and Notifications module provides team collaboration tools and notification channels to keep facility staff aligned. It includes task comments with @mentions, daily digest emails/notifications, an announcements channel for SOP changes and inspection dates, and role-based notification preferences.

---

## User Stories

### As a Staff Member

- I want to comment on tasks and @mention teammates so we can collaborate
- I want to receive a daily digest of my tasks so I know what's due today
- I want to see facility announcements so I'm aware of SOP changes and inspection dates

### As a Head Grower

- I want to post announcements about SOP changes so the team stays informed
- I want to @mention staff in task comments so they're notified of important updates
- I want to see which tasks have unresolved comments so I can follow up

### As a Compliance Manager

- I want to announce upcoming inspections so the team can prepare
- I want to ensure all staff acknowledge critical announcements

### As an Owner

- I want to configure notification preferences per role so users aren't overwhelmed
- I want to see communication history for audit purposes

---

## Requirements

### Functional Requirements

#### Task Comments and @Mentions

- **Comment on tasks**:
  - Markdown-supported text
  - @mention users (autocomplete)
  - Attach photos (optional)
  - Edit/delete own comments
- **Notifications**:
  - @mentioned users receive notification
  - Task assignee notified of new comments
  - Notification channels: in-app, email, mobile push (optional)
- **Comment history**:
  - Chronological display
  - User attribution and timestamp
  - Immutable after 5 minutes (edit window)

#### Daily Digest

- **Content**:
  - Tasks due today
  - Overdue tasks
  - Upcoming key events (e.g., day-21 defoliation, harvest dates)
  - Unread announcements
- **Delivery**:
  - Email (default)
  - In-app notification
  - Mobile push (optional)
- **Timing**:
  - Configurable per user (default: 7 AM)
  - Skip if no tasks/events

#### Announcements Channel

- **Post announcements**:
  - Title and body (markdown-supported)
  - Priority (normal, important, critical)
  - Target audience (all, specific roles)
  - Expiration date (optional)
- **Acknowledgment**:
  - Critical announcements require acknowledgment
  - Track who has acknowledged
  - Reminder notifications for unacknowledged
- **Display**:
  - Announcement feed (chronological)
  - Unread badge
  - Pin important announcements

#### Notification Preferences

- **Per user**:
  - Enable/disable daily digest
  - Digest delivery time
  - Enable/disable @mention notifications
  - Enable/disable announcement notifications
  - Preferred channels (email, in-app, mobile push)
- **Per role** (admin-configured defaults):
  - Default notification settings for new users

### Non-Functional Requirements

- **Performance**: Notifications delivered within 1 minute
- **Reliability**: Email delivery with retry logic
- **Accessibility**: WCAG 2.1 AA compliant
- **Privacy**: Users can opt out of non-critical notifications

---

## Out of Scope (v1)

- Real-time chat (Slack/Discord-style)
- Video calls or screen sharing
- File sharing beyond task attachments
- Integration with external communication tools (Slack, Teams)

---

## Acceptance Criteria

### Task Comments

- [ ] Users can comment on tasks with markdown
- [ ] Users can @mention teammates with autocomplete
- [ ] @mentioned users receive notifications
- [ ] Comments can be edited within 5 minutes
- [ ] Comment history is chronological with timestamps

### Daily Digest

- [ ] Users receive daily digest at configured time
- [ ] Digest includes tasks due today and overdue
- [ ] Digest includes upcoming key events
- [ ] Digest includes unread announcements
- [ ] Users can configure digest time or disable

### Announcements

- [ ] Admins can post announcements with priority
- [ ] Critical announcements require acknowledgment
- [ ] Unacknowledged users receive reminders
- [ ] Announcements can be pinned
- [ ] Announcements can expire automatically

### Notification Preferences

- [ ] Users can configure notification preferences
- [ ] Admins can set default preferences per role
- [ ] Users can opt out of non-critical notifications
- [ ] Notification channels (email, in-app, push) are configurable

---

## Technical Notes

### Data Model (Prisma Schema)

```prisma
model TaskComment {
  id          String   @id @default(cuid())
  taskId      String
  task        Task     @relation(fields: [taskId], references: [id])
  content     String   // markdown
  authorId    String
  author      User     @relation(fields: [authorId], references: [id])
  mentions    String[] // user IDs
  photos      String[] // URLs
  editedAt    DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Announcement {
  id          String   @id @default(cuid())
  title       String
  content     String   // markdown
  priority    AnnouncementPriority @default(NORMAL)
  targetRoles String[] // role IDs, empty = all
  requiresAck Boolean  @default(false)
  expiresAt   DateTime?
  pinned      Boolean  @default(false)
  authorId    String
  author      User     @relation(fields: [authorId], references: [id])
  acknowledgments AnnouncementAck[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model AnnouncementAck {
  id            String   @id @default(cuid())
  announcementId String
  announcement  Announcement @relation(fields: [announcementId], references: [id])
  userId        String
  user          User     @relation(fields: [userId], references: [id])
  acknowledgedAt DateTime @default(now())
}

model NotificationPreference {
  id          String   @id @default(cuid())
  userId      String   @unique
  user        User     @relation(fields: [userId], references: [id])
  dailyDigest Boolean  @default(true)
  digestTime  String   @default("07:00") // HH:MM
  mentions    Boolean  @default(true)
  announcements Boolean @default(true)
  channels    Json     // { email: true, inApp: true, push: false }
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Notification {
  id          String   @id @default(cuid())
  userId      String
  user        User     @relation(fields: [userId], references: [id])
  type        NotificationType
  title       String
  content     String
  link        String?  // deep link to related entity
  read        Boolean  @default(false)
  readAt      DateTime?
  createdAt   DateTime @default(now())
}

enum AnnouncementPriority {
  NORMAL
  IMPORTANT
  CRITICAL
}

enum NotificationType {
  TASK_ASSIGNED
  TASK_DUE
  TASK_OVERDUE
  TASK_COMMENT
  MENTION
  ANNOUNCEMENT
  DIGEST
  ALERT
}
```

### API Endpoints

- `GET /api/communications/comments/:taskId` - Get comments for task
- `POST /api/communications/comments` - Post comment
- `PATCH /api/communications/comments/:id` - Edit comment
- `DELETE /api/communications/comments/:id` - Delete comment
- `GET /api/communications/announcements` - List announcements
- `POST /api/communications/announcements` - Post announcement
- `POST /api/communications/announcements/:id/acknowledge` - Acknowledge announcement
- `GET /api/communications/notifications` - Get user notifications
- `PATCH /api/communications/notifications/:id/read` - Mark notification as read
- `GET /api/communications/preferences` - Get user notification preferences
- `PATCH /api/communications/preferences` - Update notification preferences
- `POST /api/communications/digest/send` - Trigger daily digest (cron job)

### UI Components

- `TaskCommentThread` - Comment thread for tasks
- `CommentForm` - Comment input with @mention autocomplete
- `AnnouncementFeed` - Announcement list with filters
- `AnnouncementCard` - Announcement display with acknowledgment
- `AnnouncementForm` - Announcement creation/editing
- `NotificationBell` - In-app notification dropdown
- `NotificationPreferences` - User notification settings
- `DigestPreview` - Preview of daily digest

---

## Dependencies

- **Tasks** module (for task comments)
- **Authentication** (for user mentions and RBAC)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Notification fatigue | High | Configurable preferences; smart batching; daily digest |
| Email deliverability | Medium | Use reputable email service (SendGrid, Mailgun); retry logic |
| Spam/abuse of @mentions | Medium | Rate limiting; admin moderation tools |
| Missed critical announcements | High | Require acknowledgment; reminder notifications |

---

## Email Templates

### Daily Digest

```
Subject: Your tasks for [Date]

Hi [Name],

Here's your daily summary:

**Tasks Due Today** (3)
- [Task 1] - [Room/Batch]
- [Task 2] - [Room/Batch]
- [Task 3] - [Room/Batch]

**Overdue Tasks** (1)
- [Task 4] - [Room/Batch] (due [Date])

**Upcoming Events**
- Day-21 defoliation for Batch #123 (tomorrow)
- Harvest for Batch #456 (in 3 days)

**Unread Announcements** (1)
- [Announcement Title] (posted [Date])

[View Full Dashboard]
```

### @Mention Notification

```
Subject: [User] mentioned you in a task comment

Hi [Name],

[User] mentioned you in a comment on "[Task Name]":

"[Comment excerpt...]"

[View Task]
```

### Critical Announcement

```
Subject: [IMPORTANT] [Announcement Title]

Hi [Name],

A critical announcement has been posted:

[Announcement content]

Please acknowledge this announcement by [Date].

[Acknowledge Now]
```

---

## Future Enhancements (Post-v1)

- Real-time chat (Slack/Discord-style)
- Video calls or screen sharing
- File sharing beyond task attachments
- Integration with external communication tools (Slack, Teams, Discord)
- Mobile app with push notifications
- Voice-to-text for comments
- Translation for multilingual teams
