# BuyerKiosk Live Flutter App - Analysis Findings

**Analysis Date**: December 5, 2025
**Scope**: Full Stack Analysis (Business, Technical, Integration, Testing)
**Purpose**: Comprehensive system analysis for specification creation

---

## Executive Summary

BuyerKiosk Live is a **production-grade Flutter mobile application** migrated from Xamarin.Forms. It provides real-time retail store management for tracking buyer queues, completed transactions, buyer performance, workbook notes (announcements with reactions/comments), and daily KPI metrics.

### Key Findings

| Area | Assessment | Critical Issues |
|------|------------|-----------------|
| **Architecture** | Excellent | Clean Architecture, well-organized layers |
| **Business Logic** | Well-defined | Hierarchical permissions, state machines |
| **API Integration** | Comprehensive | 40+ endpoints, real-time via Ably |
| **Testing** | Critical Gap | ~0% coverage, only 1 smoke test |
| **State Management** | Modern | Riverpod 3.x with AsyncNotifier |
| **Error Handling** | Robust | Multi-layer exception hierarchy |

---

## 1. Technical Architecture

### Stack Overview

| Component | Technology | Version |
|-----------|------------|---------|
| Framework | Flutter | 3.38.3 |
| Language | Dart | 3.10.1 |
| State Management | Riverpod | 3.x (AsyncNotifier) |
| Navigation | GoRouter | 17.x |
| Models | Freezed | 3.x |
| Entities | Equatable | - |
| HTTP Client | Dio | - |
| Secure Storage | flutter_secure_storage | - |
| Real-time | Ably Flutter | - |
| Push | FCM via Ably | - |

### Layer Structure

```
lib/
├── core/           # Constants, theme, network, utils, errors
├── data/           # Models (Freezed), datasources, repository implementations, mappers
├── domain/         # Entities (Equatable), repository interfaces
├── presentation/   # Providers (Riverpod), screens, widgets
└── router/         # GoRouter configuration
```

### Data Flow Pattern

```
API (JSON) → Freezed Model → Mapper Extension → Equatable Entity → Riverpod Provider → UI
```

### Key Files Reference

| File | Purpose |
|------|---------|
| `lib/core/network/api_client.dart` | HTTP client with error handling |
| `lib/core/network/api_interceptors.dart` | Auth injection, 403 handling |
| `lib/core/constants/permission_constants.dart` | Access levels, page permissions |
| `lib/presentation/providers/providers.dart` | Provider definitions, DI |
| `lib/router/app_router.dart` | Route definitions, auth guards |

---

## 2. Business Domain

### Permission System

**Access Levels** (Lower value = Higher privilege):

| Level | Value | Capabilities |
|-------|-------|--------------|
| Owner | 1 | Full access + permission configuration |
| Manager | 2 | Task list editing, backstock management |
| Shift Lead | 3 | Performance metrics, shift notes |
| Employee | 4 | Basic queue and task access |

**Permission Check Logic**:
```dart
canAccess = user.accessLevel.value <= requiredLevel.value
```

**Default Page Permissions**:
- Employee: Dashboard, Store Detail, Buy Queue, Completed Buys, Today's Tasks
- Shift Lead: + Buyer Stats, Store Metrics, Shift Notes
- Manager: + Edit Task List, Backstock Admin
- Owner: Settings, Permission Settings

### Core Domain Entities

| Entity | Purpose | Key Properties |
|--------|---------|----------------|
| Store | Dashboard store with metrics | typeNum, storeName, queueCount, goals |
| StoreDetail | Detailed store view | transaction counts, timing metrics |
| QueueItem | Active buyer in queue | customerName, containers, waitTime |
| CompletedBuy | Finished transaction | totals, timestamps, avgTimePerContainer |
| BuyerStats | Buyer performance | metrics, rankings |
| WorkbookNote | Announcements | reactions, comments, visibility dates |
| Task | Task definition | recurrence, priority, group |
| WorkbookTaskItem | Daily task instance | status, completedBy, carryover |
| TodayPerformance | KPI metrics | sales, avgTrans, tradePercent, labor |

### State Machines

**Queue Item States**:
```
Not Started (processed=0) → In Progress (0 < processed < total) → Completed (processed >= total)
```

**Task Status**:
```
NotStarted (0) → InProgress (1) → Completed (2)
```

### Critical Business Rules

1. **Task Carryover**: Incomplete tasks from earlier lists carry forward (highlighted red)
2. **Note Visibility**: `startDate <= now < endDate` determines active notes
3. **Progress Clamping**: Progress bars clamped 0.0-1.0; percentages unclamped
4. **Store Type Normalization**: PC80000 → PC00 for URL construction
5. **Auth Error Caching**: Dashboard caches auth errors for 30 seconds

