# KROW Workforce Platform - Project Onboarding Master Document

> **Version:** 1.1
> **Last Updated:** 2026-01-22
> **Purpose:** Source of Truth for Team Onboarding & Sprint Planning

---

## Table of Contents

1. [Project Vision & Business Value](#1-project-vision--business-value)
2. [System Architecture (GCP Migration)](#2-system-architecture-gcp-migration)
3. [Core Domain Logic](#3-core-domain-logic)
4. [Feature Gap Analysis](#4-feature-gap-analysis)
5. [Data Connect & Development Strategy](#5-data-connect--development-strategy)
6. [Definition of Done (DoD)](#6-definition-of-done-dod)

---

## 1. Project Vision & Business Value

### 1.1 What is KROW?

KROW is a **workforce management platform** that connects businesses (clients) with temporary/gig workers (staff) for event-based staffing needs. The platform handles the complete lifecycle from job posting to payment processing.

### 1.2 The Problem We Solve

| Stakeholder | Pain Point | KROW Solution |
|-------------|------------|---------------|
| **Businesses** | Finding qualified temp workers is time-consuming and unreliable | Instant access to pre-verified workers with ratings and certifications |
| **Workers** | Inconsistent gig opportunities, delayed payments, opaque earnings | Centralized shift discovery, real-time earnings tracking, transparent payment |
| **Administrators** | Manual coordination between clients and workers, paper-based time tracking | Automated assignment, QR/NFC clock-in, digital invoicing |

### 1.3 Core Value Proposition

```
KROW = Uber for Event Staffing
```

- **For Clients:** Post events, define shifts, get matched workers, track time, pay invoices
- **For Staff:** Browse shifts, accept gigs, clock in/out, track earnings, get paid
- **For Admins:** Manage workforce, verify profiles, resolve disputes, generate reports

### 1.4 Business Model

1. **Service Fees:** Markup on worker hourly rates (configurable per business)
2. **Premium Add-ons:** Optional services (uniforms, equipment, expedited matching)
3. **Enterprise Contracts:** Long-term staffing agreements with volume discounts

### 1.5 Strategic Objective

> **Mission:** Achieve complete technical independence by consolidating the KROW platform onto a single, robust, and maintainable ecosystem: **Firebase & Google Cloud**.

**Guiding Principles:**

1. **Velocity & Focus:** Maximize productivity with Firebase Data Connect and generated SDKs
2. **Unified Backend:** Single backend (Data Connect) powers all applications (Web, iOS, Android)
3. **Scalability & Low Overhead:** Managed services minimize operational burden
4. **Data Ownership:** Full control over PostgreSQL database for complex reporting
5. **Base44 as Design Accelerator:** Treat Base44 as a prototyping tool, not a system to migrate
6. **Automation as Force Multiplier:** Automate via Makefile and CI/CD pipelines

---

## 2. System Architecture (GCP Migration)

### 2.1 Migration Overview

```
LEGACY (Digital Ocean)          ──────────►          NEW (Google Cloud Platform)
├── PHP/Laravel Backend                              ├── Firebase Data Connect (GraphQL)
├── Laravel Nova Admin                               ├── Cloud Functions (Business Logic)
├── GraphQL (Lighthouse)                             ├── Cloud Run (Heavy Compute)
├── PostgreSQL (Self-managed)     ──────────►        ├── Cloud SQL (Managed PostgreSQL)
├── Digital Ocean Spaces          ──────────►        ├── Cloud Storage
└── Firebase Auth + FCM           ──────────►        └── Firebase Auth + FCM (unchanged)
```

### 2.2 New Architecture Diagram

```mermaid
graph TB
    subgraph Clients["Client Applications"]
        direction LR
        Mobile["Flutter Apps<br/>(Client + Staff)"]
        Web["Vite/React<br/>(Business + Admin)"]
    end

    subgraph Firebase["Firebase Services"]
        direction LR
        Auth["Firebase Auth + FCM"]
        DataConnect["Firebase Data Connect<br/>GraphQL API + Generated SDKs"]
    end

    subgraph Backend["Backend Services"]
        direction LR
        CloudRun["Cloud Run"]
        CloudFunctions["Cloud Functions"]
    end

    subgraph AI["AI Services"]
        VertexAI["Vertex AI / Gemini"]
    end

    subgraph Data["Data Layer"]
        direction LR
        CloudSQL["Cloud SQL<br/>(PostgreSQL)"]
        Storage["Cloud Storage"]
    end

    subgraph Security["Security & Compliance"]
        direction LR
        SecServices["Cloud IAM | Monitoring | Secret Manager"]
        Compliance["GDPR Ready | SOC 2 Type II | HIPAA Eligible"]
    end

    Mobile -->|"GraphQL SDK"| DataConnect
    Web -->|"GraphQL SDK"| DataConnect
    Mobile -.-> Auth
    Web -.-> Auth

    Mobile -->|"HTTP/REST"| CloudRun
    Web -->|"HTTP/REST"| CloudRun
    CloudFunctions -.->|"Events"| CloudRun

    DataConnect --> CloudSQL
    CloudRun --> CloudSQL
    CloudFunctions --> CloudSQL
    CloudRun --> Storage

    CloudRun --> VertexAI
    CloudFunctions --> VertexAI
```

### 2.3 Technology Stack Comparison

| Component | Legacy (Current) | New (Target) |
|-----------|-----------------|--------------|
| **Backend Framework** | PHP/Laravel | Firebase Data Connect + Cloud Functions |
| **API Layer** | GraphQL (Lighthouse) | Firebase Data Connect (GraphQL) |
| **Admin Panel** | Laravel Nova | Custom React Admin (or Firebase Extension) |
| **Database** | PostgreSQL (DO Droplet) | Cloud SQL (Managed PostgreSQL) |
| **File Storage** | Digital Ocean Spaces | Cloud Storage |
| **Authentication** | Firebase Auth | Firebase Auth (unchanged) |
| **Notifications** | FCM | FCM (unchanged) |
| **Mobile Apps** | Flutter | Flutter (code restructure with Melos) |
| **Web App** | Inertia.js + Vue | Vite + React |
| **AI/ML** | None | Vertex AI / Gemini |
| **Hosting** | Digital Ocean | Firebase Hosting + Cloud Run |

### 2.4 Key Architecture Decisions

1. **Firebase Data Connect as Primary API:**
   - Auto-generates type-safe SDKs for all clients
   - Eliminates API versioning headaches
   - Direct PostgreSQL access with GraphQL abstraction

2. **Cloud Functions for Business Logic:**
   - Email sending, AI invocations, file processing
   - Event-driven architecture for async operations
   - Clean separation from data layer

3. **PostgreSQL Retention:**
   - Full data ownership and portability
   - Complex queries and reporting capabilities
   - Industry-standard for enterprise requirements

4. **Monorepo Structure:**
   ```
   krow-workforce-web/
   ├── apps/
   │   ├── web-dashboard/     # Vite + React
   │   ├── mobile/
   |   |  ├── apps/  
   |   |  │   ├── client/       # Flutter (business app)
   |   |  │   └── staff/       # Flutter (staff app)
   ├── backend/
   │   ├── dataconnect/       # Firebase Data Connect schemas
   │   └── functions/         # Cloud Functions
   ├── firebase/              # Firebase config
   ├── internal/
   │   └── launchpad/         # Internal tools & prototypes
   └── docs/                  # Documentation
   ```

---

## 3. Core Domain Logic

### 3.1 Domain Entities Overview

The KROW platform has **49 domain entities** organized into 8 logical groups:

```
┌────────────────────────────────────────────────────────────────────┐
│                        KROW DOMAIN MODEL                           │
├────────────────────────────────────────────────────────────────────┤
│                                                                    │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐             │
│  │   USERS &   │    │  BUSINESS & │    │  EVENTS &   │             │
│  │ MEMBERSHIP  │    │ ORGANIZATION│    │   SHIFTS    │             │
│  ├─────────────┤    ├─────────────┤    ├─────────────┤             │
│  │ User        │    │ Business    │    │ Event       │             │
│  │ Staff       │    │ BusinessSet │    │ EventShift  │             │
│  │ Membership  │    │ Hub         │    │ Position    │             │
│  │ BizMember   │    │ HubDept     │    │ Assignment  │             │
│  │ HubMember   │    │ BizContract │    │ WorkSession │             │
│  └─────────────┘    └─────────────┘    └─────────────┘             │
│                                                                    │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐             │
│  │  SKILLS &   │    │  FINANCIAL  │    │  RATINGS &  │             │
│  │   CERTS     │    │   PAYROLL   │    │  PENALTIES  │             │
│  ├─────────────┤    ├─────────────┤    ├─────────────┤             │
│  │ Skill       │    │ Invoice     │    │ StaffRating │             │
│  │ SkillCat    │    │ InvoiceItem │    │ PenaltyLog  │             │
│  │ StaffSkill  │    │ InvDecline  │    │ BizStaffPref│             │
│  │ Certificate │    │ StaffPayment│    │             │             │
│  │ SkillKit    │    │             │    │             │             │
│  └─────────────┘    └─────────────┘    └─────────────┘             │
│                                                                    │
│  ┌─────────────┐    ┌─────────────┐                                │
│  │   STAFF     │    │   SUPPORT   │                                │
│  │   PROFILE   │    │    CONFIG   │                                │
│  ├─────────────┤    ├─────────────┤                                │
│  │ EmergencyC  │    │ Addon       │                                │
│  │ BankAccount │    │ Tag         │                                │
│  │ Accessibl   │    │ Media       │                                │
│  │ Schedule    │    │ WorkingArea │                                │
│  └─────────────┘    └─────────────┘                                │
│                                                                    │
└────────────────────────────────────────────────────────────────────┘
```

### 3.2 Key Entity Definitions

#### User & Authentication

| Entity | Description | Key Fields |
|--------|-------------|------------|
| **User** | Base auth entity (Firebase) | `id`, `email`, `phone`, `role` |
| **Staff** | Worker profile | `auth_provider_id`, `name`, `email`, `phone`, `status`, `address`, `avatar`, `live_photo` |
| **Membership** | Polymorphic org membership | `user_id`, `memberable_id`, `memberable_type`, `role` |

**Staff Status Flow:**
```
registered → pending → completed_profile → verified → [active | blocked | inactive]
```

#### Business & Organization

| Entity | Description | Key Fields |
|--------|-------------|------------|
| **Business** | Client company | `name`, `registration`, `status`, `avatar` |
| **BusinessSetting** | Payroll config | `prefix`, `overtime`, `clock_in`, `clock_out` |
| **Hub** | Branch location | `business_id`, `name`, `address`, `status` |
| **HubDepartment** | Dept within hub | `hub_id`, `name` |

#### Events & Shifts

| Entity | Description | Key Fields |
|--------|-------------|------------|
| **Event** | Job posting | `business_id`, `hub_id`, `name`, `date`, `status`, `contract_type` |
| **EventShift** | Work session | `event_id`, `name`, `address` |
| **EventShiftPosition** | Job opening | `shift_id`, `skill_id`, `count`, `rate`, `start_time`, `end_time`, `break` |
| **EventShiftPositionStaff** | Assignment | `staff_id`, `position_id`, `status`, `clock_in`, `clock_out` |

**Event Status Flow:**
```
draft → pending → assigned → confirmed → active → finished → completed → closed
                                                           ↘ under_review
```

**Assignment Status Flow:**
```
assigned → confirmed → ongoing → completed
         ↘ decline_by_staff → [penalty logged]
         ↘ canceled_by_staff → [penalty logged]
         ↘ no_showed → [penalty logged]
```

#### Skills & Certifications

| Entity | Description | Key Fields |
|--------|-------------|------------|
| **Skill** | Job category | `category_id`, `name`, `price` |
| **StaffSkill** | Worker qualification | `staff_id`, `skill_id`, `level`, `experience`, `status` |
| **Certificate** | Required credential | `name`, `required` |
| **SkillKit** | Uniform/equipment req | `skill_id`, `name`, `is_required`, `type` |

**Skill Levels:** `beginner` | `skilled` | `professional`

#### Financial & Payroll

| Entity | Description | Key Fields |
|--------|-------------|------------|
| **Invoice** | Business bill | `event_id`, `business_id`, `status`, `total`, `work_amount`, `addons_amount` |
| **InvoiceItem** | Line item | `invoice_id`, `staff_id`, `work_hours`, `rate`, `amounts` |
| **StaffPayment** | Worker payout | `staff_id`, `assignment_id`, `amount`, `status`, `paid_at` |

**Invoice Status Flow:**
```
open → disputed → resolved → verified → paid/reconciled
     ↘ overdue
```

### 3.3 Core Business Workflows

#### Workflow 1: Event Lifecycle

```mermaid
sequenceDiagram
    participant Client as Client App
    participant API as Backend API
    participant Admin as Admin
    participant Staff as Staff App

    Note over Client,API: 1. Event Creation
    Client->>API: Create Event with Shifts & Positions
    API-->>Client: Event Created (Draft)
    Client->>API: Publish Event
    API-->>Client: Event Published

    opt 2. Staff Assignment (Optional)
        Note over Admin,API: Optional Staff Assignment
        Admin->>API: Assign Staff to Shift
        API-->>Admin: Assignment Confirmed
        API->>Staff: Notification: New Shift
    end

    Note over Staff,API: 3. Shift Acceptance
    Staff->>API: Accept Shift
    API-->>Staff: Shift Confirmed

    Note over Client,Staff: 4. Day of Event
    Client->>Client: Generate QR Code
    Staff->>Staff: Scan QR Code
    Staff->>API: Clock In
    Staff->>API: Clock Out

    Note over Client,API: 5. Post-Event
    Client->>API: Rate Staff
    API->>API: Generate Invoice
    Client->>API: Approve Invoice

```

#### Workflow 2: Staff Onboarding

```
1. Registration (Firebase Phone Auth)
   ├── Create Staff record (status: registered)
   └── Profile created with auth_provider_id

2. Profile Completion
   ├── Personal info (name, email, address)
   ├── Avatar upload
   ├── Emergency contacts
   └── Bank account details

3. Skills Declaration
   ├── Add skills with level/experience
   └── Status: pending → verified (admin)

4. Certification Upload
   ├── Upload certificates
   └── Status: pending → verified (admin)

5. Equipment Confirmation
   ├── Confirm uniforms per skill
   ├── Confirm equipment per skill
   └── Upload photos as proof

6. Profile Submission
   ├── Complete verification checklist
   └── Status: completed_profile → verified
```

But there is an ambiguity in the workflow. In the legacy application, worker verification happens at the beginning, and all workers are fully verified before they can access the application. In the new version, however, workers are allowed to access the application without being fully verified. This creates ambiguity in the following areas:
- Definition of worker verification in the new system
  - Does verification mean the worker has fully completed their profile, or can a worker be considered verified with an incomplete profile?
- Visibility of shifts for unverified workers
  - Should unverified workers be able to view the shifts page?

#### Workflow 3: Payroll Calculation

```
Work Hours = (clock_out - clock_in) - break_duration

Overtime Rules:
├── Regular Hours (1x):     hours <= 8
├── Overtime Hours (1.5x):  8 < hours <= 10
└── Doubletime Hours (2x):  hours > 10

Payment = (regular_hours × rate × 1.0)
        + (overtime_hours × rate × 1.5)
        + (doubletime_hours × rate × 2.0)
        + addons_amount
```

### 3.4 API Structure (Legacy Reference)

#### Client (Business) API

**Queries:**
- `client_hubs` - Get accessible hubs
- `client_events(status)` - Paginated events
- `client_invoices(status)` - Paginated invoices
- `client_business_skills` - Business skill catalog

**Mutations:**
- `client_create_event(input)` - Create event
- `client_publish_event(id)` - Publish event
- `track_client_clockin/clockout` - Manual time tracking
- `rate_client_staff(input)` - Rate worker

#### Staff (Worker) API

**Queries:**
- `me` - Current staff profile
- `staff_shifts(status)` - Paginated shifts
- `staff_payments(status)` - Paginated payments
- `verification_check_list` - Onboarding progress

**Mutations:**
- `accept_shift(position_id)` - Accept shift
- `decline_shift(position_id, reason)` - Decline with penalty
- `track_staff_clockin/clockout` - Time tracking
- `update_staff_*` - Profile updates

---

## 4. Feature Gap Analysis

### 4.1 Legacy Feature Inventory

#### Client Mobile App (Flutter)
| Feature | Files | Status | Priority |
|---------|-------|--------|----------|
| Event Creation & Management | 40 | Production | P0 |
| Event List & Details | 21 | Production | P0 |
| Invoice Management | 29 | Production | P0 |
| Hub Management | 11 | Production | P1 |
| Staff Assignment View | 4 | Production | P0 |
| Manual Clock In/Out | 9 | Production | P0 |
| Staff Rating | 9 | Production | P1 |
| Notifications | 12 | Production | P1 |
| Profile Management | 11 | Production | P2 |

**Total:** 272 Dart files, 24,690 LOC, 12 features

#### Staff Mobile App (Flutter)
| Feature | Files | Status | Priority |
|---------|-------|--------|----------|
| Authentication (Phone) | 9 | Production | P0 |
| Shift Management | 70 | Production | P0 |
| Earnings & Payments | 32 | Production | P0 |
| Profile (Complete) | 211 | Production | P0 |
| Check List (Verification) | 11 | Production | P1 |
| QR Scanner | 1 | Production | P0 |
| Support | 2 | Production | P2 |

**Total:** 430 Dart files, 34,676 LOC, 10 features

#### Backend (PHP/Laravel)
| Component | Count | Status |
|-----------|-------|--------|
| Eloquent Models | 49 | Production |
| Actions | 19 | Production |
| GraphQL Queries | 30+ | Production |
| GraphQL Mutations | 40+ | Production |
| Nova Resources | 20+ | Production |

**Total:** 353 PHP files, 28,675 LOC

### 4.2 Web Prototype Analysis (Source Code)

**Location:** `internal/launchpad/prototypes-src/web/`

The web prototype is a **fully functional React application** with rich business logic:

#### 4.2.1 Feature Routes (38 Routes)

| Category | Route | Component | Roles |
|----------|-------|-----------|-------|
| **Overview** | `/dashboard/admin` | AdminDashboard | Admin |
| | `/dashboard/client` | ClientDashboard | Client |
| | `/dashboard/vendor` | VendorDashboard | Vendor |
| | `/savings` | SavingsEngine | All |
| | `/performance` | VendorPerformance | Vendor, Admin |
| **Operations** | `/orders` | OrderList | Admin |
| | `/orders/client` | ClientOrderList | Client |
| | `/orders/vendor` | VendorOrderList | Vendor |
| | `/orders/:id` | OrderDetail | All |
| | `/orders/:id/edit` | EditOrder | All |
| | `/schedule` | Schedule | All |
| | `/availability` | StaffAvailability | All |
| | `/tasks` | TaskBoard | All |
| **Marketplace** | `/marketplace` | VendorMarketplace | Client, Admin |
| | `/marketplace/compare` | CompareRates | Client, Admin |
| **Workforce** | `/staff` | StaffList | All |
| | `/staff/add` | AddStaff | All |
| | `/staff/:id/edit` | EditStaff | All |
| | `/onboarding` | OnboardingFlow | All |
| | `/teams` | TeamList | All |
| | `/teams/create` | CreateTeam | All |
| | `/teams/:id` | TeamDetail | All |
| | `/compliance` | ComplianceDashboard | Vendor, Admin |
| | `/documents` | DocumentVault | Vendor, Admin |
| **Finance** | `/invoices` | InvoiceList | All |
| | `/invoices/new` | InvoiceEditor | All |
| | `/invoices/:id` | InvoiceDetail | All |
| **Business** | `/clients` | ClientList | Vendor, Admin |
| | `/clients/add` | AddClient | Vendor, Admin |
| | `/clients/:id/edit` | EditClient | Vendor, Admin |
| | `/rates` | ServiceRates | Vendor, Admin |
| **Analytics** | `/reports` | ReportsDashboard | All |
| | `/activity` | ActivityLog | Vendor, Admin |
| **Communication** | `/messages` | MessageCenter | All |
| | `/tutorials` | TutorialList | Client, Admin |
| **Support** | `/support` | SupportCenter | Client, Admin |

#### 4.2.2 Business Logic Implemented (Client-Side)

**1. Overtime Calculator** (`logic/OvertimeCalculator.ts`)
```typescript
// State-specific OT/DT rules (California vs Federal)
STATE_RULES = {
  CA: { dailyOT: 8, dailyDT: 12, weeklyOT: 40, seventhDayDT: true },
  DEFAULT: { dailyOT: null, weeklyOT: 40 }
}
// Returns: status (GREEN/AMBER/RED), otHours, dtHours, costImpact
```

**2. Smart Assignment Engine** (`logic/SmartAssignmentEngine.ts`)
```typescript
// Multi-factor scoring algorithm
Factors: Skill Match, Reliability Score, Vendor Priority,
         Fatigue Level, Compliance, Proximity, Cost Optimization
// Features: Double-booking detection, Auto-fill shifts
```

**3. Conflict Detection** (`logic/ConflictDetection.ts`)
```typescript
// Detects: Staff overlap, Venue overlap, Buffer time violations
// Supports: Multi-day events, Time buffers, Severity levels
```

**4. Order Status Utils** (`logic/OrderStatusUtils.ts`)
- Status color mapping
- Status transition rules

**5. Double Booking Validator** (`logic/DoubleBookingValidator.ts`)
- Validates staff assignments across events

#### 4.2.3 TypeScript Data Models (30+ Types)

| Type | Fields | Maps to Legacy |
|------|--------|----------------|
| `User` | id, email, role, user_role, preferred_vendor_id, dashboard_layout | User + BusinessMember |
| `Staff` | id, employee_name, position, rating, reliability_score, vendor_id | Staff |
| `Event` | id, event_name, date, status, shifts, assigned_staff, is_rapid, buffer_time | Event |
| `Shift` | roles[] | EventShift |
| `ShiftRole` | role, count, start_time, end_time, bill_rate, pay_rate | EventShiftPosition |
| `StaffAssignment` | staff_id, staff_name, role | EventShiftPositionStaff |
| `Invoice` | id, invoice_number, status, amount, roles[], disputed_items | Invoice + InvoiceItem |
| `Business` | id, business_name, hubs[], favorite_staff, blocked_staff, erp_* | Business |
| `Vendor` | id, legal_name, region, approval_status, markup, fee, rates[] | NEW |
| `VendorRate` | id, vendor_name, role_name, client_rate, employee_wage, markup_% | NEW |
| `Team` | id, team_name, owner_id, members, hubs, favorite_staff, blocked_staff | Business context |
| `TeamMember` | id, team_id, member_name, email, role, department, hub | Membership |
| `TeamHub` | id, team_id, hub_name, departments[] | Hub + HubDepartment |
| `Task` | id, task_name, priority, status, assigned_members, files | NEW |
| `Certification` | id, employee_id, certification_type, status, expiry_date | StaffCertificate |
| `WorkerAvailability` | staff_id, availability_status, need_work_index, utilization_% | NEW |
| `Conversation` | id, subject, participants[], last_message | NEW |
| `ActivityLog` | id, title, description, activity_type, icon_type | ActivityLog |

### 4.3 Feature Gap Matrix (Updated)

| Feature Area | Legacy Mobile | Web Prototype | Gap Status |
|--------------|---------------|---------------|------------|
| **Auth & Onboarding** | Full (Phone) | Basic (Email) | Merge approaches |
| **Event/Order CRUD** | Full | Full + Enhanced | Prototype ahead |
| **Shift Management** | Full | Full + Scheduler | Prototype ahead |
| **Time Tracking (QR/NFC)** | Full | None | Legacy only |
| **Invoice Generation** | Full | Full + Templates | Prototype ahead |
| **Payroll Calculation** | Backend only | **Client-side OT calc** | Port to backend |
| **Staff Profile** | Full (211 files) | Basic | Legacy ahead |
| **Skills & Certs** | Full | Compliance Dashboard | Legacy ahead |
| **Ratings & Penalties** | Full | None explicit | Legacy only |
| **Notifications** | Full | None | Legacy only |
| **Admin Dashboard** | Nova | **3 Role Dashboards** | Prototype ahead |
| **Vendor Management** | None | **Full Marketplace** | Prototype only |
| **Smart Assignment** | None | **AI Engine** | Prototype only |
| **Conflict Detection** | None | **Full** | Prototype only |
| **Savings Engine** | None | **Full** | Prototype only |
| **Task Board** | None | **Full** | Prototype only |
| **Messaging** | None | **Full** | Prototype only |
| **Reports** | Basic | **Advanced Templates** | Prototype ahead |
| **Teams/Organizations** | Membership | **Full Team Mgmt** | Prototype ahead |
| **Worker Availability** | Schedule | **Predictive** | Prototype ahead |

### 4.4 NEW Features in Prototype (Not in Legacy)

These are **new capabilities** to be implemented:

1. **Savings Engine** - Cost optimization recommendations
2. **Vendor Marketplace** - Vendor discovery and comparison
3. **Smart Assignment Engine** - AI-powered worker matching
4. **Conflict Detection** - Staff/venue/buffer conflict alerts
5. **State-Specific OT Calculator** - California labor law compliance
6. **Task Board** - Project management within platform
7. **Rate Cards & Compare Rates** - Pricing transparency
8. **Worker Availability Prediction** - Utilization scoring
9. **Report Templates** - Scheduled, exportable reports
10. **ERP Integration Settings** - Enterprise system connectivity
11. **Multi-Dashboard by Role** - Admin/Client/Vendor views
12. **Messaging Center** - In-app communication

### 4.5 Legacy Features Missing in Prototype

These **must be ported** from legacy:

1. **Phone Authentication** - Firebase phone auth flow
2. **QR/NFC Clock In/Out** - Mobile time tracking
3. **Staff Profile Completion Wizard** - 9-step verification
4. **Skills & Skill Kits** - Uniform/equipment confirmation
5. **Certificate Upload & Verification** - Document management
6. **Penalty System** - Decline/cancel/no-show tracking
7. **Staff Rating by Business** - Performance reviews
8. **Payment Workflow** - Staff payout confirmation
9. **Emergency Contacts** - Worker safety info
10. **Bank Account Management** - Payout details
11. **Push Notifications** - FCM integration
12. **Geofencing** - Location-based clock validation

### 4.6 Migration Strategy

```
┌─────────────────────────────────────────────────────────────────┐
│                    FEATURE MIGRATION PRIORITY                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  P0 - MUST HAVE (Sprint 3-4)                                    │
│  ├── Auth (Phone + Email)                                       │
│  ├── Event/Order CRUD                                           │
│  ├── Staff Profile Basics                                       │
│  ├── Invoice List/Detail                                        │
│  └── Dashboard (by role)                                        │
│                                                                 │
│  P1 - SHOULD HAVE (Sprint 5-6)                                  │
│  ├── Clock In/Out (QR at minimum)                               │
│  ├── Smart Assignment                                           │
│  ├── Conflict Detection                                         │
│  ├── Staff Verification Workflow                                │
│  └── Notifications                                              │
│                                                                 │
│  P2 - NICE TO HAVE (Sprint 7+)                                  │
│  ├── Savings Engine                                             │
│  ├── Vendor Marketplace                                         │
│  ├── Advanced Reports                                           │
│  ├── Task Board                                                 │
│  └── Messaging                                                  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### 4.7 Mobile Prototype Analysis (Source Code)

#### 4.7.1 Mobile Client App (Flutter)

**Location:** `internal/launchpad/prototypes-src/mobile/apps/client/`

**Routes (22 screens):**

| Category | Route | Screen | Description |
|----------|-------|--------|-------------|
| **Auth** | `/client-get-started` | GetStarted | Welcome screen |
| | `/client-sign-in` | SignIn | Email/password login |
| | `/client-sign-up` | SignUp | Registration |
| **Orders** | `/create-order` | CreateOrder | Order type selector |
| | `/create-order/rapid` | **RapidOrderFlow** | **NEW: Voice-enabled URGENT orders** |
| | `/create-order/one-time` | OneTimeOrderFlow | Single event |
| | `/create-order/recurring` | RecurringOrderFlow | Repeating schedule |
| | `/create-order/permanent` | PermanentOrderFlow | Ongoing staffing |
| **Main Nav** | `/client-coverage` | Coverage | Staffing coverage dashboard |
| | `/client-billing` | Billing | Invoice management |
| | `/client-home` | Home | Main dashboard |
| | `/client-shifts` | Shifts | Active orders |
| | `/client-reports` | Reports | Analytics hub |
| **Reports** | `/daily-ops-report` | DailyOps | **NEW: Daily operations** |
| | `/spend-report` | Spend | Cost analysis |
| | `/forecast-report` | **Forecast** | **NEW: Predictive staffing** |
| | `/performance-report` | Performance | Vendor/staff metrics |
| | `/no-show-report` | NoShow | Attendance tracking |
| | `/coverage-report-detail` | CoverageDetail | Coverage analytics |
| **Other** | `/verify-worker-attire` | **VerifyAttire** | **NEW: Uniform check** |
| | `/client-hubs` | Hubs | Location management |
| | `/client-settings` | Settings | Preferences |

**Key NEW Features:**
- **RAPID Orders** - Voice-enabled urgent staffing requests ("Need 2 cooks ASAP")
- **4 Order Types** - One-time, Rapid, Recurring, Permanent
- **Forecast Reports** - Predictive staffing needs
- **Verify Worker Attire** - Photo verification of uniforms

---

#### 4.7.2 Mobile Staff App (Flutter)

**Location:** `internal/launchpad/prototypes-src/mobile/apps/staff/`

**Routes (35+ screens):**

| Category | Route | Screen | Description |
|----------|-------|--------|-------------|
| **Auth** | `/get-started` | GetStarted | Welcome |
| | `/phone-verification` | PhoneVerification | OTP flow |
| | `/profile-setup` | ProfileSetup | Initial setup |
| **Main Nav** | `/shifts` | Shifts | Available/assigned shifts |
| | `/payments` | Payments | Earnings overview |
| | `/worker-home` | Home | Dashboard |
| | `/clock-in` | **ClockIn** | **Swipe/NFC + GPS + Commute** |
| | `/worker-profile` | Profile | Settings hub |
| **Earnings** | `/earnings` | Earnings | Detailed breakdown |
| | `/early-pay` | **EarlyPay** | **NEW: Instant pay (5% fee)** |
| **Shifts** | `/shift-details/:id` | ShiftDetails | Shift info |
| | `/jobs` | Jobs | Job search |
| | `/availability` | Availability | Schedule preferences |
| | `/benefits` | Benefits | Perks info |
| **Profile/Onboarding** | `/personal-info` | PersonalInfo | Basic details |
| | `/emergency-contact` | EmergencyContact | Safety info |
| | `/experience` | Experience | Work history |
| | `/attire` | Attire | Uniform confirmation |
| **Profile/Compliance** | `/documents` | Documents | ID uploads |
| | `/certificates` | Certificates | Certifications |
| | `/tax-forms` | TaxForms | Tax documents hub |
| | `/taxforms/i9` | **FormI9** | **NEW: I-9 verification** |
| | `/taxforms/w4` | **FormW4** | **NEW: W-4 tax form** |
| **Profile/Finances** | `/bank-account` | BankAccount | Payout setup |
| | `/time-card` | TimeCard | Hours log |
| **Profile/Level Up** | `/krow-university` | **KrowUniversity** | **NEW: Training platform** |
| | `/trainings` | **Trainings** | **NEW: Skill courses** |
| | `/leaderboard` | **Leaderboard** | **NEW: Gamification** |
| **Profile/Support** | `/faqs` | FAQs | Help articles |
| | `/messages` | Messages | Support chat |
| | `/privacy` | Privacy | Settings |

**Key NEW Features:**

1. **Advanced Clock-In System:**
   - Swipe-to-check-in UI
   - NFC badge support
   - **Commute Tracker** (GPS-based ETA)
   - Lunch break modal
   - Geofencing validation

2. **Early Pay (Earned Wage Access):**
   - Request portion of earned wages early
   - 5% service fee
   - Enrollment flow with terms

3. **Gamification & Training:**
   - **KROW University** - Training courses
   - **Leaderboard** - Worker rankings
   - **Trainings** - Skill development

4. **Tax Compliance:**
   - **Form I-9** - Employment eligibility
   - **Form W-4** - Tax withholding

5. **Enhanced Profile:**
   - Time Card history
   - Documents vault
   - Certificate management

---

### 4.8 Complete Feature Comparison (All 3 Apps)

| Feature | Legacy Mobile | Web Prototype | Mobile Prototype |
|---------|--------------|---------------|------------------|
| **Auth - Phone** | ✅ | ❌ | ✅ |
| **Auth - Email** | ❌ | ✅ | ✅ |
| **Order Types** | 1 (basic) | 4 (one-time, rapid, recurring, permanent) | **4 types** |
| **RAPID Orders (Voice)** | ❌ | ❌ | **✅ NEW** |
| **Clock In - QR** | ✅ | ❌ | ❌ |
| **Clock In - Swipe** | ❌ | ❌ | **✅ NEW** |
| **Clock In - NFC** | ❌ | ❌ | **✅ NEW** |
| **Commute Tracker** | ❌ | ❌ | **✅ NEW** |
| **Early Pay** | ❌ | ❌ | **✅ NEW** |
| **KROW University** | ❌ | ❌ | **✅ NEW** |
| **Leaderboard** | ❌ | ❌ | **✅ NEW** |
| **Tax Forms (I-9, W-4)** | ❌ | ❌ | **✅ NEW** |
| **Forecast Reports** | ❌ | ❌ | **✅ NEW** |
| **Verify Attire** | ❌ | ❌ | **✅ NEW** |
| **Smart Assignment** | ❌ | **✅** | ❌ |
| **Conflict Detection** | ❌ | **✅** | ❌ |
| **Savings Engine** | ❌ | **✅** | ❌ |
| **Vendor Marketplace** | ❌ | **✅** | ❌ |
| **Staff Profile (complete)** | ✅ | Basic | Enhanced |
| **Penalty System** | ✅ | ❌ | ❌ |
| **Staff Rating** | ✅ | ❌ | ❌ |

### 4.9 Source Code Locations

| Component | Location | Tech |
|-----------|----------|------|
| Web Prototype Source | `internal/launchpad/prototypes-src/web/` | React + TypeScript |
| Mobile Client Prototype | `internal/launchpad/prototypes-src/mobile/client/` | Flutter + Dart |
| Mobile Worker Prototype | `internal/launchpad/prototypes-src/mobile/worker/` | Flutter + Dart |
| Legacy Client Mobile | `_legacy/apps/krow_client_context.md` | Flutter (context doc) |
| Legacy Worker (Legacy Staff) Mobile | `_legacy/apps/krow_staff_context.md` | Flutter (context doc) |
| Legacy Backend | `_legacy/apps/php_backend_context.md` | PHP/Laravel |
| New Backend | `backend/dataconnect/` | Firebase Data Connect |

---

## 5. Data Connect & Development Strategy

### 5.1 Feature-Driven Schema Evolution

> **Principle:** The Data Connect schema is **not** pre-designed. It evolves iteratively as features are implemented.

```
Feature Implementation Flow:
┌──────────────────┐     ┌──────────────────┐     ┌──────────────────┐
│   Pick Feature   │ ──► │  Define Schema   │ ──► │  Implement UI    │
│   from Sprint    │     │  Tables/Queries  │     │  with SDK        │
└──────────────────┘     └──────────────────┘     └──────────────────┘
         │                        │                        │
         │                        │                        │
         ▼                        ▼                        ▼
    No mocks!              Just enough               Generated SDK
    Real data              for feature               guarantees types
    from start
```

### 5.2 No Mock Data Policy

**Why no mocks?**
1. Data Connect generates type-safe SDKs automatically
2. Mocks create drift between expected and actual schemas
3. Real data surfaces integration issues early
4. Reduces "works on my machine" problems

**Instead of mocks:**
- Use Firebase emulator suite for local development
- Seed development database with realistic test data
- Write schema migrations as features are added

### 5.3 Sprint 3 Schema Strategy

For each feature in Sprint 3:

1. **Identify Data Requirements**
   - What entities does this feature need?
   - What fields are required vs optional?
   - What relationships exist?

2. **Write Schema Incrementally**
   ```gql
   # backend/dataconnect/schema/event.gql
   type Event @table {
     id: UUID! @default(expr: "uuidV4()")
     name: String!
     status: EventStatus!
     date: Date!
     business: Business! @relation
     hub: Hub @relation
     shifts: [EventShift!]! @relation
     createdAt: Timestamp! @default(expr: "request.time")
   }
   ```

3. **Define Queries/Mutations**
   ```gql
   # backend/dataconnect/queries/events.gql
   query ListEvents($status: EventStatus) @auth(level: USER) {
     events(where: { status: { eq: $status } }) {
       id, name, status, date
       business { name }
     }
   }
   ```

4. **Generate SDK & Implement UI**
   ```bash
   firebase dataconnect:sdk:generate
   ```

### 5.4 Development Environment Setup

```bash
# Prerequisites
node -v    # >= 20.x
pnpm -v    # latest
fvm use    # Flutter version management
firebase --version  # >= 13.x

# Setup
git clone <repo>
cd krow-workforce-web
pnpm install
firebase login
firebase use development

# Start development
make dev              # Start all services
make dev-web          # Web only
make dev-mobile       # Mobile emulators
make sync-prototypes  # Sync visual references
```

### 5.5 Recommended Sprint 3 Feature Order

Based on minimal dependencies:

1. **Authentication Flow** (depends: Firebase Auth only)
2. **Staff Profile Basics** (depends: Auth)
3. **Event List View** (depends: Auth, basic schema)
4. **Event Creation** (depends: Auth, Events schema)
5. **Shift Assignment** (depends: Events, Staff)
6. **Time Tracking** (depends: Assignments)
7. **Invoice Generation** (depends: Completed shifts)

---

## 6. Definition of Done (DoD)

### 6.1 Feature-Level DoD (MVP Phase)

A feature is **DONE** when:

- [ ] **Schema:** Data Connect schema defined and deployed
- [ ] **SDK:** Generated SDK integrated into app
- [ ] **UI:** All screens implemented per prototype design
- [ ] **Logic:** Business logic working correctly
- [ ] **Manual Testing:** Feature tested directly in the application (happy path + edge cases)
- [ ] **Security:** Auth rules validated
- [ ] **Accessibility:** Basic a11y compliance
- [ ] **Documentation:** API documented in schema comments
- [ ] **Review:** Code reviewed and approved

> **Note (MVP):** For rapid MVP delivery, we focus on manual/integration testing directly in applications rather than unit tests. Automated test coverage will be added post-MVP.

### 6.2 Sprint-Level DoD

A sprint is **DONE** when:

- [ ] All planned features meet Feature DoD
- [ ] No P0 bugs in staging environment
- [ ] Performance: <3s initial load, <500ms interactions
- [ ] Security audit passed (no critical vulnerabilities)
- [ ] Staging deployed and validated
- [ ] Demo-ready for stakeholders
- [ ] Documentation updated

### 6.3 Code Quality Standards

| Aspect | Standard |
|--------|----------|
| **Linting** | Zero ESLint/Dart analyzer errors |
| **Formatting** | Prettier (JS/TS), dart format |
| **Types** | Strict TypeScript, no `any` |
| **Commits** | Conventional commits format |
| **PRs** | Template completed, 1+ approval |
| **Testing (MVP)** | Manual testing in application |

### 6.4 Commit Message Format

```
<type>(<scope>): <subject>

[optional body]

[optional footer]
```

**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`

**Examples:**
```
feat(events): add event creation form
fix(auth): handle token expiration correctly
docs(readme): update setup instructions
```

### 6.5 Branch Strategy

```
main (production)
  └── dev (staging)
       └── feature/KROW-123-event-creation
       └── feature/KROW-124-shift-management
       └── fix/KROW-125-clock-in-bug
```

### 6.6 PR Checklist

```markdown
## PR Checklist
- [ ] Code follows project conventions
- [ ] Self-reviewed changes
- [ ] Feature manually tested in application
- [ ] Documentation updated if needed
- [ ] No console.log/print statements
- [ ] Sensitive data not hardcoded
- [ ] Tested on emulator/device
```

---

## Appendix A: Entity Relationship Summary

```
User (1) ─── (M) Membership ──┬── Business
                              ├── Hub
                              └── HubDepartment

Staff (1) ──┬── (M) StaffSkill ─── Skill ─── SkillCategory
            │         └── (M) StaffSkillKit ─── SkillKit
            ├── (M) StaffCertificate ─── Certificate
            ├── (1) StaffBankAccount
            ├── (1) StaffAccessibility
            ├── (M) StaffSchedule
            ├── (M) StaffEmergencyContact
            └── (M) EventShiftPositionStaff

Business (1) ──┬── (1) BusinessSetting
               ├── (1) BusinessContact
               ├── (M) BusinessContract
               ├── (M) Hub ──── (M) HubDepartment
               └── (M) Event ──── (M) EventShift ──── (M) EventShiftPosition
                          │
                          └── (M) Invoice ──── (M) InvoiceItem
```

---

## Appendix B: Status Enums Reference

### Event Status
`draft` → `pending` → `assigned` → `confirmed` → `active` → `finished` → `completed` → `closed`

### Assignment Status
`assigned` | `confirmed` | `ongoing` | `completed` | `canceled_by_staff` | `decline_by_staff` | `canceled_by_business` | `canceled_by_admin` | `requested_replace` | `no_showed`

### Staff Status
`registered` | `pending` | `verified` | `blocked` | `inactive` | `completed_profile`

### Invoice Status
`open` | `disputed` | `resolved` | `verified` | `overdue` | `reconciled` | `paid`

### Payment Status
`new` | `confirmed_by_admin` | `confirmed_by_staff` | `decline_by_staff` | `sent` | `paid` | `failed` | `canceled`

---

## Appendix C: Key Files Reference

| Purpose | Location |
|---------|----------|
| Vision document | `docs/00-vision.md` |
| Backend API spec (legacy) | `docs/01-backend-api-specification.md` |
| CI/CD config | `docs/02-codemagic-env-vars.md` |
| Contributing guide | `docs/03-contributing.md` |
| Prototype sync | `docs/04-sync-prototypes.md` |
| Legacy PHP context | `_legacy/apps/php_backend_context.md` |
| Legacy Client context | `_legacy/apps/krow_client_context.md` |
| Legacy Staff context | `_legacy/apps/krow_staff_context.md` |
| Architecture diagrams | `internal/launchpad/assets/diagrams/` |
| Data Connect schemas | `backend/dataconnect/` |

---

*This document is the source of truth for team onboarding. Update it as the project evolves.*
