# Product Requirements Document

## Validation Checklist

- [x] All required sections are complete
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Problem statement is specific and measurable
- [x] Problem is validated by evidence (not assumptions)
- [x] Context → Problem → Solution flow makes sense
- [x] Every persona has at least one user journey
- [x] All MoSCoW categories addressed (Must/Should/Could/Won't)
- [x] Every feature has testable acceptance criteria
- [x] Every metric has corresponding tracking events
- [x] No feature redundancy (check for duplicates)
- [x] No contradictions between sections
- [x] No technical implementation details included
- [x] A new team member could understand this PRD

---

## Product Overview

### Vision

Enable real-time team communication within the BuyerKiosk Live app so store teams can coordinate instantly without leaving the app they use all day for operations.

### Problem Statement

Store teams currently rely on external messaging apps (SMS, GroupMe, WhatsApp) to communicate about operational matters - shift changes, customer escalations, inventory updates, and daily coordination. This creates three problems:

1. **Context switching**: Staff leave the BuyerKiosk app to check messages, losing focus on operational tasks and missing real-time queue/performance updates
2. **Information silos**: Important operational decisions made in external chats are disconnected from the store data they reference, making it hard to track what was decided and why
3. **No management oversight**: Managers have no visibility into store communication patterns, can't ensure important announcements reach everyone, and can't moderate inappropriate content

The BuyerKiosk Team app already ships a fully functional Staff Chat module that has been validated with users. The Live app currently shows a "Chat coming soon" placeholder on its Chat tab, creating an expectation gap.

### Value Proposition

By integrating the proven Staff Chat module from the Team app, Live app users get:
- **Zero context switching** - chat lives alongside queues, stats, and tasks in the same app
- **Store-scoped conversations** - channels organized per store, automatically matching the user's store access
- **Role-based communication** - public channels for all staff, manager-only channels for sensitive topics, owner-only channels for strategic discussions
- **Real-time messaging** - instant delivery with typing indicators, read receipts, and @mentions
- **Familiar experience** - identical feature set to the Team app, no retraining needed

## User Personas

### Primary Persona: Store Employee (Buyer/Seller)
- **Demographics:** Store staff member, moderate tech proficiency, uses the Live app daily for queue and transaction monitoring
- **Goals:** Stay informed about store operations, coordinate with teammates about queue management, get notified about announcements and schedule changes
- **Pain Points:** Misses important team messages because they're in a separate app; doesn't know about last-minute changes until it's too late; feels disconnected from team decisions

### Secondary Persona: Store Manager
- **Demographics:** Manages 1-3 stores, uses the Live app to monitor performance and coordinate teams, higher tech proficiency
- **Goals:** Broadcast announcements that reach all staff, coordinate across stores, manage channels for different topics (opening procedures, closing checklists, general chat), moderate conversations
- **Pain Points:** Can't ensure messages reach everyone; no way to organize conversations by topic; external chat apps don't respect store access boundaries; no audit trail for important decisions

### Tertiary Persona: Store Owner / Area Manager
- **Demographics:** Oversees multiple stores, uses the Live app primarily for KPI monitoring and high-level oversight
- **Goals:** Communicate policy changes to managers, create owner-only discussion channels for sensitive business topics, monitor communication health across stores
- **Pain Points:** No centralized communication platform tied to store operations; relies on phone calls and fragmented group chats; can't delegate channel creation to managers while retaining oversight

## User Journey Maps

### Primary User Journey: Daily Team Communication

1. **Awareness:** Employee opens the Live app for their shift and sees a badge count on the Chat tab indicating unread messages
2. **Engagement:** Employee taps the Chat tab and sees a list of channels (General, Opening, Closing, etc.) with unread indicators showing which channels have new activity
3. **Interaction:** Employee opens a channel, reads recent messages, scrolls up for older messages, and types a response or reacts with an emoji
4. **Notification:** When @mentioned by a manager, the employee sees it in their Mentions tab and can tap to navigate directly to the message in context
5. **Return:** Employee switches back to other tabs (Home, Buys, Ops) and returns to Chat when new messages arrive

### Secondary User Journey: Manager Announcement Broadcast

1. **Need:** Manager needs to announce a schedule change or policy update to all staff at a store
2. **Creation:** Manager navigates to Chat, sees their channels, and sends a message in the appropriate channel (or creates a new channel if needed)
3. **Delivery:** All staff with access to that channel receive the message in real-time with push notification support
4. **Verification:** Manager can see read receipts to confirm who has seen the announcement
5. **Follow-up:** Staff can react (thumbs up) to acknowledge or reply with questions

### Tertiary User Journey: Cross-Store Coordination (Manager)

1. **Context:** Manager switches between stores using the store switcher in the Live app
2. **Access:** Chat channels automatically update to show the selected store's channels
3. **Communication:** Manager can send messages in each store's channels while monitoring store performance in the same app
4. **Tracking:** Mentions tab aggregates @mentions from all stores, providing a single inbox for action items

## Feature Requirements

### Must Have Features

#### Feature 1: Channel List View
- **User Story:** As a store team member, I want to see all chat channels I have access to so that I can choose which conversation to engage with
- **Acceptance Criteria:**
  - [ ] Channels displayed in a list sorted by most recent activity
  - [ ] Each channel shows name, last message preview, timestamp, and unread count badge
  - [ ] Pinned channels appear at the top of the list in user-defined order
  - [ ] Muted channels appear with dimmed styling
  - [ ] Pull-to-refresh reloads channel list
  - [ ] Empty state shown when no channels exist

#### Feature 2: Message Thread View
- **User Story:** As a store team member, I want to read and send messages in a channel so that I can communicate with my team in real-time
- **Acceptance Criteria:**
  - [ ] Messages displayed in chronological order (newest at bottom)
  - [ ] Infinite scroll loads older messages when scrolling up
  - [ ] Own messages visually distinct from others (right-aligned vs left-aligned)
  - [ ] System messages (member joined/left) displayed as centered, styled differently
  - [ ] Deleted messages shown as "[deleted]" placeholder
  - [ ] Edited messages show "edited" indicator
  - [ ] Typing indicators visible when other users are composing
  - [ ] Message composer at bottom with text input and send button

#### Feature 3: Send & Edit Messages
- **User Story:** As a store team member, I want to send messages and correct mistakes so that I can communicate clearly
- **Acceptance Criteria:**
  - [ ] Text messages up to 4,000 characters supported
  - [ ] Messages appear optimistically before server confirmation
  - [ ] Failed messages show retry option
  - [ ] Own messages editable within 24-hour window
  - [ ] Own messages deletable (soft delete with "[deleted]" placeholder)
  - [ ] Rate limiting handled gracefully (30 messages/minute/channel)

#### Feature 4: @Mentions
- **User Story:** As a manager, I want to @mention specific team members so that they get notified and can respond to important messages
- **Acceptance Criteria:**
  - [ ] Typing "@" triggers autocomplete showing channel members
  - [ ] Selecting a member inserts their name as a mention
  - [ ] Mentioned users receive notification (via Mentions tab)
  - [ ] Mentions tab shows paginated list of all @mentions across channels
  - [ ] Tapping a mention navigates to the message in context

#### Feature 5: Emoji Reactions
- **User Story:** As a store team member, I want to react to messages with emoji so that I can acknowledge or respond quickly without typing
- **Acceptance Criteria:**
  - [ ] Quick-react bar with common emoji (thumbs up, heart, laugh, wow, sad, celebrate)
  - [ ] Full emoji keyboard accessible from reaction picker
  - [ ] Reaction chips below message show emoji and count
  - [ ] Tapping own reaction removes it
  - [ ] Maximum 20 unique emoji per message enforced
  - [ ] Rate limiting handled gracefully (20 reactions/minute)

#### Feature 6: Read Receipts
- **User Story:** As a manager, I want to know which team members have seen my messages so that I can follow up with those who haven't
- **Acceptance Criteria:**
  - [ ] Channel automatically marked as read when opened
  - [ ] Unread count on channel list updates in real-time
  - [ ] Badge count on Chat tab reflects total unread across all channels

#### Feature 7: Real-Time Updates
- **User Story:** As a store team member, I want to see new messages instantly without manually refreshing so that conversations feel natural
- **Acceptance Criteria:**
  - [ ] New messages appear in real-time via WebSocket connection
  - [ ] Message edits and deletes reflected in real-time
  - [ ] Reaction changes reflected in real-time
  - [ ] Connection status indicator shown when degraded (polling fallback)
  - [ ] Automatic reconnection with message resync after disconnect
  - [ ] Typing indicators update in real-time

#### Feature 8: Channel Pin & Mute
- **User Story:** As a store team member, I want to pin important channels and mute noisy ones so that I can prioritize my attention
- **Acceptance Criteria:**
  - [ ] Long-press or context menu on channel shows pin/mute options
  - [ ] Pinned channels persist locally per store
  - [ ] Muted channels suppress notifications but remain accessible
  - [ ] Mute state synced with server

### Should Have Features

#### Feature 9: Channel Management (Manager+)
- **User Story:** As a manager, I want to create and configure channels so that I can organize team communication by topic
- **Acceptance Criteria:**
  - [ ] Create channel with name, description, and access level (public/manager/owner)
  - [ ] Configure message retention period (days)
  - [ ] Add/remove members for non-default channels
  - [ ] Only managers and above can create channels
  - [ ] Default channels (e.g., General) cannot be deleted

#### Feature 10: Message Search
- **User Story:** As a store team member, I want to search for past messages so that I can find information discussed previously
- **Acceptance Criteria:**
  - [ ] Search within a specific channel by keyword
  - [ ] Minimum 2 characters required for search
  - [ ] Results show message with context (sender, timestamp)
  - [ ] Tapping a result scrolls to the message in the channel

#### Feature 11: Connection Status Awareness
- **User Story:** As a store team member, I want to know if my messages are being delivered so that I'm not talking into the void
- **Acceptance Criteria:**
  - [ ] Banner shown when connection is degraded (polling mode)
  - [ ] Banner shown when fully disconnected
  - [ ] Pending messages show sending indicator
  - [ ] Failed messages show error state with retry

### Could Have Features

#### Feature 12: Sound Feedback
- **User Story:** As a store team member, I want audio cues for chat events so that I notice new messages even when not looking at the screen
- **Acceptance Criteria:**
  - [ ] Sound plays on new message received (when in chat)
  - [ ] Sound plays on own message sent
  - [ ] Sounds can be toggled on/off in preferences

#### Feature 13: Attachment Display
- **User Story:** As a store team member, I want to view images and files shared in chat so that I can see visual information
- **Acceptance Criteria:**
  - [ ] Images display inline with thumbnail
  - [ ] Full-screen image viewer on tap
  - [ ] PDF and document attachments show download link
  - [ ] Signed download URLs handled (15-minute expiry, auto-refresh)

### Won't Have (This Phase)

- **File/Image Upload** - Display existing attachments only; upload UI deferred to future phase
- **Reply Threading** - Reply-to-message feature deferred; models support it but UI is not built
- **Offline Message Queue** - No offline compose/send; messages require connectivity
- **Push Notifications for Chat** - Handled by existing Ably push infrastructure; no new push work needed in this spec
- **Global Cross-Channel Search** - Search limited to individual channels
- **Channel Deletion** - Only channel creation and settings management
- **Message Forwarding** - Not supported in current API

## Detailed Feature Specifications

### Feature: Message Thread View (Most Complex)

**Description:** The core chat experience where users read messages, compose new ones, see real-time updates, and interact with message content. This is the screen users spend the most time on.

**User Flow:**
1. User taps a channel from the channel list
2. System loads the most recent 50 messages and displays them
3. User scrolls up to load older messages (infinite scroll, 50 at a time)
4. User types a message in the composer at the bottom
5. System shows the message immediately (optimistic update) with a sending indicator
6. Server confirms delivery; message transitions to confirmed state
7. Other users' new messages appear in real-time at the bottom
8. Typing indicators show below the last message when others are composing
9. User swipes right on a message to open reaction picker
10. User long-presses own message to see edit/delete options

**Business Rules:**
- Rule 1: Messages can only be edited within 24 hours of sending. After 24 hours, the edit option is hidden.
- Rule 2: Deleted messages remain visible as "[deleted]" to preserve conversation context. The content is permanently removed.
- Rule 3: Each user can send a maximum of 30 messages per minute per channel. Exceeding this shows a "Slow down" message.
- Rule 4: Messages have a maximum length of 4,000 characters. The composer prevents exceeding this limit.
- Rule 5: Optimistic messages use a client-generated UUID (`clientMessageId`) for deduplication when the server confirms.
- Rule 6: When a user has been disconnected for more than 5 minutes, a full resync is triggered on reconnection.
- Rule 7: The in-memory message cache holds a maximum of 100 messages per channel. Scrolling beyond this triggers a fresh load.

**Edge Cases:**
- Scenario 1: Network disconnects while sending → Expected: Message shows "failed to send" with retry button. Retrying resends with same `clientMessageId` to prevent duplicates.
- Scenario 2: User edits a message that was already deleted by another device → Expected: 404 response handled gracefully, message removed from view.
- Scenario 3: User opens a channel they were removed from → Expected: 403 response shows "You no longer have access to this channel" and navigates back.
- Scenario 4: Rate limit exceeded → Expected: 429 response shows "Slow down! Please wait a moment before sending" with `Retry-After` countdown.
- Scenario 5: Very long channel with 1000+ messages → Expected: Infinite scroll loads 50 at a time, never loads entire history at once.
- Scenario 6: User receives a message while the app is in background → Expected: Message appears when user returns to the channel.

## Success Metrics

### Key Performance Indicators

- **Adoption:** 70%+ of active Live app users open the Chat tab within the first month after launch
- **Engagement:** Average 5+ messages per active chat user per day within 3 months
- **Channel Activity:** At least 1 message per store per day in active stores
- **Real-time Reliability:** 95%+ of messages delivered within 2 seconds via WebSocket (non-polling)
- **Quality:** Less than 1% message send failure rate (excluding network errors)
- **Retention Impact:** Chat users return to the app 2x more frequently than non-chat users

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `chat_tab_opened` | `typeNum`, `channelCount`, `totalUnread` | Measure chat adoption and entry patterns |
| `chat_channel_opened` | `typeNum`, `channelId`, `unreadCount` | Track which channels get the most engagement |
| `chat_message_sent` | `typeNum`, `channelId`, `hasAttachment`, `hasMention`, `messageLength` | Measure messaging volume and patterns |
| `chat_message_edited` | `typeNum`, `channelId`, `messageId` | Track edit frequency |
| `chat_message_deleted` | `typeNum`, `channelId`, `messageId` | Track delete frequency |
| `chat_reaction_added` | `typeNum`, `channelId`, `emoji` | Measure reaction engagement |
| `chat_mention_tapped` | `typeNum`, `channelId`, `mentionedUserId` | Track mention follow-through |
| `chat_channel_created` | `typeNum`, `channelName`, `accessLevel` | Track manager channel management |
| `chat_search_performed` | `typeNum`, `channelId`, `queryLength`, `resultCount` | Measure search utility |
| `chat_connection_degraded` | `typeNum`, `durationMs`, `fallbackMode` | Monitor real-time reliability |
| `chat_message_failed` | `typeNum`, `channelId`, `errorType` | Track delivery failures |
| `chat_channel_pinned` | `typeNum`, `channelId`, `pinned` | Measure personalization usage |
| `chat_channel_muted` | `typeNum`, `channelId`, `muted` | Measure notification management |

---

## Constraints and Assumptions

### Constraints
- **Shared Package Dependency**: The `buyerkiosk_chat` shared package (models, entities, services, repository) from the Team app is the foundation. Any model changes must be compatible with both apps.
- **API Parity**: The Staff Chat API already exists and serves the Team app. No new API endpoints are needed; the Live app consumes the same endpoints.
- **Store-Scoped**: All chat operations are scoped to the current store's `typeNum`. Users see different channels when switching stores.
- **JWT Auth**: The Live app's unified JWT auth system (Spec 003) provides the Bearer token. Chat API uses the same auth mechanism - no separate login needed.
- **Ably Infrastructure**: Real-time messaging uses the Ably service already integrated for push notifications. Chat-specific Ably tokens are obtained via a dedicated endpoint.

### Assumptions
- **Backend Ready**: The Staff Chat API is fully operational (already serving Team app traffic)
- **Ably Capacity**: Current Ably plan supports additional real-time channels from Live app users
- **Package Compatibility**: The shared `buyerkiosk_chat` package's dependencies are compatible with the Live app's dependency versions (same Flutter/Dart SDK, same Dio, Freezed, Ably versions)
- **User Familiarity**: Some users already use the Team app's chat, so the identical UX reduces onboarding friction
- **Employee Records**: The JWT auth response includes employee information needed for message attribution and @mention resolution

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Package dependency conflicts between Live and Team apps | High | Medium | Pin compatible versions; test integration early before building UI |
| Ably connection issues in areas with poor connectivity | Medium | Medium | Polling fallback (30-second interval) already built into shared package |
| Chat feature increases data usage significantly | Low | Low | Messages are text-only (small payload); attachments display-only with lazy loading |
| Users overwhelmed by notifications from chat | Medium | Medium | Channel mute feature; notification preferences; respect OS notification settings |
| Message send failures create confusion | Medium | Low | Optimistic UI with clear retry UX; clientMessageId prevents duplicates |
| Performance impact from real-time WebSocket connections | Medium | Low | Single Ably connection shared with push notifications; connection pooling built-in |

## Open Questions

- [x] Can the `buyerkiosk_chat` shared package be referenced via local path dependency from the Live app? (Answer: Yes, via `path: ../buyerkiosk-team/packages/buyerkiosk_chat`)
- [ ] Does the Ably plan have sufficient concurrent connection capacity for Live app users in addition to Team app users?
- [ ] Should the Chat tab badge count (total unread) be visible when the app is backgrounded (app icon badge)?
- [ ] Are there any stores where the Staff Chat API is disabled or gated behind a feature flag?
- [ ] Should analytics events be sent through the existing analytics pipeline or a new chat-specific one?

---

## Supporting Research

### Competitive Analysis

The Staff Chat module is modeled after proven team communication patterns from Slack, Microsoft Teams, and in-app messaging solutions. Key differentiators:
- **Store-scoped** rather than organization-wide - reduces noise and matches operational boundaries
- **Role-based channels** (public/manager/owner) - built-in access control without manual configuration
- **Embedded in operations app** - no context switching to communicate about what's visible on screen

### User Research

The BuyerKiosk Team app has already validated the chat feature with real users. The identical feature set means:
- UI patterns are tested and refined through Team app usage
- API stability is proven through production traffic
- Real-time architecture is validated at scale
- Common edge cases (network failures, rate limits) are already handled

### Market Data

- 95% of retail teams use at least one messaging app for work communication (industry surveys)
- Average employee checks work messages 15+ times per day
- In-app communication features increase daily active usage by 30-50% in workforce management apps
- Real-time messaging is a top-3 requested feature in retail operations software