---

## 3. API Integration

### Base Configuration

| Environment | URL |
|-------------|-----|
| Development | `https://try.buyerkiosk.com/api/` |
| Production | `https://buyerkiosk.com/api/` |

**Request Format**:
- Method: POST (all endpoints)
- Content-Type: application/x-www-form-urlencoded
- Authentication: `APIKey` parameter in POST body
- Timeout: 30 seconds

### Endpoint Categories

| Category | Count | Examples |
|----------|-------|----------|
| Authentication | 1 | /mobile/verify |
| Dashboard & Store | 2 | /mobile/dashboard, /mobile/storePage/:typeNum |
| Queue Management | 3 | currentQueue, completedBuys, buyerStats |
| Workbook Notes | 9 | CRUD + reactions + comments |
| Task Management | 8 | Tasks CRUD + Groups CRUD |
| Daily Tasks | 6 | lists, active, status, comments |
| Performance | 1 | todayPerformance |
| Backstock | 20+ | Events, bins, reports, analytics |

### Error Handling

| Status | Exception Type | App Behavior |
|--------|---------------|--------------|
| 401/403 | AuthException | Clear credentials, redirect to install |
| 400 | ServerException | Show validation error |
| 5xx | ServerException | Retry with exponential backoff |
| Timeout | TimeoutException | Retry up to 3 times |
| Connection | NetworkException | Show connectivity error |

### Real-time Integration (Ably)

**Channel Structure**:
- Store: `typeNum.toLowerCase()` (e.g., "pc00")
- User: `user:{userId}` (e.g., "user:123")

**Event Types**:
| Event | Provider Refresh |
|-------|------------------|
| workbook:task:complete | todayTasksProvider |
| workbook:note:create/update/delete | workbookNotesProvider |
| workbook:kpi:refresh | todayPerformanceProvider |

### Push Notifications

**Types**: note:comment, note:mention, task:assigned, task:reminder, queue:new_buy, kpi:alert

**Architecture**: Backend → Ably → FCM → Device

---

## 4. Testing Gap Analysis

### Current State

| Metric | Value |
|--------|-------|
| Test Files | 1 (smoke test only) |
| Test Cases | 1 |
| Coverage | ~0% |
| Mocktail | Configured but unused |

### Critical Untested Areas

**High Priority**:
1. JSON parsing helpers (`_parseDouble`, `_parseInt`)
2. Permission system (`AccessLevel.canAccess`)
3. Auth interceptor (APIKey injection, 403 handling)
4. Entity computed properties (progress, visibility)
5. Dashboard provider (auth error caching)

**Medium Priority**:
1. Model mappers (currency parsing, fallbacks)
2. Repository error handling
3. Family provider parameter equality
4. Error display widget

### Recommended Test Structure

```
test/
├── core/
│   ├── network/
│   │   ├── api_client_test.dart
│   │   └── api_interceptors_test.dart
│   ├── constants/
│   │   └── permission_constants_test.dart
│   └── utils/
│       └── json_parsing_test.dart
├── data/
│   └── models/mappers/
│       ├── store_mapper_test.dart
│       └── today_performance_mapper_test.dart
├── domain/entities/
│   ├── store_test.dart
│   ├── workbook_note_test.dart
│   └── queue_item_test.dart
├── presentation/providers/
│   ├── dashboard_provider_test.dart
│   └── permission_provider_test.dart
└── integration_test/
    └── auth_flow_test.dart
```

### Coverage Goals

| Category | Current | 3 Month Target | 6 Month Target |
|----------|---------|----------------|----------------|
| Core | 0% | 80% | 90% |
| Data | 0% | 70% | 85% |
| Domain | 0% | 90% | 95% |
| Presentation | 0% | 60% | 80% |
| **Overall** | **0%** | **60%** | **75%** |

---

## 5. Identified Patterns

### State Management Patterns

1. **AsyncNotifier**: Base pattern for async operations
2. **Error Caching**: Dashboard caches auth errors 30s to prevent API spam
3. **Family Providers**: Per-store data with parameter equality
4. **Refresh Logic**: `state = AsyncValue.guard(() => ...)`

### Data Layer Patterns

1. **Mapper Extensions**: `StoreModelX.toEntity()` on Freezed models
2. **Currency Parsing**: Strip `$` and `,`, handle numbers-as-strings
3. **Fallback Fields**: Support legacy API field names
4. **Null Safety**: Default values for nullable API responses

### Error Handling Patterns

1. **Exception Hierarchy**: `AppException` → typed exceptions
2. **Error Display**: `ErrorDisplay.fromError()` factory
3. **Interceptor Handling**: DioException → typed exception conversion
4. **Retry Logic**: Exponential backoff for transient failures

### Navigation Patterns

1. **Auth Guards**: GoRouter redirect with auth state listening
2. **Permission Guards**: Check `canAccess(AppPage)` before route
3. **Helper Extensions**: `context.goToStoreDetail(typeNum)`
4. **Deep Linking**: Query parameters for optional data

---

## 6. Risk Assessment

### Technical Risks

| Risk | Severity | Mitigation |
|------|----------|------------|
| Zero test coverage | **High** | Implement testing strategy immediately |
| Auth error handling | Medium | Add comprehensive interceptor tests |
| JSON parsing edge cases | Medium | Add parsing helper unit tests |
| Permission bypass in debug | Low | Add release-only permission tests |

### Business Logic Risks

| Risk | Severity | Mitigation |
|------|----------|------------|
| Division by zero | Medium | Already guarded, add tests |
| Carryover logic errors | Medium | Add comprehensive entity tests |
| Permission hierarchy bugs | High | Add permission constant tests |
| Date visibility errors | Medium | Add note/task visibility tests |

---

## 7. Recommendations

### Immediate Actions (Week 1)

1. **Create test infrastructure**
   - Set up test directory structure
   - Create mock utilities and fixtures
   - Configure CI/CD test pipeline

2. **Implement priority tests**
   - JSON parsing helpers
   - Permission constants
   - Entity computed properties

### Short-term (Month 1)

3. **Core layer coverage**
   - API client error handling
   - Auth interceptor logic
   - Repository error propagation

4. **Provider testing**
   - Dashboard provider with error caching
   - Permission provider state management
   - Auth provider flow

### Medium-term (Quarter 1)

5. **Integration tests**
   - Auth flow end-to-end
   - Dashboard load and refresh
   - Store detail navigation

6. **CI/CD enhancement**
   - Coverage reporting
   - Pre-commit hooks
   - PR coverage requirements

---

## 8. Documentation Created

| Document | Location | Description |
|----------|----------|-------------|
| Business Rules | `docs/domain/business-rules.md` | Permission system, queues, tasks, notes |
| Architecture Patterns | `docs/patterns/architecture-patterns.md` | Clean architecture, Riverpod, error handling |
| API Contracts | `docs/interfaces/api-contracts.md` | 40+ endpoints, Ably, push notifications |
| Testing Strategy | `docs/patterns/testing-strategy.md` | Coverage gaps, priorities, test examples |
| **This Document** | `docs/ANALYSIS_FINDINGS.md` | Consolidated findings for spec creation |

---

## 9. Specification Opportunities

Based on this analysis, the following specifications could be created:

### Feature Specifications

1. **S001: Implement Test Suite Foundation**
   - JSON parsing tests
   - Permission system tests
   - Entity computed property tests

2. **S002: Add Provider Test Coverage**
   - Dashboard provider tests
   - Permission provider tests
   - Auth provider tests

3. **S003: Create Integration Test Suite**
   - Auth flow tests
   - Dashboard flow tests
   - Store detail flow tests

### Technical Specifications

4. **T001: Standardize Error Handling**
   - Consolidate exception types
   - Add error logging
   - Improve error messages

5. **T002: Extract Shared Utilities**
   - JSON parsing to utils
   - Date formatting helpers
   - Currency formatting helpers

6. **T003: CI/CD Test Pipeline**
   - GitHub Actions workflow
   - Coverage reporting
   - PR quality gates

---

## Appendix: Key File Locations

### Core Layer
- `lib/core/network/api_client.dart`
- `lib/core/network/api_interceptors.dart`
- `lib/core/constants/api_constants.dart`
- `lib/core/constants/permission_constants.dart`
- `lib/core/errors/exceptions.dart`
- `lib/core/theme/app_theme.dart`

### Data Layer
- `lib/data/models/store_model.dart`
- `lib/data/models/mappers/store_mapper.dart`
- `lib/data/repositories/dashboard_repository_impl.dart`
- `lib/data/datasources/local/secure_storage_datasource.dart`

### Domain Layer
- `lib/domain/entities/store.dart`
- `lib/domain/entities/workbook_note.dart`
- `lib/domain/entities/workbook_task_list.dart`
- `lib/domain/repositories/dashboard_repository.dart`

### Presentation Layer
- `lib/presentation/providers/providers.dart`
- `lib/presentation/providers/dashboard_provider.dart`
- `lib/presentation/providers/permission_provider.dart`
- `lib/presentation/providers/ably_provider.dart`
- `lib/presentation/widgets/common/error_widget.dart`

### Router
- `lib/router/app_router.dart`

---

*This analysis was conducted using The Startup framework with parallel specialist agents for business, technical, integration, and testing analysis.*
