Merge remote-tracking branch 'origin/dev' into codex/feat-architecture-lead-bootstrap

This commit is contained in:
zouantchaw
2026-02-26 09:45:09 -05:00
809 changed files with 44573 additions and 7915 deletions

View File

@@ -0,0 +1,152 @@
# Krow Platform: System Architecture Overview
## 1. Executive Summary: The Business Purpose
The **Krow Platform** is an end-to-end workforce management ecosystem designed to bridge the gap between businesses that need staff ("Clients") and the temporary workers who fill those roles ("Staff").
Traditionally, this process involves phone calls, paper timesheets, and manual payroll. Krow digitizes the entire lifecycle:
1. **Finding Work:** Clients post shifts instantly; workers claim them via mobile.
2. **Doing Work:** GPS-verified clock-ins and digital timesheets ensure accuracy.
3. **Managing Business:** A web dashboard provides analytics, billing, and compliance oversight.
The system's goal is to reduce administrative friction, ensure legal compliance, and optimize labor costs through automation and real-time data.
## 2. The Application Ecosystem
The platform consists of three distinct applications, each tailored to a specific user group:
### A. Client Mobile App (The "Requester")
* **User:** Business Owners, Venue Managers.
* **Role:** The demand generator. It allows clients to request staff on the fly, track who is arriving, and approve hours worked.
* **Key Value:** Speed and visibility. A manager can fill a sudden "no-show" gap in seconds from their phone.
### B. Staff Mobile App (The "Worker")
* **User:** Temporary Staff (Servers, Cooks, Bartenders).
* **Role:** The supply pool. It acts as their personal agency, handling job discovery, schedule management, and instant payouts.
* **Key Value:** Flexibility and financial security. Workers choose when they work and get paid faster.
### C. Krow Web Application (The "HQ")
* **User:** Administrators, HR, Finance, and Client Executives.
* **Role:** The command center. It handles the heavy lifting—complex invoicing, vendor management, compliance audits, and strategic data analysis.
* **Key Value:** Control and insight. It turns operational data into cost-saving strategies.
## 3. How the Applications Interact
The three applications do not "talk" directly to each other (e.g., the staff app doesn't send a message directly to the client app). Instead, they all communicate with a central **Shared Backend System** (The "Brain").
* **Scenario: Filling a Shift**
1. **Client App:** Manager posts a shift for "Friday, 6 PM".
2. **Backend:** Receives the request, validates it, and notifies eligible workers.
3. **Staff App:** Worker sees the notification and taps "Accept".
4. **Backend:** Confirms the match, updates the schedule, and alerts the client.
5. **Web App:** Admin sees the shift status change from "Open" to "Filled" on the live dashboard.
## 4. Shared Services & Infrastructure
To function as a cohesive unit, the ecosystem relies on several shared foundational services:
* **Central Database:** The "Single Source of Truth." Whether a worker updates their profile photo on mobile or an admin updates it on the web, the change is saved in one place (Firebase/Firestore) and reflects everywhere instantly.
* **Authentication Service:** A unified login system. While users have different roles (Client vs. Staff), the security mechanism verifying their identity is shared.
* **Notification Engine:** A centralized service that knows how to reach users—sending push notifications to phones (Mobile Apps) and emails to desktops (Web App).
* **Payment Gateway:** A shared financial pipe. It collects money from clients (Credit Card/ACH) and disburses it to workers (Direct Deposit/Instant Pay).
## 5. Data Ownership & Boundaries
To maintain privacy and organization, data is strictly compartmentalized:
* **Worker Data:** Owned by the worker but accessible to the platform. Clients can only see limited details (Name, Rating, Skills) of workers assigned to *their* specific shifts. They cannot see a worker's full financial history or assignments with other clients.
* **Client Data:** Owned by the business. Workers see only what is necessary to do the job (Location, Dress Code, Supervisor Name). They cannot see the client's internal billing or strategic reports.
* **Platform Data:** owned by Krow (Admins). This includes the aggregate data used for "Smart Strategies" and market analysis—e.g., "Average hourly rate for a Bartender in downtown."
## 6. Security & Access Control
The system operates on a **Role-Based Access Control (RBAC)** model:
* **Authentication (Who are you?):** Strict verification using email/password or phone/OTP (One-Time Password).
* **Authorization (What can you do?):**
* **Staff:** Can *read* job details but *write* only to their own timesheets and profile.
* **Clients:** Can *write* new orders and *read* reports for their own venues only.
* **Admins:** Have "Super User" privileges to view and modify data across the entire system to resolve disputes or manage configurations.
## 7. Inter-Application Dependencies
While the apps are installed separately, they are operationally dependent:
* **Dependency A:** The **Client App** cannot function without the **Staff App** users. An order posted by a client is useless if no workers exist to claim it.
* **Dependency B:** The **Staff App** relies on the **Web App** for financial processing. A worker can "clock out," but they don't get paid until the backend logic (managed via Web App rules) processes the invoice.
* **Dependency C:** All apps depend on the **Backend API**. If the central server goes down, no app can fetch data, effectively pausing the entire operation.
---
# System Overview Diagram
```mermaid
flowchart LR
subgraph Users [Users]
ClientUser((Client Manager))
StaffUser((Temporary Worker))
AdminUser((Admin / Ops))
end
subgraph FrontEnd [Application Ecosystem]
direction TB
ClientApp[Client Mobile App]
StaffApp[Staff Mobile App]
WebApp[Web Management Console]
end
subgraph Backend [Shared Backend Services]
direction TB
APIGateway[API Gateway]
subgraph CoreServices [Core Business Logic]
AuthService[Authentication Service]
OrderService[Order & Shift Service]
WorkerService[Worker Profile Service]
FinanceService[Billing & Payroll Service]
NotificationEngine[Notification Engine]
AnalyticsEngine[Analytics & AI Engine]
end
Database[("Central Database (Firebase/Firestore)")]
end
subgraph External [External Integrations]
PaymentProvider["Payment Gateway (Stripe/Bank)"]
MapService[Maps & Geolocation]
SMSGateway[SMS / OTP Service]
end
%% User Interactions
ClientUser -- Uses --> ClientApp
StaffUser -- Uses --> StaffApp
AdminUser -- Uses --> WebApp
%% App to Backend Communication
ClientApp -- "Auth, Orders, Timesheets" --> APIGateway
StaffApp -- "Auth, Job Claims, Clock-In" --> APIGateway
WebApp -- "Auth, Admin, Reports" --> APIGateway
%% Internal Backend Flow
APIGateway --> CoreServices
CoreServices --> Database
%% Specific Service Interactions
AuthService -- "Verifies Identity" --> Database
OrderService -- "Matches Shifts" --> Database
WorkerService -- "Stores Profiles" --> Database
FinanceService -- "Processes Invoices" --> Database
AnalyticsEngine -- "Reads Data" --> Database
%% External Connections
AuthService -- "Sends OTP" --> SMSGateway
StaffApp -- "Verifies Location" --> MapService
FinanceService -- "Processes Payouts" --> PaymentProvider
NotificationEngine -- "Push Alerts" --> ClientApp
NotificationEngine -- "Push Alerts" --> StaffApp
%% Styling
classDef user fill:#e1f5fe,stroke:#01579b,stroke-width:2px;
classDef app fill:#fff9c4,stroke:#fbc02d,stroke-width:2px;
classDef backend fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px;
classDef db fill:#e0e0e0,stroke:#616161,stroke-width:2px;
class ClientUser,StaffUser,AdminUser user;
class ClientApp,StaffApp,WebApp app;
class APIGateway,AuthService,OrderService,WorkerService,FinanceService,NotificationEngine,AnalyticsEngine backend;
class PaymentProvider,MapService,SMSGateway external;
class Database db;
```

View File

@@ -0,0 +1,209 @@
# Client Application: Use Case Overview
This document details the primary business actions and user flows within the **Client Mobile Application**. It is organized according to the application's logical structure and navigation flow.
---
## 1. Application Access & Authentication
### 1.1 Initial Startup & Auth Check
* **Actor:** Business Manager
* **Description:** The system determines if the user is already logged in or needs to authenticate.
* **Main Flow:**
1. User opens the application.
2. System checks for a valid session.
3. If authenticated, user is directed to the **Home Dashboard**.
4. If unauthenticated, user is directed to the **Get Started** screen.
### 1.2 Register Business Account (Sign Up)
* **Actor:** New Business Manager
* **Description:** Creating a new identity for the business on the Krow platform.
* **Main Flow:**
1. User taps "Sign Up".
2. User enters company details (Name, Industry).
3. User enters contact information and password.
4. User confirms registration and is directed to the Main App.
### 1.3 Business Sign In
* **Actor:** Existing Business Manager
* **Description:** Accessing an existing account.
* **Main Flow:**
1. User enters registered email and password.
2. System validates credentials.
3. User is granted access to the dashboard.
---
## 2. Order Management (Requesting Staff)
### 2.1 Rapid Order (Urgent Needs)
* **Actor:** Business Manager
* **Description:** Posting a shift for immediate, same-day fulfillment.
* **Main Flow:** Taps "RAPID" -> Selects Role -> Sets Quantity -> Confirms ASAP status -> Posts Order.
### 2.2 Scheduled Orders (Planned Needs)
* **Actor:** Business Manager
* **Description:** Planning for future staffing requirements.
* **Main Flow:**
1. User selects "Create Order".
2. User chooses the frequency:
* **One-Time:** A single specific shift.
* **Recurring:** Shifts that repeat on a schedule (e.g., every Monday).
* **Permanent:** Long-term staffing placement.
3. User enters date, time, role, and location.
4. User reviews cost and posts the order.
---
## 3. Operations & Workforce Management
### 3.1 Monitor Today's Coverage (Coverage Tab)
* **Actor:** Business Manager
* **Description:** A bird's-eye view of all shifts happening today.
* **Main Flow:** User navigates to "Coverage" tab -> Views percentage filled -> Identifies open gaps -> Re-posts unfilled shifts if necessary.
### 3.2 Live Activity Tracking
* **Actor:** Business Manager
* **Description:** Real-time feed of worker clock-ins and status updates.
* **Location:** Home Tab / Coverage Detail.
* **Main Flow:** User monitors the live feed for worker arrivals and on-site status.
### 3.3 Verify Worker Attire
* **Actor:** Business Manager / Site Supervisor
* **Description:** Ensuring staff arriving on-site meet the required dress code.
* **Main Flow:** User selects an active shift -> Selects worker -> Checks attire compliance (shoes, uniform, ID) -> Submits verification.
### 3.4 Review & Approve Timesheets
* **Actor:** Business Manager
* **Description:** Finalizing hours worked for payroll processing.
* **Main Flow:** User navigates to "Timesheets" -> Reviews actual vs. scheduled hours -> Taps "Approve" or "Dispute".
---
## 4. Reports & Analytics
### 4.1 Business Intelligence Reporting
* **Actor:** Business Manager / Executive
* **Description:** Accessing data visualizations to optimize business operations.
* **Available Reports:**
* **Daily Ops:** Day-to-day fulfillment and performance.
* **Spend Report:** Financial breakdown of labor costs.
* **Forecast:** Projected staffing needs and costs.
* **Performance:** Worker and vendor reliability scores.
* **No-Show:** Tracking attendance issues.
* **Coverage:** Detailed fill-rate analysis.
---
## 5. Billing & Administration
### 5.1 Financial Management (Billing Tab)
* **Actor:** Business Manager / Finance Admin
* **Description:** Reviewing invoices and managing payment methods.
* **Main Flow:** User navigates to "Billing" -> Views current balance -> Downloads past invoices -> Updates credit card/ACH info.
### 5.2 Manage Business Locations (Hubs)
* **Actor:** Business Manager
* **Description:** Defining different venues or branches where staff will be sent.
* **Main Flow:** User goes to Settings -> Client Hubs -> Adds/Edits location details and addresses.
### 5.3 Profile & Settings Management
* **Actor:** Business Manager
* **Description:** Updating personal contact info and notification preferences.
* **Main Flow:** User goes to Settings -> Edits Profile -> Toggles notification settings for shift updates and billing alerts.
---
# Use Case Diagram
```mermaid
flowchart TD
subgraph AppInitialization [App Initialization]
Start[Start App] --> CheckAuth{Check Auth Status}
CheckAuth -- Authenticated --> GoHome[Go to Main App]
CheckAuth -- Unauthenticated --> GetStarted[Go to Get Started]
end
subgraph Authentication [Authentication]
GetStarted --> AuthChoice{Select Option}
AuthChoice -- Sign In --> SignIn[Sign In Screen]
AuthChoice -- Sign Up --> SignUp[Sign Up Screen]
SignIn --> EnterCreds[Enter Credentials]
EnterCreds --> VerifySignIn{Verify}
VerifySignIn -- Success --> GoHome
VerifySignIn -- Failure --> SignInError[Show Error]
SignUp --> EnterBusinessDetails[Enter Business Details]
EnterBusinessDetails --> CreateAccount[Create Account]
CreateAccount -- Success --> GoHome
end
subgraph MainApp [Main Application Shell]
GoHome --> Shell[Scaffold with Nav Bar]
Shell --> TabNav{Tab Navigation}
TabNav -- Index 0 --> Coverage[Coverage Tab]
TabNav -- Index 1 --> Billing[Billing Tab]
TabNav -- Index 2 --> Home[Home Tab]
TabNav -- Index 3 --> Orders[Orders/Shifts Tab]
TabNav -- Index 4 --> Reports[Reports Tab]
end
subgraph HomeActions [Home Tab Actions]
Home --> CreateOrderAction{Create Order}
CreateOrderAction -- Rapid --> RapidOrder[Rapid Order Flow]
CreateOrderAction -- One-Time --> OneTimeOrder[One-Time Order Flow]
CreateOrderAction -- Recurring --> RecurringOrder[Recurring Order Flow]
CreateOrderAction -- Permanent --> PermanentOrder[Permanent Order Flow]
Home --> QuickActions[Quick Actions Widget]
Home --> Settings[Go to Settings]
Home --> Hubs[Go to Client Hubs]
end
subgraph OrderManagement [Order Management Flows]
RapidOrder --> SubmitRapid[Submit Rapid Order]
OneTimeOrder --> SubmitOneTime[Submit One-Time Order]
RecurringOrder --> SubmitRecurring[Submit Recurring Order]
PermanentOrder --> SubmitPermanent[Submit Permanent Order]
SubmitRapid --> OrderSuccess[Order Success]
SubmitOneTime --> OrderSuccess
SubmitRecurring --> OrderSuccess
SubmitPermanent --> OrderSuccess
OrderSuccess --> Home
end
subgraph ReportsAnalysis [Reports & Analytics]
Reports --> SelectReport{Select Report}
SelectReport -- Daily Ops --> DailyOps[Daily Ops Report]
SelectReport -- Spend --> SpendReport[Spend Report]
SelectReport -- Forecast --> ForecastReport[Forecast Report]
SelectReport -- Performance --> PerfReport[Performance Report]
SelectReport -- No-Show --> NoShowReport[No-Show Report]
SelectReport -- Coverage --> CovReport[Coverage Report]
end
subgraph WorkforceMgmt [Workforce Management]
Orders --> ViewShifts[View Shifts List]
ViewShifts --> ShiftDetail[View Shift Detail]
ShiftDetail --> VerifyAttire[Verify Attire]
Home --> ViewWorkers[View Workers List]
Home --> ViewTimesheets[View Timesheets]
ViewTimesheets --> ApproveTime[Approve Hours]
ViewTimesheets --> DisputeTime[Dispute Hours]
end
subgraph SettingsFlow [Settings & Configuration]
Settings --> EditProfile[Edit Profile]
Settings --> ManageHubsLink[Manage Hubs]
Hubs --> AddHub[Add New Hub]
Hubs --> EditHub[Edit Existing Hub]
end
%% Relationships across subgraphs
OrderSuccess -.-> Coverage
VerifySignIn -.-> Shell
CreateAccount -.-> Shell
```

View File

@@ -0,0 +1,208 @@
# Staff Application: Use Case Overview
This document details the primary business actions available within the **Staff Mobile Application**. It is organized according to the application's logical structure and navigation flow.
---
## 1. Application Access & Authentication
### 1.1 App Initialization
* **Actor:** Temporary Worker
* **Description:** The system checks if the user is logged in upon startup.
* **Main Flow:**
1. Worker opens the app.
2. System checks for a valid auth token.
3. If valid, worker goes to **Home**.
4. If invalid, worker goes to **Get Started**.
### 1.2 Onboarding & Registration
* **Actor:** New Worker
* **Description:** Creating a new profile to join the Krow network.
* **Main Flow:**
1. Worker enters phone number.
2. System sends SMS OTP.
3. Worker verifies OTP.
4. System checks if profile exists.
5. If new, worker completes **Profile Setup Wizard** (Personal Info -> Role/Experience -> Attire Sizes).
6. Worker enters the Main App.
---
## 2. Job Discovery (Home Tab)
### 2.1 Browse & Filter Jobs
* **Actor:** Temporary Worker
* **Description:** Finding suitable work opportunities.
* **Main Flow:**
1. Worker taps "View Available Jobs".
2. Worker filters by Role (e.g., Server) or Distance.
3. Worker selects a job card to view details (Pay, Location, Requirements).
### 2.2 Claim Open Shift
* **Actor:** Temporary Worker
* **Description:** Committing to work a specific shift.
* **Main Flow:**
1. From Job Details, worker taps "Claim Shift".
2. System validates eligibility (Certificates, Conflicts).
3. If eligible, shift is added to "My Schedule".
4. If missing requirements, system prompts to **Upload Compliance Docs**.
### 2.3 Set Availability
* **Actor:** Temporary Worker
* **Description:** Defining working hours to get better job matches.
* **Main Flow:** Worker taps "Set Availability" -> Selects dates/times -> Saves preferences.
---
## 3. Shift Execution (Shifts & Clock In Tabs)
### 3.1 View Schedule
* **Actor:** Temporary Worker
* **Description:** Reviewing upcoming commitments.
* **Main Flow:** Navigate to "My Shifts" tab -> View list of claimed shifts.
### 3.2 GPS-Verified Clock In
* **Actor:** Temporary Worker
* **Description:** Starting a shift once on-site.
* **Main Flow:**
1. Navigate to "Clock In" tab.
2. System checks GPS location against job site coordinates.
3. If **On Site**, "Swipe to Clock In" becomes active.
4. Worker swipes to start the timer.
5. If **Off Site**, system displays an error message.
### 3.3 Submit Timesheet
* **Actor:** Temporary Worker
* **Description:** Completing a shift and submitting hours for payment.
* **Main Flow:**
1. Worker swipes to "Clock Out".
2. Worker confirms total hours and break times.
3. Worker submits timesheet for client approval.
---
## 4. Financial Management (Payments Tab)
### 4.1 Track Earnings
* **Actor:** Temporary Worker
* **Description:** Monitoring financial progress.
* **Main Flow:** Navigate to "Payments" -> View "Pending Pay" (unpaid) and "Total Earned" (paid).
### 4.2 Request Early Pay
* **Actor:** Temporary Worker
* **Description:** Accessing wages before the standard payday.
* **Main Flow:**
1. Tap "Request Early Pay".
2. Select amount to withdraw from available balance.
3. Confirm transfer fee.
4. Funds are transferred to the linked bank account.
---
## 5. Profile & Compliance (Profile Tab)
### 5.1 Manage Compliance Documents
* **Actor:** Temporary Worker
* **Description:** Keeping certifications up to date.
* **Main Flow:** Navigate to "Compliance Menu" -> "Upload Certificates" -> Take photo of ID/License -> Submit.
### 5.2 Manage Tax Forms
* **Actor:** Temporary Worker
* **Description:** Submitting legal employment forms.
* **Main Flow:** Navigate to "Tax Forms" -> Complete W-4 or I-9 digitally -> Sign and Submit.
### 5.3 Krow University Training
* **Actor:** Temporary Worker
* **Description:** Improving skills to unlock better jobs.
* **Main Flow:** Navigate to "Krow University" -> Select Module -> Watch Video/Take Quiz -> Earn Badge.
### 5.4 Account Settings
* **Actor:** Temporary Worker
* **Description:** Managing personal data.
* **Main Flow:** Update Bank Details, View Benefits, or Access Support/FAQs.
---
# Use Cases Diagram
```mermaid
flowchart TD
subgraph AppInitialization [App Initialization]
Start[Start App] --> CheckAuth{Check Auth Status}
CheckAuth -- Authenticated --> GoHome[Go to Main App]
CheckAuth -- Unauthenticated --> GetStarted[Go to Get Started]
end
subgraph Authentication [Onboarding & Authentication]
GetStarted --> InputPhone[Enter Phone Number]
InputPhone --> VerifyOTP[Verify SMS Code]
VerifyOTP --> CheckProfile{Profile Complete?}
CheckProfile -- Yes --> GoHome
CheckProfile -- No --> SetupProfile[Profile Setup Wizard]
SetupProfile --> Step1[Personal Info]
Step1 --> Step2[Role & Experience]
Step2 --> Step3[Attire Sizes]
Step3 --> GoHome
end
subgraph MainApp [Main Application Shell]
GoHome --> Shell[Scaffold with Nav Bar]
Shell --> TabNav{Tab Navigation}
TabNav -- Index 0 --> Shifts[My Shifts Tab]
TabNav -- Index 1 --> Payments[Payments Tab]
TabNav -- Index 2 --> Home[Home Tab]
TabNav -- Index 3 --> ClockIn[Clock In Tab]
TabNav -- Index 4 --> Profile[Profile Tab]
end
subgraph HomeAndDiscovery [Job Discovery]
Home --> ViewOpenJobs[View Available Jobs]
ViewOpenJobs --> FilterJobs[Filter by Role/Distance]
ViewOpenJobs --> JobDetail[View Job Details]
JobDetail --> ClaimShift{Claim Shift}
ClaimShift -- Success --> ShiftSuccess[Shift Added to Schedule]
ClaimShift -- "Missing Req" --> PromptUpload[Prompt Compliance Upload]
Home --> SetAvailability[Set Availability]
Home --> ViewUpcoming[View Upcoming Shifts]
end
subgraph ShiftExecution [Shift Execution]
Shifts --> ViewSchedule[View My Schedule]
ClockIn --> CheckLocation{Verify GPS Location}
CheckLocation -- "On Site" --> SwipeIn[Swipe to Clock In]
CheckLocation -- "Off Site" --> LocationError[Show Location Error]
SwipeIn --> ActiveShift[Shift In Progress]
ActiveShift --> SwipeOut[Swipe to Clock Out]
SwipeOut --> ConfirmHours[Confirm Hours & Breaks]
ConfirmHours --> SubmitTimesheet[Submit Timesheet]
end
subgraph Financials [Earnings & Payments]
Payments --> ViewEarnings[View Pending Earnings]
Payments --> ViewHistory[View Payment History]
ViewEarnings --> EarlyPay{Request Early Pay?}
EarlyPay -- Yes --> SelectAmount[Select Amount]
SelectAmount --> ConfirmTransfer[Confirm Transfer]
end
subgraph ProfileAndCompliance [Profile & Compliance]
Profile --> ComplianceMenu[Compliance Menu]
ComplianceMenu --> UploadDocs[Upload Certificates]
ComplianceMenu --> TaxForms["Manage Tax Forms (W-4/I-9)"]
Profile --> KrowUniversity[Krow University]
KrowUniversity --> StartTraining[Start Training Module]
Profile --> BankAccount[Manage Bank Details]
Profile --> Benefits[View Benefits]
Profile --> Support["Access Support/FAQs"]
end
%% Relationships across subgraphs
SubmitTimesheet -.-> ViewEarnings
PromptUpload -.-> ComplianceMenu
ShiftSuccess -.-> ViewSchedule
```

View File

@@ -0,0 +1,251 @@
# The Krow Platform System Bible
**Status:** Official / Living Document
**Version:** 1.0.0
---
## 1. Executive Summary
### What the System Is
The **Krow Platform** is a multi-sided workforce management ecosystem that digitizes the entire lifecycle of temporary staffing. It replaces fragmented, manual processes (phone calls, spreadsheets, paper timesheets) with a unified digital infrastructure connecting businesses ("Clients") directly with temporary workers ("Staff").
### Why It Exists
The temporary staffing industry suffers from friction, lack of transparency, and delayed payments. Businesses struggle to find reliable staff quickly, while workers face uncertain schedules and slow wage access. Krow exists to remove this friction, ensuring shifts are filled instantly, work is verified accurately, and payments are processed swiftly.
### Who It Serves
1. **Clients (Businesses):** Venue managers and owners who need on-demand or scheduled staff.
2. **Staff (Workers):** Individuals seeking flexible, temporary employment opportunities.
3. **Admins (Operations):** Internal teams managing the marketplace, compliance, and financial flows.
### High-Level Value Proposition
Krow transforms labor from a manual logistical headache into a streamlined digital asset. For clients, it provides "staff on tap" with verified compliance. For workers, it offers "freedom and instant pay." For the platform operators, it delivers data-driven oversight of a complex marketplace.
---
## 2. System Vision & Product Principles
### Core Goals
1. **Immediacy:** Reduce the time-to-fill for urgent shifts from hours to minutes.
2. **Accuracy:** Eliminate payroll disputes through GPS-verified digital timesheets.
3. **Compliance:** Automate the enforcement of legal and safety requirements (attire, certifications).
### Problems It Intentionally Solves
* **The "No-Show" Epidemic:** By creating a transparent marketplace with reliability ratings.
* **Payroll Latency:** By enabling "Early Pay" features rooted in verified digital time cards.
* **Administrative Bloat:** By automating invoice generation and worker onboarding.
### Problems It Intentionally Does NOT Solve
* **Full-Time Recruitment:** This system is optimized for shift-based, temporary labor, not permanent headhunting.
* **Gig Economy "Tasking":** It focuses on professional hospitality and event roles, not general unskilled errands.
### Guiding Product Principles
* **Mobile-First for Operations:** If a task happens on a job site (clocking in, checking coverage), it *must* be possible on a phone.
* **Data as the Truth:** We do not rely on verbal confirmations. If it isn't in the system (GPS stamp, digital signature), it didn't happen.
* **Separation of Concerns:** Clients manage demand; Staff manage supply; Admin manages the rules. These roles never blur.
---
## 3. Ecosystem Overview
The ecosystem comprises three distinct applications, each serving a specific user persona but operating on a shared reality.
### 1. Client Mobile Application (The "Requester")
* **Platform:** Flutter (Mobile)
* **Responsibility:** Demand generation. Allows businesses to post orders, track arriving staff in real-time, and approve work hours.
* **Concept:** The "Remote Control" for the venue's staffing operations.
### 2. Staff Mobile Application (The "Worker")
* **Platform:** Flutter (Mobile)
* **Responsibility:** Supply fulfillment. Empowering workers to find jobs, manage their schedule, verify their presence (Clock In), and access earnings.
* **Concept:** The worker's "Digital Agency" in their pocket.
### 3. Krow Web Application (The "HQ")
* **Platform:** React (Web)
* **Responsibility:** Ecosystem governance. The command center for high-level analytics, complex financial operations (invoicing/payouts), vendor management, and system administration.
* **Concept:** The "Mission Control" for the business backend.
---
## 4. System Architecture Overview
The Krow Platform follows a **Service-Oriented Architecture (SOA)** where multiple front-end clients interface with a shared, monolithic logical backend (exposed via API Gateway).
### Architectural Style
* **Centralized State:** A single backend database serves as the source of truth for all apps.
* **Role-Based Access:** The API exposes different endpoints and data views depending on the authenticated user's role (Client vs. Staff).
* **Event-Driven Flows:** Key actions (e.g., "Shift Posted") trigger downstream effects (e.g., "Push Notification Sent") across the ecosystem.
### System Boundaries
The "System" encompasses the three front-end apps and the shared backend services. External boundaries are drawn at:
* **Payment Gateways:** We initiate transfers, but the actual money movement is external.
* **Maps/Geolocation:** We consume location data but do not maintain mapping infrastructure.
* **SMS/Identity:** We offload OTP delivery to specialized providers.
### Trust Boundaries
* **Mobile Apps are Untrusted:** We assume any data coming from a client device (GPS coordinates, timestamps) could be manipulated and must be validated server-side.
* **Web App is Semi-Trusted:** Admin actions are logged for audit but are assumed to be authorized operations.
```mermaid
flowchart TD
subgraph Clients [Client Layer]
CMA[Client Mobile App]
SMA[Staff Mobile App]
WEB[Web Admin Portal]
end
subgraph API [Interface Layer]
Gateway[API Gateway]
end
subgraph Services [Core Service Layer]
Auth[Identity Service]
Ops[Operations Service]
Finance[Financial Service]
end
subgraph Data [Data Layer]
DB[(Central Database)]
end
CMA --> Gateway
SMA --> Gateway
WEB --> Gateway
Gateway --> Services
Services --> DB
```
---
## 5. Application Responsibility Matrix
| Feature Domain | Client App (Mobile) | Staff App (Mobile) | Web App (Admin/Ops) |
| :--- | :--- | :--- | :--- |
| **User Onboarding** | Register Business | Register Worker | Onboard Vendors |
| **Shift Management** | **Create** & Monitor | **Claim** & Execute | **Oversee** & Resolve |
| **Time Tracking** | Approve / Dispute | Clock In / Out | Audit Logs |
| **Finance** | Pay Invoices | Request Payout | Generate Bills |
| **Compliance** | Verify Attire | Upload Docs | Verify Docs |
| **Analytics** | View My Venue Stats | View My Earnings | Global Market Analysis |
### Critical Rules
* **Client App MUST NOT** access worker financial data (bank details, total platform earnings).
* **Staff App MUST NOT** see client billing rates or internal venue notes.
* **Web App MUST** be the only place where global system configurations (e.g., platform fees) are changed.
---
## 6. Use Cases
The following are the **official system use cases**. Any feature request not mapping to one of these must be scrutinized.
### A. Staffing Operations
1. **Post Urgent Shift (Client):**
* *Pre:* Valid client account.
* *Flow:* Select Role -> Set Qty -> Post.
* *Post:* Notification sent to eligible workers.
2. **Claim Shift (Staff):**
* *Pre:* Worker meets compliance reqs.
* *Flow:* View Job -> Accept.
* *Post:* Shift is locked; Client notified.
3. **Execute Shift (Staff):**
* *Pre:* On-site GPS verification.
* *Flow:* Clock In -> Work -> Clock Out.
* *Validation:* Location check passes.
4. **Approve Timesheet (Client):**
* *Pre:* Shift completed.
* *Flow:* Review Hours -> Approve.
* *Post:* Payment scheduled.
### B. Financial Operations
5. **Process Billing (Web/Admin):**
* *Flow:* Aggregate approved hours -> Generate Invoice -> Charge Client.
6. **Request Early Pay (Staff):**
* *Pre:* Accrued unpaid earnings.
* *Flow:* Select Amount -> Confirm -> Transfer.
### C. Governance
7. **Verify Compliance (Web/Admin):**
* *Flow:* Review uploaded ID -> Mark as Verified.
* *Post:* Worker eligible for shifts.
8. **Strategic Analysis (Web/Client):**
* *Flow:* View Savings Engine -> Adopt Recommendation.
---
## 7. Cross-Application Interaction Rules
### Communication Patterns
* **Indirect Communication:** Apps NEVER speak peer-to-peer.
* *Correct:* Client App posts order -> Backend -> Staff App receives notification.
* *Forbidden:* Client App sends data directly to Staff App via Bluetooth/LAN.
* **Push Notifications:** Used as the primary signal to "wake up" an app and fetch fresh data from the server.
### Dependency Direction
* **Downstream Dependency:** The Mobile Apps depend on the Web App's configuration (e.g., if Admin adds a new "Role Type" on Web, it appears on Mobile).
* **Upstream Data Flow:** Operational data flows *up* from Mobile (Clock-ins) to Web (Reporting).
### Anti-Patterns to Avoid
* **"Split Brain" Logic:** Business logic (e.g., "How is overtime calculated?") must live in the Backend, NOT duplicated in the mobile apps.
* **Local-Only State:** Critical data (shift status) must never exist only on a user's device. It must be synced immediately.
---
## 8. Data Ownership & Source of Truth
| Data Domain | Source of Truth | Write Access | Read Access |
| :--- | :--- | :--- | :--- |
| **User Identity** | Auth Service | User (Self), Admin | System-wide |
| **Shift Status** | Order Service | Client (Create), Staff (Update status) | All (Context dependent) |
| **Time Cards** | Database | Staff (Create), Client (Approve) | Admin, Payroll |
| **Compliance Docs** | Worker Profile | Staff (Upload), Admin (Verify) | Client (Status only) |
| **Platform Rates** | System Config | Admin | Read-only |
### Consistency Principle
**"The Server is Right."** If a mobile device displays a shift as "Open" but the server says "Filled," the device is wrong and must refresh. We prioritize data integrity over offline availability for critical transaction states.
---
## 9. Security & Access Model
### User Roles
1. **Super Admin:** Full system access.
2. **Client Manager:** Access to own venue data only.
3. **Worker:** Access to own schedule and public job board only.
### Authentication Philosophy
* **Zero Trust:** Every API request must carry a valid, unexpired token.
* **Session Management:** Mobile sessions are persistent (long-lived tokens) for usability; Web sessions (Admin) are shorter for security.
### Authorization Boundaries
* **Horizontal Separation:** Client A cannot see Client B's orders. Worker A cannot see Worker B's pay.
* **Vertical Separation:** Staff cannot access Admin APIs.
---
## 10. Non-Negotiables & Guardrails
1. **No GPS, No Pay:** A clock-in event *must* have valid geolocation data attached. No exceptions.
2. **Compliance First:** A worker cannot claim a shift if their required documents (e.g., Food Handler Card) are expired. The system must block this at the API level.
3. **Immutable Audit Trail:** Once a timesheet is approved and paid, it cannot be deleted or modified, only reversed via a new corrective transaction.
4. **One Account Per Person:** Strict identity checks to prevent duplicate worker profiles.
---
## 11. Known Constraints & Assumptions
* **Connectivity:** The system assumes a reliable internet connection for critical actions (Claiming, Clocking In). Offline mode is limited to read-only views of cached schedules.
* **Device Capability:** We assume worker devices have functional GPS and Camera hardware.
* **Payment Timing:** "Instant" pay is subject to external banking network delays (ACH/RTP) and is not truly real-time in all cases.
---
## 12. Glossary
* **Shift:** A single unit of work with a start time, end time, and role.
* **Order:** A request from a client containing one or more shifts.
* **Clock-In:** The digital timestamp marking the start of work, verified by GPS.
* **Rapid Order:** A specific order type designed for immediate (<24h) fulfillment.
* **Early Pay:** A financial feature allowing workers to withdraw accrued wages before the standard pay period ends.
* **Hub:** A specific physical location or venue belonging to a Client.
* **Compliance:** The state of having all necessary legal and safety documents verified.

View File

@@ -0,0 +1,639 @@
# Web Application: Use Case Overview
This document details the primary business actions and user flows within the **Krow Web Application**. It is organized according to the logical workflows for each primary user role as defined in the system's architecture.
---
## 1. Access & Authentication (Common)
### 1.1 Web Portal Login
* **Actor:** All Users (Admin, Client, Vendor)
* **Description:** Secure entry into the management console.
* **Main Flow:**
1. User enters email and password on the login screen.
2. System verifies credentials against authentication service.
3. System determines user role (Admin, Client, or Vendor).
4. User is directed to their specific role-based dashboard with customizable widgets.
5. System loads user-specific dashboard layout preferences.
---
## 2. Admin Workflows (Operations Manager)
### 2.1 Global Operational Oversight
* **Actor:** Admin
* **Description:** Monitoring the pulse of the entire platform through a customizable dashboard.
* **Main Flow:**
1. User accesses Admin Dashboard with global metrics.
2. Views fill rate, total spend, performance score, and active events.
3. Monitors today's orders with status indicators (RAPID, Fully Staffed, Partial Staffed).
4. Reviews action items prioritized by urgency (critical, high, medium).
5. Accesses ecosystem visualization showing connections between Buyers, Enterprises, Sectors, Partners, and Vendors.
6. Customizes dashboard widget layout via drag-and-drop.
### 2.2 Vendor & Partner Management
* **Actor:** Admin
* **Description:** Managing the vendor network and partnerships.
* **Main Flow:**
1. User navigates to Vendor Marketplace.
2. Reviews vendor approval status and performance metrics.
3. Sets vendor tier levels (Approved Vendor, Gold Vendor).
4. Monitors vendor CSAT scores and compliance rates.
5. Views vendor rate books and service rates.
### 2.3 Order & Schedule Management
* **Actor:** Admin
* **Description:** Overseeing all orders across the platform.
* **Main Flow:**
1. User views all orders with filtering by status (All, Upcoming, Active, Past, Conflicts).
2. Reviews order details including business, hub, date/time, assigned staff.
3. Monitors assignment status (Requested vs Assigned counts).
4. Detects and resolves scheduling conflicts.
5. Accesses schedule view for visual timeline.
### 2.4 Workforce Management
* **Actor:** Admin
* **Description:** Managing platform-wide workforce.
* **Main Flow:**
1. User navigates to Staff Directory.
2. Views staff with filters (position, department, hub, profile type).
3. Monitors compliance status (background checks, certifications).
4. Reviews staff performance metrics (rating, reliability score, shift coverage).
5. Manages onboarding workflows for new staff.
### 2.5 Analytics & Reporting
* **Actor:** Admin
* **Description:** Generating insights through reports and activity logs.
* **Main Flow:**
1. User accesses Reports Dashboard.
2. Selects report type (Staffing Cost, Staff Performance, Operational Efficiency, Client Trends).
3. Configures report parameters and filters.
4. Views report insights with AI-generated recommendations.
5. Exports reports in multiple formats (PDF, Excel, CSV).
6. Reviews Activity Log for audit trail.
---
## 3. Client Executive Workflows
### 3.1 Dashboard Overview
* **Actor:** Client Executive
* **Description:** Personalized dashboard for order and labor management.
* **Main Flow:**
1. User opens Client Dashboard with customizable widgets.
2. Views action items (overdue invoices, unfilled orders, rapid requests).
3. Monitors key metrics (Today's Count, In Progress, Needs Attention).
4. Reviews labor summary with cost breakdown by position.
5. Analyzes sales analytics via pie charts.
### 3.2 Order Management
* **Actor:** Client Executive / Operations Manager
* **Description:** Creating and managing staffing requests.
* **Main Flow:**
1. User clicks "Order Now" or "RAPID Order" for urgent requests.
2. Selects business, hub, and event details.
3. Defines shifts with roles, counts, start/end times, and rates.
4. Chooses order type (one-time, rapid, recurring, permanent).
5. Enables conflict detection to prevent scheduling issues.
6. Reviews detected conflicts before submission.
7. Submits order to preferred vendor or marketplace.
### 3.3 Vendor Discovery & Selection
* **Actor:** Client Executive
* **Description:** Finding and managing vendor relationships.
* **Main Flow:**
1. User navigates to Vendor Marketplace.
2. Searches and filters vendors by region, category, rating, price.
3. Views vendor profiles with metrics (staff count, rating, fill rate, response time).
4. Expands vendor cards to view rate books by category.
5. Sets preferred vendor for automatic order routing.
6. Configures vendor preferences (locked vendors for optimization).
7. Contacts vendors via integrated messaging.
### 3.4 Savings Engine (Strategic Insights)
* **Actor:** Client Executive
* **Description:** Using AI to optimize labor spend and vendor mix.
* **Main Flow:**
1. User opens Savings Engine.
2. Reviews overview cards showing total spend, potential savings, fill rate.
3. Selects analysis timeframe (7 days, 30 days, Quarter, Year).
4. Navigates tabs for different insights:
- **Overview**: Dynamic dashboard with savings opportunities
- **Budget**: Budget utilization tracker
- **Strategies**: Smart operation strategies with AI recommendations
- **Predictions**: Cost forecasts and trend analysis
- **Vendors**: Vendor performance comparison
5. Views actionable strategies (vendor consolidation, rate optimization).
6. Exports analysis report.
### 3.5 Finance & Invoicing
* **Actor:** Client Executive / Finance Admin
* **Description:** Managing invoices and payments.
* **Main Flow:**
1. User views invoice list filtered by status (Open, Overdue, Paid, Disputed).
2. Opens invoice detail to review line items by role and staff.
3. Views from/to company information and payment terms.
4. Downloads invoice in PDF or Excel format.
5. Processes payment or disputes invoice with reason.
6. Tracks payment history.
### 3.6 Communication & Support
* **Actor:** Client Executive
* **Description:** Engaging with vendors and getting help.
* **Main Flow:**
1. User accesses Message Center for conversations.
2. Initiates conversation with vendors or admins.
3. Views conversation threads grouped by type (client-vendor, client-admin).
4. Accesses Tutorials for platform guidance.
5. Submits support tickets via Support Center.
---
## 4. Vendor Workflows (Staffing Agency)
### 4.1 Vendor Dashboard
* **Actor:** Vendor Manager
* **Description:** Comprehensive view of operations and performance.
* **Main Flow:**
1. User accesses Vendor Dashboard with customizable widgets.
2. Views KPI cards (Orders Today, In Progress, RAPID, Staff Assigned).
3. Monitors action items (urgent unfilled orders, expiring certifications, invoices to submit).
4. Reviews recent orders table with assignment status.
5. Accesses revenue carousel showing monthly revenue, total revenue, active orders.
6. Views top clients by revenue and order count.
7. Reviews client loyalty status (Champion, Loyal, At Risk).
8. Monitors top performer staff by rating.
### 4.2 Order Fulfillment
* **Actor:** Vendor Manager
* **Description:** Fulfilling client staffing requests.
* **Main Flow:**
1. User views incoming orders via "Orders" section.
2. Filters orders by tab (All, Conflicts, Upcoming, Active, Past).
3. Reviews order details (business, hub, event, date/time, roles).
4. Identifies RAPID orders (< 24 hours) needing immediate attention.
5. Clicks "Assign Staff" to open Smart Assign Modal.
6. Selects optimal staff based on skills, availability, and proximity.
7. Confirms assignments and updates order status.
8. Reviews conflict alerts for staff/venue overlaps.
### 4.3 Workforce Roster Management
* **Actor:** Vendor Manager
* **Description:** Managing agency's worker pool.
* **Main Flow:**
1. User navigates to Staff Directory.
2. Views staff with filtering options (profile type, position, department, hub).
3. Toggles between grid and list view.
4. Adds new staff via "Add Staff" button.
5. Fills staff profile form (personal info, position, department, hub, contact).
6. Edits existing staff profiles.
7. Monitors staff metrics (rating, reliability score, shift coverage, cancellations).
8. Reviews compliance status (background checks, certifications).
### 4.4 Staff Onboarding
* **Actor:** Vendor Manager
* **Description:** Streamlined multi-step onboarding for new workers.
* **Main Flow:**
1. User navigates to "Onboard Staff" section.
2. Completes profile setup step (name, email, position, department).
3. Uploads required documents (ID, certifications, licenses).
4. Assigns training modules.
5. Reviews completion status.
6. Activates staff member upon completion.
### 4.5 Compliance Management
* **Actor:** Vendor Manager
* **Description:** Maintaining workforce compliance standards.
* **Main Flow:**
1. User accesses Compliance Dashboard.
2. Views compliance metrics (background check status, certification expiry).
3. Filters staff needing attention.
4. Updates compliance documents in Document Vault.
5. Tracks certification renewal deadlines.
### 4.6 Schedule & Availability
* **Actor:** Vendor Manager
* **Description:** Managing staff availability and schedules.
* **Main Flow:**
1. User navigates to Staff Availability.
2. Views calendar-based availability grid.
3. Updates staff availability preferences.
4. Accesses Schedule view for visual timeline of assignments.
5. Identifies gaps and conflicts.
### 4.7 Client Relationship Management
* **Actor:** Vendor Manager
* **Description:** Managing client accounts and preferences.
* **Main Flow:**
1. User navigates to Clients section.
2. Views client list with business details.
3. Adds new client accounts.
4. Edits client information (contact, address, hubs, departments).
5. Configures client preferences (favorite staff, blocked staff).
6. Sets ERP integration details (vendor ID, cost center, EDI format).
### 4.8 Rate Management
* **Actor:** Vendor Manager
* **Description:** Managing service rates and pricing.
* **Main Flow:**
1. User accesses Service Rates section.
2. Views rate cards by client and role.
3. Creates new rate entries (role, client rate, employee wage).
4. Configures markup percentage and vendor fee.
5. Sets approved cap rates.
6. Activates/deactivates rates.
### 4.9 Vendor Finance & Invoicing
* **Actor:** Vendor Manager
* **Description:** Managing revenue and submitting invoices.
* **Main Flow:**
1. User views invoice list for completed orders.
2. Auto-generates invoices from completed events.
3. Reviews invoice details with staff entries and line items.
4. Edits invoice before submission if needed.
5. Submits invoice to client.
6. Tracks invoice status (Draft, Open, Confirmed, Paid).
7. Downloads invoice for records.
### 4.10 Performance Analytics
* **Actor:** Vendor Manager
* **Description:** Monitoring vendor performance metrics.
* **Main Flow:**
1. User accesses Performance section.
2. Reviews fill rate, on-time performance, client satisfaction.
3. Views staff performance leaderboard.
4. Analyzes revenue trends by client and timeframe.
### 4.11 Savings Engine (Growth Opportunities)
* **Actor:** Vendor Manager
* **Description:** Identifying growth and optimization opportunities.
* **Main Flow:**
1. User opens Savings Engine with vendor-specific tabs.
2. Reviews performance metrics and benchmarks.
3. Identifies opportunities to improve ratings and win more business.
4. Views workforce utilization statistics.
5. Analyzes growth forecasts.
---
## 5. Shared Functional Modules
### 5.1 Order Details & History
* **Actor:** All Roles
* **Description:** Accessing granular data for any specific staffing request.
* **Main Flow:**
1. User clicks any order ID from lists or dashboards.
2. System displays comprehensive order information:
- Event details (name, business, hub, date, time)
- Shift configuration with roles, counts, and rates
- Assigned staff with profiles
- Status history and audit trail
- Detected conflicts (if any)
- Invoice linkage (if completed)
3. User can edit order (if permissions allow).
4. User can assign/reassign staff.
5. User can view related invoices.
### 5.2 Invoice Detail View
* **Actor:** Admin, Client, Vendor
* **Description:** Reviewing the breakdown of costs for a billing period.
* **Main Flow:**
1. User opens an invoice from the invoice list.
2. System displays invoice header (invoice number, dates, status, parties).
3. Views detailed breakdown:
- Roles section with staff entries per role
- Hours worked (regular, overtime, double-time)
- Bill rates and totals per role
- Additional charges
- Subtotal and grand total
4. Reviews payment terms and PO reference.
5. Downloads invoice in PDF or Excel.
6. Copies invoice data to clipboard.
7. Sends invoice via email (vendor role).
8. Approves or disputes invoice (client role).
### 5.3 Task Board
* **Actor:** All Roles
* **Description:** Collaborative task management across teams.
* **Main Flow:**
1. User accesses Task Board.
2. Views tasks in columns by status (Pending, In Progress, On Hold, Completed).
3. Drags tasks between columns to update status.
4. Creates new tasks with details (name, description, priority, due date).
5. Assigns tasks to team members.
6. Adds comments and attachments to tasks.
7. Filters tasks by department, priority, or assignee.
### 5.4 Message Center
* **Actor:** All Roles
* **Description:** Cross-platform communication hub.
* **Main Flow:**
1. User accesses Message Center.
2. Views conversation list with unread counts.
3. Filters by conversation type (client-vendor, client-admin, internal).
4. Opens conversation thread.
5. Sends messages with attachments.
6. Views system-generated messages for automated events.
7. Archives completed conversations.
### 5.5 Reports & Analytics
* **Actor:** All Roles (with role-specific access)
* **Description:** Data-driven insights and custom reporting.
* **Main Flow:**
1. User accesses Reports Dashboard.
2. Selects from report types:
- Staffing Cost Report
- Staff Performance Report
- Operational Efficiency Report
- Client Trends Report
- Custom Report Builder
3. Configures report parameters (date range, filters, grouping).
4. Views AI-generated insights banner with key findings.
5. Exports report in preferred format.
6. Schedules recurring reports for automated delivery.
7. Saves report templates for reuse.
### 5.6 Teams Management
* **Actor:** Admin, Client, Vendor
* **Description:** Creating and managing staff teams.
* **Main Flow:**
1. User navigates to Teams section.
2. Views team list with member counts.
3. Creates new team with name and description.
4. Adds team members from staff directory.
5. Views team detail page with member profiles.
6. Assigns teams to orders as groups.
### 5.7 Staff Conflict Detection
* **Actor:** Admin, Vendor
* **Description:** Automated detection of scheduling conflicts.
* **Main Flow:**
1. System automatically detects conflicts when creating/editing orders:
- **Staff Overlap**: Same staff assigned to overlapping shifts
- **Venue Overlap**: Same venue booked for overlapping times
- **Time Buffer**: Insufficient travel time between assignments
2. System assigns severity level (Critical, High, Medium, Low).
3. Displays conflict alerts with details (conflicting event, staff, location).
4. User resolves conflicts before finalizing order.
5. System tracks conflict resolution in audit log.
### 5.8 Dashboard Customization
* **Actor:** All Roles
* **Description:** Personalizing dashboard layouts.
* **Main Flow:**
1. User clicks "Customize Dashboard" button.
2. Enters customization mode with drag-and-drop interface.
3. Reorders widgets by dragging.
4. Hides/shows widgets using visibility controls.
5. Previews changes in real-time.
6. Saves layout preferences to user profile.
7. Resets to default layout if desired.
---
## 6. Advanced Features
### 6.1 Smart Assignment Engine (Vendor)
* **Actor:** Vendor Manager
* **Description:** AI-powered staff assignment optimization.
* **Main Flow:**
1. User clicks "Smart Assign" on an order.
2. System analyzes requirements (skills, location, time, availability).
3. Engine scores available staff based on:
- Skill match
- Proximity to venue
- Past performance
- Availability
- Client preferences
4. Presents ranked staff recommendations.
5. User reviews suggestions and confirms assignments.
### 6.2 Auto-Invoice Generation
* **Actor:** Vendor Manager
* **Description:** Automated invoice creation from completed orders.
* **Main Flow:**
1. When order status changes to "Completed", system triggers auto-invoice.
2. System aggregates staff entries, hours, and rates.
3. Generates invoice line items by role.
4. Calculates totals (regular, overtime, double-time).
5. Applies additional charges if configured.
6. Creates draft invoice for vendor review.
7. Vendor reviews and submits to client.
### 6.3 Vendor Preferences & Optimization (Client)
* **Actor:** Client Executive
* **Description:** Configuring vendor routing and procurement strategies.
* **Main Flow:**
1. User accesses Client Vendor Preferences panel.
2. Sets preferred vendor for automatic order routing.
3. Configures locked vendors (never used for optimization).
4. Enables/disables procurement optimization.
5. System respects preferences when suggesting vendors in Savings Engine.
### 6.4 Contract Conversion & Tier Optimization
* **Actor:** Admin, Client (via Savings Engine)
* **Description:** Analyzing opportunities to move spend to preferred vendors.
* **Main Flow:**
1. User accesses "Conversion Map" tab in Savings Engine.
2. Views non-contracted spend by vendor.
3. System identifies conversion opportunities to approved/gold vendors.
4. Reviews potential savings from rate arbitrage.
5. Approves conversion strategy.
6. System routes future orders accordingly.
### 6.5 Predictive Savings Model
* **Actor:** Admin, Client
* **Description:** Forecasting cost savings through AI analysis.
* **Main Flow:**
1. User accesses "Predictions" tab in Savings Engine.
2. System analyzes historical spend, rates, and vendor performance.
3. Generates forecasts for 7 days, 30 days, quarter, year.
4. Identifies rate optimization opportunities.
5. Recommends vendor consolidation strategies.
6. Shows projected ROI for each strategy.
---
# Use Case Diagram
```mermaid
flowchart TD
subgraph AccessControl [Access & Authentication]
Start[Start Web Portal] --> CheckSession{Check Session}
CheckSession -- Valid --> CheckRole{Check User Role}
CheckSession -- Invalid --> Login[Login Screen]
Login --> EnterCreds[Enter Credentials]
EnterCreds --> Verify{Verify}
Verify -- Success --> CheckRole
Verify -- Failure --> Error[Show Error]
CheckRole -- Admin --> AdminDash[Admin Dashboard]
CheckRole -- Client --> ClientDash[Client Dashboard]
CheckRole -- Vendor --> VendorDash[Vendor Dashboard]
end
subgraph AdminWorkflows [Admin Workflows]
AdminDash --> GlobalOversight[Global Oversight]
GlobalOversight --> EcosystemWheel[Ecosystem Wheel]
GlobalOversight --> ViewAllOrders[View All Orders]
GlobalOversight --> ActionItems[Action Items]
AdminDash --> VendorMgmt[Vendor Management]
VendorMgmt --> ApproveVendors[Approve Vendors]
VendorMgmt --> SetTiers[Set Vendor Tiers]
AdminDash --> WorkforceMgmt[Workforce Management]
WorkforceMgmt --> StaffDirectory[Staff Directory]
WorkforceMgmt --> Compliance[Compliance Dashboard]
AdminDash --> AnalyticsReports[Analytics & Reports]
AnalyticsReports --> ReportsDashboard[Reports Dashboard]
AnalyticsReports --> ActivityLog[Activity Log]
end
subgraph ClientWorkflows [Client Executive Workflows]
ClientDash --> ClientActionItems[Action Items]
ClientActionItems --> ReviewAlerts[Review Alerts]
ClientDash --> OrderMgmt[Order Management]
OrderMgmt --> CreateOrder[Create Order]
CreateOrder --> DefineShifts[Define Shifts & Roles]
DefineShifts --> ConflictDetection[Conflict Detection]
ConflictDetection --> SubmitOrder[Submit Order]
OrderMgmt --> ViewMyOrders[View My Orders]
ViewMyOrders --> OrderDetail[Order Detail]
ClientDash --> VendorDiscovery[Vendor Discovery]
VendorDiscovery --> BrowseMarketplace[Browse Marketplace]
BrowseMarketplace --> SetPreferred[Set Preferred Vendor]
BrowseMarketplace --> ContactVendor[Contact Vendor]
ClientDash --> SavingsEngine[Savings Engine]
SavingsEngine --> AnalyzeSpend[Analyze Spend]
AnalyzeSpend --> ViewStrategies[View Strategies]
ViewStrategies --> ApproveStrategy[Approve Strategy]
SavingsEngine --> PredictiveSavings[Predictive Savings]
SavingsEngine --> ConversionMap[Conversion Map]
ClientDash --> ClientFinance[Finance & Invoicing]
ClientFinance --> ViewInvoices[View Invoices]
ViewInvoices --> InvoiceDetail[Invoice Detail]
InvoiceDetail --> PayInvoice[Pay Invoice]
InvoiceDetail --> DisputeInvoice[Dispute Invoice]
ClientDash --> Communication[Communication]
Communication --> MessageCenter[Message Center]
Communication --> SupportCenter[Support Center]
end
subgraph VendorWorkflows [Vendor Workflows]
VendorDash --> VendorKPIs[KPI Dashboard]
VendorKPIs --> RevenueStats[Revenue Stats]
VendorKPIs --> TopClients[Top Clients]
VendorKPIs --> TopPerformers[Top Performers]
VendorDash --> OrderFulfillment[Order Fulfillment]
OrderFulfillment --> ViewOrders[View Orders]
ViewOrders --> FilterOrders[Filter Orders]
FilterOrders --> AssignStaff[Smart Assign Staff]
AssignStaff --> ResolveConflicts[Resolve Conflicts]
VendorDash --> RosterMgmt[Roster Management]
RosterMgmt --> StaffDir[Staff Directory]
StaffDir --> AddStaff[Add Staff]
StaffDir --> EditStaff[Edit Staff]
StaffDir --> ViewMetrics[View Staff Metrics]
RosterMgmt --> OnboardStaff[Onboard Staff]
OnboardStaff --> ProfileSetup[Profile Setup]
ProfileSetup --> UploadDocs[Upload Documents]
UploadDocs --> AssignTraining[Assign Training]
AssignTraining --> ActivateStaff[Activate Staff]
VendorDash --> ComplianceMgmt[Compliance Management]
ComplianceMgmt --> ComplianceDash[Compliance Dashboard]
ComplianceDash --> DocumentVault[Document Vault]
ComplianceDash --> CertTracking[Certification Tracking]
VendorDash --> ScheduleAvail[Schedule & Availability]
ScheduleAvail --> StaffAvailability[Staff Availability]
ScheduleAvail --> ScheduleView[Schedule View]
VendorDash --> ClientMgmt[Client Management]
ClientMgmt --> ManageClients[Manage Clients]
ManageClients --> ClientPrefs[Client Preferences]
VendorDash --> RateMgmt[Rate Management]
RateMgmt --> ServiceRates[Service Rates]
ServiceRates --> RateCards[Rate Cards]
VendorDash --> VendorFinance[Finance]
VendorFinance --> AutoInvoice[Auto-Generate Invoice]
VendorFinance --> SubmitInvoice[Submit Invoice]
VendorFinance --> TrackPayments[Track Payments]
VendorDash --> VendorPerformance[Performance Analytics]
VendorPerformance --> FillRate[Fill Rate]
VendorPerformance --> CSAT[Client Satisfaction]
VendorPerformance --> RevenueAnalysis[Revenue Analysis]
end
subgraph SharedModules [Shared Functional Modules]
TaskBoard[Task Board] -.-> Tasks[Manage Tasks]
Tasks -.-> DragDrop[Drag & Drop Status]
MessageCenter -.-> Conversations[Conversations]
Conversations -.-> SendMessage[Send Message]
ReportsDashboard -.-> ReportTypes[Report Types]
ReportTypes -.-> CustomBuilder[Custom Report Builder]
ReportTypes -.-> ScheduledReports[Scheduled Reports]
ReportTypes -.-> ExportReport[Export Report]
TeamsModule[Teams] -.-> CreateTeam[Create Team]
CreateTeam -.-> AddMembers[Add Members]
DashboardCustom[Dashboard Customization] -.-> DragWidgets[Drag Widgets]
DragWidgets -.-> HideShow[Hide/Show Widgets]
HideShow -.-> SaveLayout[Save Layout]
end
```
---
## Summary of Key Enhancements
**Compared to the original document, this updated version includes:**
1. **Detailed Dashboard Workflows**: Comprehensive descriptions of customizable dashboards for each role with specific widgets and metrics.
2. **Advanced Order Management**: Multi-step order creation with shift configuration, conflict detection, and order type options (one-time, rapid, recurring, permanent).
3. **Smart Assignment**: AI-powered staff assignment engine for vendors to optimize worker selection.
4. **Savings Engine**: Detailed AI-driven cost optimization workflows with predictive modeling, vendor conversion strategies, and budget tracking.
5. **Vendor Marketplace**: Complete vendor discovery and selection process with filtering, rate comparison, and preference settings.
6. **Enhanced Finance**: Auto-invoice generation, detailed invoice views, export capabilities, and dispute resolution.
7. **Onboarding Workflow**: Multi-step staff onboarding process for vendors.
8. **Compliance Management**: Dedicated compliance dashboard and document vault.
9. **Conflict Detection**: Automated scheduling conflict detection with severity levels.
10. **Communication Hub**: Integrated message center for cross-platform communication.
11. **Teams Management**: Team creation and assignment workflows.
12. **Advanced Analytics**: Multiple report types, custom report builder, scheduled reports, and AI-generated insights.
13. **Dashboard Customization**: Drag-and-drop widget management with layout persistence.
14. **Schedule & Availability**: Calendar-based staff availability management with visual schedule view.
15. **Client & Rate Management**: Vendor-side client relationship and service rate management.
This document now accurately reflects the robust feature set implemented in the krow_web_application.

91
docs/ARCHITECTURE/web.md Normal file
View File

@@ -0,0 +1,91 @@
# KROW Web Application Architecture
## 1. Overview
The KROW Web Application serves as the "Command Center" for the platform, catering to administrators, HR, finance, and client executives. It is a high-performance, scalable dashboard designed for complex data management and analytics.
## 2. Tech Stack
- **Framework**: [React 19](https://react.dev/)
- **Build Tool**: [Vite](https://vitejs.dev/)
- **Styling**: [Tailwind CSS v4](https://tailwindcss.com/)
- **State Management**: [Redux Toolkit](https://redux-toolkit.js.org/)
- **Data Fetching**: [TanStack Query (React Query)](https://tanstack.com/query/latest)
- **Backend Integration**: Firebase Data Connect + PostgreSQL
- **Language**: TypeScript
## 3. Monorepo & Project Structure
### Recommendation: Skip Nx
After evaluating `nx` for the KROW project, the recommendation is to **skip its adoption** at this stage.
**Reasoning:**
- **Existing Orchestration**: The root `Makefile` and `Melos` (for mobile) already provide a robust orchestration layer. Adding `nx` would introduce redundant complexity.
- **Heterogeneous Stack**: `nx` excels in JS/TS-heavy monorepos. Our project is a mix of Flutter (Dart) and React (TS), which reduces the native benefits of `nx`.
- **Maintainability**: The overhead of learning and maintaining `nx` configurations outweighs the current benefits for a project of this scale.
### Future Alternative: Turborepo
If caching and task orchestration become a bottleneck for the web/JS side, **Turborepo** is recommended as a lighter alternative that integrates seamlessly with our current `pnpm` setup.
### Final Project Structure (Unified)
```
/apps
/web # React Web Dashboard
/mobile # Flutter Mobile Apps (Melos monorepo)
/packages
/design-tokens # Shared Design System (TS/JSON)
/backend
/dataconnect # Shared GraphQL Schemas
/docs
/ARCHITECTURE # Architecture Documentation
/Makefile # Unified Command Orchestrator
```
## 4. Shared Design System
### Package: `@krow/design-tokens`
A dedicated package at `/packages/design-tokens` serves as the single source of truth for design constants across all platforms.
**Folder Structure:**
```
/packages/design-tokens
/src
/colors.ts # Color palette definitions
/typography.ts # Typography scale and font families
/index.ts # Main export entry
/package.json
/tsconfig.json
```
### Color Palette (Aligned with Mobile)
Based on `UiColors` from the mobile app:
- **Primary**: `#0A39DF` (Brand Blue)
- **Accent**: `#F9E547` (Accent Yellow)
- **Background**: `#FAFBFC`
- **Foreground**: `#121826`
- **Secondary**: `#F1F3F5`
- **Muted**: `#F1F3F5`
- **Destructive**: `#F04444` (Error Red)
- **Success**: `#10B981` (Success Green)
- **Border**: `#D1D5DB`
### Typography Scale (Aligned with Mobile)
- **Primary Font**: Instrument Sans
- **Secondary Font**: Space Grotesk
- **Scales**:
- **Display L**: 36px, Height 1.1
- **Display M**: 32px, Height 1.1
- **Title 1**: 18px, Height 1.5
- **Body 1**: 16px, Height 1.5
- **Body 2**: 14px, Height 1.5
### Implementation Strategy
1. **Definition**: Define tokens in TypeScript (or JSON) within `/packages/design-tokens`.
2. **Web Consumption**: Export tokens for use in `tailwind.config.ts` or as CSS variables.
3. **Mobile Consumption**: Use a script to generate `ui_colors.dart` and `ui_typography.dart` from the shared tokens to ensure perfect alignment.
## 5. Web Application Organization
The web application follows a **feature-based** modular architecture:
- `src/features/`: Contains feature-specific logic, components, and hooks (e.g., `billing`, `scheduling`, `admin`).
- `src/components/shared/`: Reusable UI components built with Tailwind.
- `src/hooks/`: Shared React hooks.
- `src/store/`: Redux slices for global state.
- `src/dataconnect-generated/`: SDK generated by Firebase Data Connect.

View File

@@ -0,0 +1,365 @@
# KROW Workforce API Contracts
This document captures all API contracts used by the Staff and Client mobile applications. The application backend is powered by **Firebase Data Connect (GraphQL)**, so traditional REST endpoints do not exist natively. For clarity and ease of reading for all engineering team members, the tables below formulate these GraphQL Data Connect queries and mutations into their **Conceptual REST Endpoints** alongside the actual **Data Connect Operation Name**.
---
## Staff Application
### Authentication / Onboarding Pages
*(Pages: get_started_page.dart, intro_page.dart, phone_verification_page.dart, profile_setup_page.dart)*
#### Setup / User Validation API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /users/{id}` |
| **Data Connect OP** | `getUserById` |
| **Purpose** | Retrieves the base user profile to determine authentication status and role access (e.g., if the user is STAFF). |
| **Operation** | Query |
| **Inputs** | `id: UUID!` (Firebase UID) |
| **Outputs** | `User { id, email, phone, role }` |
| **Notes** | Required after OTP verification to route users appropriately. |
#### Create Default User API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `POST /users` |
| **Data Connect OP** | `createUser` |
| **Purpose** | Inserts a base user record into the system during initial signup. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `role: UserBaseRole` |
| **Outputs** | `id` of newly created User |
| **Notes** | Used explicitly during the "Sign Up" flow if the user doesn't physically exist in the database. |
#### Get Staff Profile API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/user/{userId}` |
| **Data Connect OP** | `getStaffByUserId` |
| **Purpose** | Finds the specific Staff record associated with the base user ID. |
| **Operation** | Query |
| **Inputs** | `userId: UUID!` |
| **Outputs** | `Staffs { id, userId, fullName, email, phone, photoUrl, status }` |
| **Notes** | Needed to verify if a complete staff profile exists before allowing navigation to the main app dashboard. |
#### Update Staff Profile API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `PUT /staff/{id}` |
| **Data Connect OP** | `updateStaff` |
| **Purpose** | Saves onboarding data across Personal Info, Experience, and Preferred Locations pages. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `fullName`, `email`, `phone`, `address`, etc. |
| **Outputs** | `id` |
| **Notes** | Called incrementally during the profile setup wizard as the user fills out step-by-step information. |
### Home Page & Benefits Overview
*(Pages: worker_home_page.dart, benefits_overview_page.dart)*
#### Load Today/Tomorrow Shifts
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/{staffId}/applications` |
| **Data Connect OP** | `getApplicationsByStaffId` |
| **Purpose** | Retrieves applications (shifts) assigned to the current staff member within a specific date range. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!`, `dayStart: Timestamp`, `dayEnd: Timestamp` |
| **Outputs** | `Applications { shift, shiftRole, status, createdAt }` |
| **Notes** | The frontend filters the query response for `CONFIRMED` applications to successfully display "Today's" and "Tomorrow's" shifts. |
#### List Recommended Shifts
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /shifts/recommended` |
| **Data Connect OP** | `listShifts` |
| **Purpose** | Fetches open shifts that are available for the staff to apply to. |
| **Operation** | Query |
| **Inputs** | None directly mapped on load, but fetches available items logically. |
| **Outputs** | `Shifts { id, title, orderId, cost, location, startTime, endTime, status }` |
| **Notes** | Limits output to 10 on the frontend. Should ideally rely on an active backend `$status: OPEN` parameter. |
#### Benefits Summary API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/{staffId}/benefits` |
| **Data Connect OP** | `listBenefitsDataByStaffId` |
| **Purpose** | Retrieves accrued benefits (e.g., Sick time, Vacation) to display gracefully on the home screen. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `BenefitsDatas { vendorBenefitPlan { title, total }, current }` |
| **Notes** | Used by `benefits_overview_page.dart`. Derives available metrics via `usedHours = total - current`. |
### Find Shifts / Shift Details Pages
*(Pages: shifts_page.dart, shift_details_page.dart)*
#### List Available Shifts Filtered
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /shifts` |
| **Data Connect OP** | `filterShifts` |
| **Purpose** | Used to fetch Open Shifts in specific regions when the worker searches in the "Find Shifts" tab. |
| **Operation** | Query |
| **Inputs** | `$status: ShiftStatus`, `$dateFrom: Timestamp`, `$dateTo: Timestamp` |
| **Outputs** | `Shifts { id, title, location, cost, durationDays, order { business, vendor } }` |
| **Notes** | Main driver for discovering available work. |
#### Get Shift Details
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /shifts/{id}` |
| **Data Connect OP** | `getShiftById` |
| **Purpose** | Gets deeper details for a single shift including exact uniform requirements and managers. |
| **Operation** | Query |
| **Inputs** | `id: UUID!` |
| **Outputs** | `Shift { id, title, hours, cost, locationAddress, workersNeeded ... }` |
| **Notes** | Invoked when users click into a full `shift_details_page.dart`. |
#### Apply To Shift
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `POST /applications` |
| **Data Connect OP** | `createApplication` |
| **Purpose** | Worker submits an intent to take an open shift (creates an application record). |
| **Operation** | Mutation |
| **Inputs** | `shiftId: UUID!`, `staffId: UUID!`, `roleId: UUID!`, `status: ApplicationStatus!` (e.g. `PENDING` or `CONFIRMED`), `origin: ApplicationOrigin!` (e.g. `STAFF`); optional: `checkInTime`, `checkOutTime` |
| **Outputs** | `application_insert.id` (Application ID) |
| **Notes** | The app uses `status: CONFIRMED` and `origin: STAFF` when claiming; backend also supports `PENDING` for admin review flows. After creation, shift-role assigned count and shift filled count are updated. |
### Availability Page
*(Pages: availability_page.dart)*
#### Get Default Availability
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/{staffId}/availabilities` |
| **Data Connect OP** | `listStaffAvailabilitiesByStaffId` |
| **Purpose** | Fetches the standard Mon-Sun recurring availability for a staff member. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `StaffAvailabilities { dayOfWeek, isAvailable, startTime, endTime }` |
| **Notes** | Bound to Monday through Sunday configuration. |
#### Update Availability
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `PUT /staff/availabilities/{id}` |
| **Data Connect OP** | `updateStaffAvailability` (or `createStaffAvailability` for new entries) |
| **Purpose** | Upserts availability preferences. |
| **Operation** | Mutation |
| **Inputs** | `staffId`, `dayOfWeek`, `isAvailable`, `startTime`, `endTime` |
| **Outputs** | `id` |
| **Notes** | Called individually per day edited. |
### Payments Page
*(Pages: payments_page.dart, early_pay_page.dart)*
#### Get Recent Payments
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/{staffId}/payments` |
| **Data Connect OP** | `listRecentPaymentsByStaffId` |
| **Purpose** | Loads the history of earnings and timesheets completed by the staff. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `Payments { amount, processDate, shiftId, status }` |
| **Notes** | Displays historical metrics under the comprehensive Earnings tab. |
### Compliance / Profiles
*(Pages: certificates_page.dart, documents_page.dart, tax_forms_page.dart, form_i9_page.dart, form_w4_page.dart)*
#### Get Tax Forms
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /staff/{staffId}/tax-forms` |
| **Data Connect OP** | `getTaxFormsByStaffId` |
| **Purpose** | Check the filing status and detailed inputs of I9 and W4 forms. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `TaxForms { formType, isCompleted, updatedDate }` |
| **Notes** | Crucial requirement for staff to be eligible to apply for highly regulated shifts. |
#### Update Tax Forms
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `PUT /tax-forms/{id}` |
| **Data Connect OP** | `updateTaxForm` |
| **Purpose** | Submits state and filing for the given tax form type (W4/I9). |
| **Operation** | Mutation |
| **Inputs** | `id`, `dataPoints...` |
| **Outputs** | `id` |
| **Notes** | Modifies the core compliance state variables directly. |
---
## Client Application
### Authentication / Intro
*(Pages: client_sign_in_page.dart, client_get_started_page.dart)*
#### Client User Validation API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /users/{id}` |
| **Data Connect OP** | `getUserById` |
| **Purpose** | Retrieves the base user profile to determine authentication status and role access (ensuring user is BUSINESS). |
| **Operation** | Query |
| **Inputs** | `id: UUID!` (Firebase UID) |
| **Outputs** | `User { id, email, phone, userRole }` |
| **Notes** | Validates against conditional statements checking `userRole == BUSINESS` or `BOTH`. |
#### Get Businesses By User API
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/user/{userId}` |
| **Data Connect OP** | `getBusinessesByUserId` |
| **Purpose** | Maps the authenticated user to their client business context. |
| **Operation** | Query |
| **Inputs** | `userId: String!` |
| **Outputs** | `Businesses { id, businessName, email, contactName }` |
| **Notes** | Dictates the working scopes (Business ID) across the entire application lifecycle and binds the user. |
### Hubs Page
*(Pages: client_hubs_page.dart, edit_hub_page.dart, hub_details_page.dart)*
#### List Hubs by Team
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /teams/{teamId}/hubs` |
| **Data Connect OP** | `getTeamHubsByTeamId` |
| **Purpose** | Fetches the primary working sites (Hubs) for a client context by using Team mapping. |
| **Operation** | Query |
| **Inputs** | `teamId: UUID!` |
| **Outputs** | `TeamHubs { id, hubName, address, managerName, isActive }` |
| **Notes** | `teamId` is derived first from `getTeamsByOwnerId(ownerId: businessId)`. |
#### Create / Update / Delete Hub
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `POST /team-hubs` / `PUT /team-hubs/{id}` / `DELETE /team-hubs/{id}` |
| **Data Connect OP** | `createTeamHub` / `updateTeamHub` / `deleteTeamHub` |
| **Purpose** | Provisions, Edits details directly, or Removes a Team Hub location. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, optionally `hubName`, `address`, etc. |
| **Outputs** | `id` |
| **Notes** | Fired from `edit_hub_page.dart` mutations. |
### Orders Page
*(Pages: create_order_page.dart, view_orders_page.dart, recurring_order_page.dart)*
#### Create Order
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `POST /orders` |
| **Data Connect OP** | `createOrder` |
| **Purpose** | Submits a new request for temporary staff requirements. |
| **Operation** | Mutation |
| **Inputs** | `businessId`, `eventName`, `orderType`, `status` |
| **Outputs** | `id` (Order ID) |
| **Notes** | This explicitly invokes an order pipeline, meaning Shift instances are subsequently created through secondary mutations triggered after order instantiation. |
#### List Orders
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/orders` |
| **Data Connect OP** | `listOrdersByBusinessId` |
| **Purpose** | Retrieves all ongoing and past staff requests from the client. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `Orders { id, eventName }` |
| **Notes** | Populates the `view_orders_page.dart`. |
### Billing Pages
*(Pages: billing_page.dart, pending_invoices_page.dart, completion_review_page.dart)*
#### List Invoices
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/invoices` |
| **Data Connect OP** | `listInvoicesByBusinessId` |
| **Purpose** | Fetches all invoices bound directly to the active business context (mapped directly in Firebase Schema). |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `Invoices { id, amount, issueDate, status }` |
| **Notes** | Used massively across all Billing view tabs. |
#### Mark / Dispute Invoice
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `PUT /invoices/{id}` |
| **Data Connect OP** | `updateInvoice` |
| **Purpose** | Actively marks an invoice as disputed or pays it directly (altering status). |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `status: InvoiceStatus` |
| **Outputs** | `id` |
| **Notes** | Disputing usually involves setting a `disputeReason` flag state dynamically via builder pattern. |
### Reports Page
*(Pages: reports_page.dart, coverage_report_page.dart, performance_report_page.dart)*
#### Get Coverage Stats
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/coverage` |
| **Data Connect OP** | `listShiftsForCoverage` |
| **Purpose** | Provides data on Shifts grouped by Date for fulfillment calculations. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `startDate: Timestamp!`, `endDate: Timestamp!` |
| **Outputs** | `Shifts { id, date, workersNeeded, filled, status }` |
| **Notes** | The frontend aggregates the raw backend rows to compose Coverage percentage natively. |
#### Get Daily Ops Stats
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/dailyops` |
| **Data Connect OP** | `listShiftsForDailyOpsByBusiness` |
| **Purpose** | Supplies current day operations and shift tracking progress. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `date: Timestamp!` |
| **Outputs** | `Shifts { id, title, location, workersNeeded, filled }` |
| **Notes** | - |
#### Get Forecast Stats
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/forecast` |
| **Data Connect OP** | `listShiftsForForecastByBusiness` |
| **Purpose** | Retrieves scheduled future shifts to calculate financial run-rates. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `startDate: Timestamp!`, `endDate: Timestamp!` |
| **Outputs** | `Shifts { id, date, workersNeeded, hours, cost }` |
| **Notes** | The App maps hours `x` cost to deliver Financial Dashboards. |
#### Get Performance KPIs
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/performance` |
| **Data Connect OP** | `listShiftsForPerformanceByBusiness` |
| **Purpose** | Fetches historical data allowing time-to-fill and completion-rate calculations. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `startDate: Timestamp!`, `endDate: Timestamp!` |
| **Outputs** | `Shifts { id, workersNeeded, filled, createdAt, filledAt }` |
| **Notes** | Data Connect exposes timestamps so the App calculates `avgFillTimeHours`. |
#### Get No-Show Metrics
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/noshows` |
| **Data Connect OP** | `listShiftsForNoShowRangeByBusiness` |
| **Purpose** | Retrieves shifts where workers historically ghosted the platform. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `startDate: Timestamp!`, `endDate: Timestamp!` |
| **Outputs** | `Shifts { id, date }` |
| **Notes** | Accompanies `listApplicationsForNoShowRange` cascading querying to generate full report. |
#### Get Spend Analytics
| Field | Description |
|---|---|
| **Conceptual Endpoint** | `GET /business/{businessId}/spend` |
| **Data Connect OP** | `listInvoicesForSpendByBusiness` |
| **Purpose** | Detailed invoice aggregates for Spend metrics filtering. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!`, `startDate: Timestamp!`, `endDate: Timestamp!` |
| **Outputs** | `Invoices { id, issueDate, dueDate, amount, status }` |
| **Notes** | Used explicitly under the "Spend Report" graphings. |
---

View File

@@ -0,0 +1,183 @@
# Backend Cloud Run / Functions Guide
## 1) Validate Shift Acceptance (Worker)
**Best fit:** Cloud Run
**Why backend logic is required**
- Shift acceptance must be enforced serverside to prevent bypassing the client.
- It must be racecondition safe (two accepts at the same time).
- It needs to be extensible for future eligibility rules.
**Proposed backend solution**
Add a single command endpoint:
- `POST /shifts/:shiftId/accept`
**Backend flow**
- Verify Firebase Auth token + permissions (worker identity).
- Run an extensible validation pipeline (pluggable rules):
- `NoOverlapRule` (M4)
- Future rules can be added without changing core logic.
- Apply acceptance in a DB transaction (atomic).
- Return a clear error payload on rejection:
- `409 CONFLICT` (overlap) with `{ code, message, conflictingShiftIds }`
---
## 2) Validate Shift Creation by a Client (Minimum Hours — soft check)
**Best fit:** Cloud Run
**Why backend logic is required**
- Creation rules must be enforced serverside so clients cant bypass validations by skipping the UI or calling APIs directly.
- We want a scalable rule system so new creation checks can be added without rewriting core logic.
**Proposed backend solution**
Add/route creation through a backend validation layer (Cloud Run endpoint or a dedicated “create order” command).
**On create**
- Compute shift duration and compare against vendor minimum (current: **5 hours**).
- Return a consistent validation response when below minimum, e.g.:
- `200 OK` with `{ valid: false, severity: "SOFT", code: "MIN_HOURS", message, minHours: 5 }`
- (or `400` only if we decide it should block creation; for now its a soft check)
**FE note**
- Show the same message before submission (UX feedback), but backend remains the source of truth.
---
## 3) Enforce Cancellation Policy (no cancellations within 24 hours)
**Best fit:** Cloud Run
**Why backend logic is required**
- Cancellation restrictions must be enforced serverside to prevent policy bypass.
- Ensures consistent behavior across web/mobile and future clients.
**Proposed backend solution**
Add a backend command endpoint for cancel:
- `POST /shifts/:shiftId/cancel` (or `/orders/:id/cancel` depending on ownership model)
**Backend checks**
- If `now >= shiftStart - 24h`, reject cancellation.
**Error response**
- `403 FORBIDDEN` (or `409 CONFLICT`) with `{ code: "CANCEL_WINDOW_LOCKED", message, windowHours: 24, penalty: <TBD> }`
- Once penalty is finalized, include it in the response and logs/audit trail.
---
## 4) Implement Worker Documentation Upload Process
**Best fit:** Cloud Functions v2 + Cloud Storage
**Why backend logic is required**
- Uploads must be stored securely and reliably linked to the correct worker profile.
- Requires serverside auth and auditing.
**Proposed backend solution**
- HTTP/Callable Function: `uploadInit(workerId, docType)` → returns signed upload URL + `documentId`.
- Client uploads directly to Cloud Storage.
- Storage trigger (`onFinalize`) or `uploadComplete(documentId)`:
- Validate uploader identity/ownership.
- Store metadata in DB (type, path, status, timestamps).
- Link document to worker profile.
- Enforce access control (worker/self, admins, authorized client reviewers).
---
## 5) Parse Uploaded Documentation for Verification
**Best fit:** Cloud Functions (eventdriven) or Cloud Run worker (async)
**Why backend logic is required**
- Parsing should run asynchronously.
- Store structured results for review while keeping manual verification as the final authority.
**Proposed backend solution**
- Trigger on Storage upload finalize:
- OCR/AI extract key fields → store structured output (`parsedFields`, `confidence`, `aiStatus`).
- Keep manual review:
- Client can approve/override AI results.
- Persist reviewer decision + audit trail.
---
## 6) Support Attire Upload for Workers
**Best fit:** Cloud Functions v2 + Cloud Storage
**Why backend logic is required**
- Attire images must be securely stored and linked to the correct worker profile.
- Requires serverside authorization.
**Proposed backend solution**
- HTTP/Callable Function: `attireUploadInit(workerId)` → signed upload URL + `attireAssetId`.
- Client uploads to Cloud Storage.
- Storage trigger (`onFinalize`) or `attireUploadComplete(attireAssetId)`:
- Validate identity/ownership.
- Store metadata and link to worker profile.
---
## 7) Verify Attire Images Against Shift Dress Code
**Best fit:** Cloud Functions (trigger) or Cloud Run worker (async)
**Why backend logic is required**
- Verification must be enforced serverside.
- Must remain reviewable/overrideable by the client even if AI passes.
**Proposed backend solution**
- Async verification triggered after upload or when tied to a shift:
- Evaluate dress code rules (and optional AI).
- Store results `{ status, reasons, evidence, confidence }`.
- Client can manually approve/override; audit every decision.
---
## 8) Support Shifts Requiring “Awaiting Confirmation” Status
**Best fit:** Cloud Run (domain state transitions)
**Why backend logic is required**
- State transitions must be enforced serverside.
- Prevent invalid bookings and support future workflow rules.
**Proposed backend solution**
- Add status flow: `AWAITING_CONFIRMATION → BOOKED/ACTIVE` (per lifecycle).
- Command endpoint: `POST /shifts/:id/confirm`.
**Backend validates**
- Caller is the assigned worker.
- Shift is still eligible (not started/canceled/overlapped, etc.).
- Persist transition + audit event.
---
## 9) Enable NFCBased ClockIn and ClockOut
**Best fit:** Cloud Run (secure API) + optional Cloud Functions for downstream events
**Why backend logic is required**
- Clockin/out is securitysensitive and must be validated serverside.
- Requires strong auditing and antifraud checks.
**Proposed backend solution**
API endpoints:
- `POST /attendance/clock-in`
- `POST /attendance/clock-out`
**Validate**
- Firebase identity.
- NFC tag legitimacy (mapped to hub/location).
- Time window rules + prevent duplicates/inconsistent sequences.
**Persist**
- Store immutable events + derived attendance record.
- Emit audit logs/alerts if needed.
---
## 10) Update Recurring & Permanent Orders (Backend)
**Best fit:** Cloud Run
**Why backend logic is required**
Updating a recurring or permanent order is not a single update. It may affect **N shifts** and **M shift roles**, and requires extra validations, such as:
- Prevent editing shifts that already started.
- Prevent removing or reducing roles with assigned staff.
- Control whether changes apply to future only, from a given date, or all.
- Ensure data consistency (allornothing updates).
These operations can take time and must be enforced serverside, even if the client is bypassed.

View File

@@ -0,0 +1,135 @@
# Agent Development Rules
These rules are **NON-NEGOTIABLE**. They are designed to prevent architectural degradation by automated agents.
## 1. File Creation & Structure
1. **Feature-First Packaging**:
* **DO**: Create new features as independent packages in `apps/mobile/packages/features/<app_name>/<feature_name>`.
* **DO NOT**: Add features to `apps/mobile/packages/core` or existing apps directly.
* **DO NOT**: Create cross-feature or cross-app dependencies.
2. **Path Conventions**:
* Entities: `apps/mobile/packages/domain/lib/src/entities/<entity>.dart`
* Repositories (Interface): `apps/mobile/packages/features/<app_name>/<feature>/lib/src/domain/repositories/<name>_repository_interface.dart`
* Repositories (Impl): `apps/mobile/packages/features/<app_name>/<feature>/lib/src/data/repositories_impl/<name>_repository_impl.dart`
* Use Cases: `apps/mobile/packages/features/<app_name>/<feature>/lib/src/application/<name>_usecase.dart`
* BLoCs: `apps/mobile/packages/features/<app_name>/<feature>/lib/src/presentation/blocs/<name>_bloc.dart`
* Pages: `apps/mobile/packages/features/<app_name>/<feature>/lib/src/presentation/pages/<name>_page.dart`
* Widgets: `apps/mobile/packages/features/<app_name>/<feature>/lib/src/presentation/widgets/<name>_widget.dart`
3. **Barrel Files**:
* **DO**: Use `export` in `lib/<package_name>.dart` only for public APIs.
* **DO NOT**: Export internal implementation details in the main package file.
## 2. Naming Conventions
Follow Dart standards strictly.
| Type | Convention | Example |
| :--- | :--- | :--- |
| **Files** | `snake_case` | `user_profile_page.dart` |
| **Classes** | `PascalCase` | `UserProfilePage` |
| **Variables** | `camelCase` | `userProfile` |
| **Interfaces** | terminate with `Interface` | `AuthRepositoryInterface` |
| **Implementations** | terminate with `Impl` | `AuthRepositoryImpl` |
## 3. Logic Placement (Strict Boundaries)
* **Business Rules**: MUST reside in **Use Cases** (Domain/Feature Application layer).
* *Forbidden*: Placing business rules in BLoCs or Widgets.
* **State Logic**: MUST reside in **BLoCs** or **StatefulWidgets** (only for ephemeral UI state).
* *Forbidden*: `setState` in Pages for complex state management.
* **Recommendation**: Pages should be `StatelessWidget` with state delegated to BLoCs.
* **Data Transformation**: MUST reside in **Repositories** (Data Connect layer).
* *Forbidden*: Parsing JSON in the UI or Domain.
* **Pattern**: Repositories map Data Connect models to Domain entities.
* **Navigation Logic**: MUST reside in **Flutter Modular Routes**.
* *Forbidden*: `Navigator.push` with hardcoded widgets.
* **Pattern**: Use named routes via `Modular.to.navigate()`.
* **Session Management**: MUST reside in **DataConnectService** via **SessionHandlerMixin**.
* **Pattern**: Automatic token refresh, auth state listening, and role-based validation.
* **UI Reaction**: **SessionListener** widget wraps the entire app and responds to session state changes.
## 4. Localization (core_localization) Integration
All user-facing text MUST be localized using the centralized `core_localization` package:
1. **String Management**:
* Define all user-facing strings in `apps/mobile/packages/core_localization/lib/src/l10n/`
* Use `slang` or similar i18n tooling for multi-language support
* Access strings in presentation layer via `context.strings.<key>`
2. **BLoC Integration**:
* `LocaleBloc` manages the current locale state
* Apps import `core_localization.LocalizationModule()` in their module imports
* Wrap app with `BlocProvider<LocaleBloc>()` to expose locale state globally
3. **Feature Usage**:
* Pages and widgets access localized strings: `Text(context.strings.buttonLabel)`
* Build methods receive `BuildContext` with access to current locale
* No hardcoded English strings in feature packages
4. **Error Messages**:
* Use `ErrorTranslator` from `core_localization` to map domain failures to user-friendly messages
* **Pattern**: Failures emitted from BLoCs are translated to localized strings in the UI
## 5. Data Connect Integration Strategy
All backend access is centralized through `DataConnectService` in `apps/mobile/packages/data_connect`:
1. **Repository Interface First**: Define `abstract interface class <Name>RepositoryInterface` in the feature's `domain/repositories/` folder.
2. **Repository Implementation**: Implement the interface in `data/repositories_impl/` using `_service.run()` wrapper.
* **Pattern**: `await _service.run(() => connector.<query>().execute())`
* **Benefit**: Automatic auth validation, token refresh, and error handling.
3. **Session Handling**: Use `DataConnectService.instance.initializeAuthListener(allowedRoles: [...])` in app main.dart.
* **Automatic**: Token refresh with 5-minute expiry threshold.
* **Retry Logic**: 3 attempts with exponential backoff (1s → 2s → 4s) before emitting error.
* **Role Validation**: Configurable per app (e.g., Staff: `['STAFF', 'BOTH']`, Client: `['CLIENT', 'BUSINESS', 'BOTH']`).
4. **Session State Management**: Wrap app with `SessionListener` widget to react to session changes.
* **Dialogs**: Shows session expired or error dialogs for user-facing feedback.
* **Navigation**: Routes to login on session loss, to home on authentication.
## 5. Prototype Migration Rules
You have access to `prototypes/` folders. When migrating code:
1. **Extract Assets**:
* You MAY copy icons, images, and colors. But they should be tailored to the current design system. Do not change the colours and typgorahys in the design system. They are final. And you have to use these in the UI.
* When you matching colous and typography, from the POC match it with the design system and use the colors and typography from the design system. As mentioned in the `apps/mobile/docs/03-design-system-usage.md`.
2. **Extract Layouts**: You MAY copy `build` methods for UI structure.
3. **REJECT Architecture**: You MUST **NOT** copy the `GetX`, `Provider`, or `MVC` patterns often found in prototypes. Refactor immediately to **Bloc + Clean Architecture with Flutter Modular and Melos**.
## 6. Handling Ambiguity
If a user request is vague:
1. **STOP**: Do not guess domain fields or workflows.
2. **ANALYZE**:
- For architecture related questions, refer to `apps/mobile/docs/01-architecture-principles.md` or existing code.
- For design system related questions, refer to `apps/mobile/docs/03-design-system-usage.md` or existing code.
3. **DOCUMENT**: If you must make an assumption to proceed, add a comment `// ASSUMPTION: <explanation>` and mention it in your final summary.
4. **ASK**: Prefer asking the user for clarification on business rules (e.g., "Should a 'Job' have a 'status'?").
## 7. Dependencies
* **DO NOT** add 3rd party packages without checking `apps/mobile/packages/core` first.
* **DO NOT** add `firebase_auth` or `firebase_data_connect` to any Feature package. They belong in `data_connect` only.
* **Service Locator**: Use `DataConnectService.instance` for singleton access to backend operations.
* **Dependency Injection**: Use Flutter Modular for BLoC (never use `addSingleton` for Blocs, always use `add` method) and UseCase injection in `Module.routes()`.
## 8. Error Handling
* **Domain Failures**: Define custom `Failure` classes in `domain/failures/`.
* **Data Connect Errors**: Map Data Connect exceptions to Domain failures in repositories.
* **User Feedback**: BLoCs emit error states; UI displays snackbars or dialogs.
* **Session Errors**: SessionListener automatically shows dialogs for session expiration/errors.
## 9. Testing
* **Unit Tests**: Test use cases and repositories with real implementations.
* **Widget Tests**: Use `WidgetTester` to test UI widgets and BLoCs.
* **Integration Tests**: Test full feature flows end-to-end with Data Connect.
* **Pattern**: Use dependency injection via Modular to swap implementations if needed for testing.
## 10. Follow Clean Code Principles
* Add doc comments to all classes and methods you create.
* Keep methods and classes focused and single-responsibility.
* Use meaningful variable names that reflect intent.
* Keep widget build methods concise; extract complex widgets to separate files.

View File

@@ -0,0 +1,378 @@
# KROW Architecture Principles
This document is the **AUTHORITATIVE** source of truth for the KROW engineering architecture.
All agents and engineers must adhere strictly to these principles. Deviations are interpreted as errors.
## 1. High-Level Architecture
The KROW platform follows a strict **Clean Architecture** implementation within a **Melos Monorepo**.
Dependencies flow **inwards** towards the Domain.
```mermaid
graph TD
subgraph "Apps (Entry Points)"
ClientApp["apps/mobile/apps/client"]
StaffApp["apps/mobile/apps/staff"]
end
subgraph "Features"
ClientFeatures["apps/mobile/packages/features/client/*"]
StaffFeatures["apps/mobile/packages/features/staff/*"]
end
subgraph "Services"
DataConnect["apps/mobile/packages/data_connect"]
DesignSystem["apps/mobile/packages/design_system"]
CoreLocalization["apps/mobile/packages/core_localization"]
end
subgraph "Core Domain"
Domain["apps/mobile/packages/domain"]
Core["apps/mobile/packages/core"]
end
%% Dependency Flow
ClientApp --> ClientFeatures & DataConnect & CoreLocalization
StaffApp --> StaffFeatures & DataConnect & CoreLocalization
ClientFeatures & StaffFeatures --> Domain
ClientFeatures & StaffFeatures --> DesignSystem
ClientFeatures & StaffFeatures --> CoreLocalization
ClientFeatures & StaffFeatures --> Core
DataConnect --> Domain
DataConnect --> Core
DesignSystem --> Core
CoreLocalization --> Core
Domain --> Core
%% Strict Barriers
linkStyle default stroke-width:2px,fill:none,stroke:gray
```
## 2. Repository Structure & Package Roles
### 2.1 Apps (`apps/mobile/apps/`)
- **Role**: Application entry points and Dependency Injection (DI) roots.
- **Responsibilities**:
- Initialize Flutter Modular.
- Assemble features into a navigation tree.
- Inject concrete implementations (from `data_connect`) into Feature packages.
- Configure environment-specific settings.
- **RESTRICTION**: NO business logic. NO UI widgets (except `App` and `Main`).
### 2.2 Features (`apps/mobile/packages/features/<APP_NAME>/<FEATURE_NAME>`)
- **Role**: Vertical slices of user-facing functionality.
- **Internal Structure**:
- `domain/`: Feature-specific Use Cases(always extend the apps/mobile/packages/core/lib/src/domain/usecases/usecase.dart abstract clas) and Repository Interfaces.
- `data/`: Repository Implementations.
- `presentation/`:
- Pages, BLoCs, Widgets.
- For performance make the pages as `StatelessWidget` and move the state management to the BLoC (always use a BlocProvider when providing the BLoC to the widget tree) or `StatefulWidget` to an external separate widget file.
- **Responsibilities**:
- **Presentation**: UI Pages, Modular Routes.
- **State Management**: BLoCs / Cubits.
- **Application Logic**: Use Cases.
- **RESTRICTION**: Features MUST NOT import other features. Communication happens via shared domain events.
### 2.3 Domain (`apps/mobile/packages/domain`)
- **Role**: The stable heart of the system. Pure Dart.
- **Responsibilities**:
- **Entities**: Immutable data models (Data Classes).
- **Failures**: Domain-specific error types.
- **RESTRICTION**: NO Flutter dependencies. NO `json_annotation`. NO package dependencies (except `equatable`).
### 2.4 Data Connect (`apps/mobile/packages/data_connect`)
- **Role**: Interface Adapter for Backend Access (Datasource Layer).
- **Responsibilities**:
- **Connectors**: Centralized repository implementations for each backend connector (see `03-data-connect-connectors-pattern.md`)
- One connector per backend connector domain (staff, order, user, etc.)
- Repository interfaces and use cases defined at domain level
- Repository implementations query backend and map responses
- Implement Firebase Data Connect connector and service layer
- Map Domain Entities to/from Data Connect generated code
- Handle Firebase exceptions and map to domain failures
- Provide centralized `DataConnectService` with session management
- **RESTRICTION**:
- NO feature-specific logic. Connectors are domain-neutral and reusable.
- All queries must follow Clean Architecture (domain → data layers)
- See `03-data-connect-connectors-pattern.md` for detailed pattern documentation
### 2.5 Design System (`apps/mobile/packages/design_system`)
- **Role**: Visual language and component library.
- **Responsibilities**:
- UI components if needed. But mostly try to modify the theme file (apps/mobile/packages/design_system/lib/src/ui_theme.dart) so we can directly use the theme in the app, to use the default material widgets.
- If not possible, and if that specific widget is used in multiple features, then try to create a shared widget in the `apps/mobile/packages/design_system/widgets`.
- Theme definitions (Colors, Typography).
- Assets (Icons, Images).
- More details on how to use this package is available in the `apps/mobile/docs/03-design-system-usage.md`.
- **RESTRICTION**:
- CANNOT change colours or typography.
- Dumb widgets only. NO business logic. NO state management (Bloc).
- More details on how to use this package is available in the `apps/mobile/docs/03-design-system-usage.md`.
### 2.6 Core Localization (`apps/mobile/packages/core_localization`)
- **Role**: Centralized language and localization management.
- **Responsibilities**:
- Define all user-facing strings in `l10n/` with i18n tooling support
- Provide `LocaleBloc` for reactive locale state management
- Export `TranslationProvider` for BuildContext-based string access
- Map domain failures to user-friendly localized error messages via `ErrorTranslator`
- **Feature Integration**:
- Features access strings via `context.strings.<key>` in presentation layer
- BLoCs don't depend on localization; they emit domain failures
- Error translation happens in UI layer (pages/widgets)
- **App Integration**:
- Apps import `LocalizationModule()` in their module imports
- Apps wrap the material app with `BlocProvider<LocaleBloc>()` and `TranslationProvider`
- Apps initialize `MaterialApp` with locale from `LocaleState`
### 2.7 Core (`apps/mobile/packages/core`)
- **Role**: Cross-cutting concerns.
- **Responsibilities**:
- Extension methods.
- Logger configuration.
- Base classes for Use Cases or Result types (functional error handling).
## 3. Dependency Direction & Boundaries
1. **Domain Independence**: `apps/mobile/packages/domain` knows NOTHING about the outer world. It defines *what* needs to be done, not *how*.
2. **UI Agnosticism**: `apps/mobile/packages/features` depends on `apps/mobile/packages/design_system` for looks and `apps/mobile/packages/domain` for logic. It does NOT know about Firebase.
3. **Data Isolation**: `apps/mobile/packages/data_connect` depends on `apps/mobile/packages/domain` to know what interfaces to implement. It does NOT know about the UI.
## 4. Data Connect Service & Session Management
All backend access is unified through `DataConnectService` with integrated session management:
### 4.1 Session Handler Mixin
- **Location**: `apps/mobile/packages/data_connect/lib/src/services/mixins/session_handler_mixin.dart`
- **Responsibilities**:
- Automatic token refresh (triggered when token <5 minutes to expiry)
- Firebase auth state listening
- Role-based access validation
- Session state stream emissions
- 3-attempt retry logic with exponential backoff on token validation failure
- **Key Method**: `initializeAuthListener(allowedRoles: [...])` - call once on app startup
### 4.2 Session Listener Widget
- **Location**: `apps/mobile/apps/<app>/lib/src/widgets/session_listener.dart`
- **Responsibilities**:
- Wraps entire app to listen to session state changes
- Shows user-friendly dialogs for session expiration/errors
- Handles navigation on auth state changes
- **Pattern**: `SessionListener(child: AppWidget())`
### 4.3 Repository Pattern with Data Connect
1. **Interface First**: Define `abstract interface class <Name>RepositoryInterface` in feature domain layer.
2. **Implementation**: Use `_service.run()` wrapper that automatically:
- Validates user is authenticated (if required)
- Ensures token is valid and refreshes if needed
- Executes the Data Connect query
- Handles exceptions and maps to domain failures
3. **Session Store Population**: On successful auth, session stores are populated:
- Staff: `StaffSessionStore.instance.setSession(StaffSession(...))`
- Client: `ClientSessionStore.instance.setSession(ClientSession(...))`
4. **Lazy Loading**: If session is null, fetch data via `getStaffById()` or `getBusinessById()` and update store.
## 5. Feature Isolation & Cross-Feature Communication
- **Zero Direct Imports**: `import 'package:feature_a/...'` is FORBIDDEN inside `package:feature_b`.
- Exception: Shared packages like `domain`, `core`, and `design_system` are always accessible.
- **Navigation**: Use named routes via Flutter Modular:
- **Pattern**: `Modular.to.navigate('route_name')`
- **Configuration**: Routes defined in `module.dart` files; constants in `paths.dart`
- **Data Sharing**: Features do not share state directly. Shared data accessed through:
- **Domain Repositories**: Centralized data sources (e.g., `AuthRepository`)
- **Session Stores**: `StaffSessionStore` and `ClientSessionStore` for app-wide user context
- **Event Streams**: If needed, via `DataConnectService` streams for reactive updates
## 6. App-Specific Session Management
Each app (`staff` and `client`) has different role requirements and session patterns:
### 6.1 Staff App Session
- **Location**: `apps/mobile/apps/staff/lib/main.dart`
- **Initialization**: `DataConnectService.instance.initializeAuthListener(allowedRoles: ['STAFF', 'BOTH'])`
- **Session Store**: `StaffSessionStore` with `StaffSession(user: User, staff: Staff?, ownerId: String?)`
- **Lazy Loading**: `getStaffName()` fetches via `getStaffById()` if session null
- **Navigation**: On auth → `Modular.to.toStaffHome()`, on unauth → `Modular.to.toInitialPage()`
### 6.2 Client App Session
- **Location**: `apps/mobile/apps/client/lib/main.dart`
- **Initialization**: `DataConnectService.instance.initializeAuthListener(allowedRoles: ['CLIENT', 'BUSINESS', 'BOTH'])`
- **Session Store**: `ClientSessionStore` with `ClientSession(user: User, business: ClientBusinessSession?)`
- **Lazy Loading**: `getUserSessionData()` fetches via `getBusinessById()` if session null
- **Navigation**: On auth → `Modular.to.toClientHome()`, on unauth → `Modular.to.toInitialPage()`
## 7. Data Connect Connectors Pattern
See **`03-data-connect-connectors-pattern.md`** for comprehensive documentation on:
- How connector repositories work
- How to add queries to existing connectors
- How to create new connectors
- Integration patterns with features
- Benefits and anti-patterns
**Quick Reference**:
- All backend queries centralized in `apps/mobile/packages/data_connect/lib/src/connectors/`
- One connector per backend connector domain (staff, order, user, etc.)
- Each connector follows Clean Architecture (domain interfaces + data implementations)
- Features use connector repositories through dependency injection
- Results in zero query duplication and single source of truth
## 8. Prop Drilling Prevention & Direct BLoC Access
### 8.1 The Problem: Prop Drilling
Passing data through intermediate widgets creates maintenance headaches:
- Every intermediate widget must accept and forward props
- Changes to data structure ripple through multiple widget constructors
- Reduces code clarity and increases cognitive load
**Anti-Pattern Example**:
```dart
// ❌ BAD: Drilling status through 3 levels
ProfilePage(status: status)
ProfileHeader(status: status)
ProfileLevelBadge(status: status) // Only widget that needs it!
```
### 8.2 The Solution: Direct BLoC Access with BlocBuilder
Use `BlocBuilder` to access BLoC state directly in leaf widgets:
**Correct Pattern**:
```dart
// ✅ GOOD: ProfileLevelBadge accesses ProfileCubit directly
class ProfileLevelBadge extends StatelessWidget {
const ProfileLevelBadge({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<ProfileCubit, ProfileState>(
builder: (context, state) {
final Staff? profile = state.profile;
if (profile == null) return const SizedBox.shrink();
final level = _mapStatusToLevel(profile.status);
return LevelBadgeUI(level: level);
},
);
}
}
```
### 8.3 Guidelines for Avoiding Prop Drilling
1. **Leaf Widgets Get Data from BLoC**: Widgets that need specific data should access it directly via BlocBuilder
2. **Container Widgets Stay Simple**: Parent widgets like `ProfileHeader` only manage layout and positioning
3. **No Unnecessary Props**: Don't pass data to intermediate widgets unless they need it for UI construction
4. **Single Responsibility**: Each widget should have one reason to exist
**Decision Tree**:
```
Does this widget need data?
├─ YES, and it's a leaf widget → Use BlocBuilder
├─ YES, and it's a container → Use BlocBuilder in child, not parent
└─ NO → Don't add prop to constructor
```
## 9. BLoC Lifecycle & State Emission Safety
### 9.1 The Problem: StateError After Dispose
When async operations complete after a BLoC is closed, attempting to emit state causes:
```
StateError: Cannot emit new states after calling close
```
**Root Causes**:
1. **Transient BLoCs**: `BlocProvider(create:)` creates new instance on every rebuild → disposed prematurely
2. **Singleton Disposal**: Multiple BlocProviders disposing same singleton instance
3. **Navigation During Async**: User navigates away while `loadProfile()` is still running
### 9.2 The Solution: Singleton BLoCs + Error Handler Defensive Wrapping
#### Step 1: Register as Singleton
```dart
// ✅ GOOD: ProfileCubit as singleton
i.addSingleton<ProfileCubit>(
() => ProfileCubit(useCase1, useCase2),
);
// ❌ BAD: Creates new instance each time
i.add(ProfileCubit.new);
```
#### Step 2: Use BlocProvider.value() for Singletons
```dart
// ✅ GOOD: Use singleton instance
ProfileCubit cubit = Modular.get<ProfileCubit>();
BlocProvider<ProfileCubit>.value(
value: cubit, // Reuse same instance
child: MyWidget(),
)
// ❌ BAD: Creates duplicate instance
BlocProvider<ProfileCubit>(
create: (_) => Modular.get<ProfileCubit>(), // Wrong!
child: MyWidget(),
)
```
#### Step 3: Defensive Error Handling in BlocErrorHandler Mixin
The `BlocErrorHandler<S>` mixin provides `_safeEmit()` wrapper:
**Location**: `apps/mobile/packages/core/lib/src/presentation/mixins/bloc_error_handler.dart`
```dart
void _safeEmit(void Function(S) emit, S state) {
try {
emit(state);
} on StateError catch (e) {
// Bloc was closed before emit - log and continue gracefully
developer.log(
'Could not emit state: ${e.message}. Bloc may have been disposed.',
name: runtimeType.toString(),
);
}
}
```
**Usage in Cubits/Blocs**:
```dart
Future<void> loadProfile() async {
emit(state.copyWith(status: ProfileStatus.loading));
await handleError(
emit: emit,
action: () async {
final profile = await getProfile();
emit(state.copyWith(status: ProfileStatus.loaded, profile: profile));
// ✅ If BLoC disposed before emit, _safeEmit catches StateError gracefully
},
onError: (errorKey) {
return state.copyWith(status: ProfileStatus.error);
},
);
}
```
### 9.3 Pattern Summary
| Pattern | When to Use | Risk |
|---------|------------|------|
| Singleton + BlocProvider.value() | Long-lived features (Profile, Shifts, etc.) | Low - instance persists |
| Transient + BlocProvider(create:) | Temporary widgets (Dialogs, Overlays) | Medium - requires careful disposal |
| Direct BlocBuilder | Leaf widgets needing data | Low - no registration needed |
**Remember**:
- Use **singletons** for feature-level cubits accessed from multiple pages
- Use **transient** only for temporary UI states
- Always wrap emit() in `_safeEmit()` via `BlocErrorHandler` mixin
- Test navigation away during async operations to verify graceful handling
```

View File

@@ -0,0 +1,155 @@
# 03 - Design System Usage Guide
This document defines the mandatory standards for designing and implementing user interfaces across all applications and feature packages using the shared `apps/mobile/packages/design_system`.
## 1. Introduction & Purpose
The Design System is the single source of truth for the visual identity of the project. Its purpose is to ensure UI consistency, reduce development velocity by providing reusable primitives, and eliminate "design drift" across multiple feature teams and applications.
**All UI implementation MUST consume values ONLY from the `design_system` package.**
### Core Principle
Design tokens (colors, typography, spacing, etc.) are immutable and defined centrally. Features consume these tokens but NEVER modify them. The design system maintains visual coherence across staff and client apps.
## 2. Design System Ownership & Responsibility
- **Centralized Authority**: The `apps/mobile/packages/design_system` is the owner of all brand assets, colors, typography, and core components.
- **No Local Overrides**: Feature packages (e.g., `staff_authentication`) are consumers. They are prohibited from defining their own global styles or overriding theme values locally.
- **Extension Policy**: If a required style (color, font, or icon) is missing, the developer must first add it to the `design_system` package following existing patterns before using it in a feature.
## 3. Package Structure Overview (`apps/mobile/packages/design_system`)
The package is organized to separate tokens from implementation:
- `lib/src/ui_colors.dart`: Color tokens and semantic mappings.
- `lib/src/ui_typography.dart`: Text styles and font configurations.
- `lib/src/ui_icons.dart`: Exported icon sets.
- `lib/src/ui_constants.dart`: Spacing, radius, and elevation tokens.
- `lib/src/ui_theme.dart`: Centralized `ThemeData` factory.
- `lib/src/widgets/`: Common "Smart Widgets" and reusable UI building blocks.
## 4. Colors Usage Rules
Feature packages **MUST NOT** define custom hex codes or `Color` constants.
### Usage Protocol
- **Primary Method**:Use `UiColors` from the design system for specific brand accents.
- **Naming Matching**: If an exact color is missing, use the closest existing semantic color (e.g., use `UiColors.mutedForeground` instead of a hardcoded grey).
```dart
// ❌ ANTI-PATTERN: Hardcoded color
Container(color: Color(0xFF1A2234))
// ✅ CORRECT: Design system token
Container(color: UiColors.background)
```
## 5. Typography Usage Rules
Custom `TextStyle` definitions in feature packages are **STRICTLY PROHIBITED**.
### Usage Protocol
- Use `UiTypography` from the design system for specific brand accents.
```dart
// ❌ ANTI-PATTERN: Custom TextStyle
Text('Hello', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold))
// ✅ CORRECT: Design system typography
Text('Hello', style: UiTypography.display1m)
```
## 6. Icons Usage Rules
Feature packages **MUST NOT** import icon libraries (like `lucide_icons`) directly. They should use the icons exposed via `UiIcons`.
- **Standardization**: Ensure the same icon is used for the same action across all features (e.g., always use `UiIcons.chevronLeft` for navigation).
- **Additions**: New icons must be added to the design system (only using the typedef _IconLib = LucideIcons or typedef _IconLib2 = FontAwesomeIcons; and nothing else) first to ensure they follow the project's stroke weight and sizing standards.
## 7. UI Constants & Layout Rules
Hardcoded padding, margins, and radius values are **PROHIBITED**.
- **Spacing**: Use `UiConstants.spacing` multiplied by tokens (e.g., `S`, `M`, `L`).
- **Border Radius**: Use `UiConstants.borderRadius`.
- **Elevation**: Use `UiConstants.elevation`.
```dart
// ✅ CORRECT: Spacing and Radius constants
Padding(
padding: EdgeInsets.all(UiConstants.spacingL),
child: Container(
borderRadius: BorderRadius.circular(UiConstants.radiusM),
),
)
```
## 8. Common Smart Widgets Guidelines
The design system provides "Smart Widgets" these are high-level UI components that encapsulate both styling and standard behavior.
- **Standard Widgets**: Prefer standard Flutter Material widgets (e.g., `ElevatedButton`) but styled via the central theme.
- **Custom Components**: Use `design_system` widgets for non-standard elements or wisgets that has similar design across various features, if provided.
- **Composition**: Prefer composing standard widgets over creating deep inheritance hierarchies in features.
## 9. Theme Configuration & Usage
Applications (`apps/mobile/apps/`) must initialize the theme once in the root `MaterialApp`.
```dart
MaterialApp.router(
theme: StaffTheme.light, // Mandatory: Consumption of centralized theme
// ...
)
```
**No application-level theme customization is allowed.**
## 10. Feature Development Workflow (POC → Themed)
To bridge the gap between rapid prototyping (POCs) and production-grade code, developers must follow this three-step workflow:
1. **Step 1: Structural Implementation**: Implement the UI logic and layout **exactly matching the POC**. Hardcoded values from the POC are acceptable in this transient state to ensure visual parity.
2. **Step 2: Architecture Refactor**: Immediately refactor the code to:
- Follow clean architecture principles from `apps/mobile/docs/00-agent-development-rules.md` and `01-architecture-principles.md`
- Move business logic from widgets to BLoCs and use cases
- Implement proper repository pattern with Data Connect
- Use dependency injection via Flutter Modular
3. **Step 3: Design System Integration**: Immediately refactor UI to consume design system primitives:
- Replace hex codes with `UiColors`
- Replace manual `TextStyle` with `UiTypography`
- Replace hardcoded padding/radius with `UiConstants`
- Upgrade icons to design system versions
- Use `ThemeData` from `design_system` instead of local theme overrides
## 11. Anti-Patterns & Common Mistakes
- **"Magic Numbers"**: Hardcoding `EdgeInsets.all(12.0)` instead of using design system constants.
- **Local Themes**: Using `Theme(data: ...)` to override colors for a specific section of a page.
- **Hex Hunting**: Copy-pasting hex codes from Figma or POCs into feature code.
- **Package Bypassing**: Importing `package:flutter/material.dart` and ignoring `package:design_system`.
- **Stateful Pages**: Pages with complex state logic instead of delegating to BLoCs.
- **Direct Data Queries**: Features querying Data Connect directly instead of through repositories.
- **Global State**: Using global variables for session/auth instead of `SessionStore` + `SessionListener`.
- **Hardcoded Routes**: Using `Navigator.push(context, MaterialPageRoute(...))` instead of Modular.
- **Feature Coupling**: Importing one feature package from another instead of using domain-level interfaces.
## 12. Enforcement & Review Checklist
Before any UI code is merged, it must pass this checklist:
### Design System Compliance
1. [ ] No hardcoded `Color(...)` or `0xFF...` in the feature package.
2. [ ] No custom `TextStyle(...)` definitions.
3. [ ] All spacing/padding/radius uses `UiConstants`.
4. [ ] All icons are consumed from the approved design system source.
5. [ ] The feature relies on the global `ThemeData` and does not provide local overrides.
6. [ ] The layout matches the POC visual intent while using design system primitives.
### Architecture Compliance
7. [ ] No direct Data Connect queries in widgets; all data access via repositories.
8. [ ] BLoCs handle all non-trivial state logic; pages are mostly stateless.
9. [ ] Session/auth accessed via `SessionStore` not global state.
10. [ ] Navigation uses Flutter Modular named routes.
11. [ ] Features don't import other feature packages directly.
12. [ ] All business logic in use cases, not BLoCs or widgets.
13. [ ] Repositories properly implement error handling and mapping.
14. [ ] Doc comments present on all public classes and methods.

View File

@@ -0,0 +1,285 @@
# Data Connect Connectors Pattern
## Overview
This document describes the **Data Connect Connectors** pattern implemented in the KROW mobile app. This pattern centralizes all backend query logic by mirroring backend connector structure in the mobile data layer.
## Problem Statement
**Without Connectors Pattern:**
- Each feature creates its own repository implementation
- Multiple features query the same backend connector → duplication
- When backend queries change, updates needed in multiple places
- No reusability across features
**Example Problem:**
```
staff_main/
└── data/repositories/profile_completion_repository_impl.dart ← queries staff connector
profile/
└── data/repositories/profile_repository_impl.dart ← also queries staff connector
onboarding/
└── data/repositories/personal_info_repository_impl.dart ← also queries staff connector
```
## Solution: Connectors in Data Connect Package
All backend connector queries are implemented once in a centralized location, following the backend structure.
### Structure
```
apps/mobile/packages/data_connect/lib/src/connectors/
├── staff/
│ ├── domain/
│ │ ├── repositories/
│ │ │ └── staff_connector_repository.dart (interface)
│ │ └── usecases/
│ │ └── get_profile_completion_usecase.dart
│ └── data/
│ └── repositories/
│ └── staff_connector_repository_impl.dart (implementation)
├── order/
├── user/
├── emergency_contact/
└── ...
```
**Maps to backend structure:**
```
backend/dataconnect/connector/
├── staff/
├── order/
├── user/
├── emergency_contact/
└── ...
```
## Clean Architecture Layers
Each connector follows Clean Architecture with three layers:
### Domain Layer (`connectors/{name}/domain/`)
**Repository Interface:**
```dart
// staff_connector_repository.dart
abstract interface class StaffConnectorRepository {
Future<bool> getProfileCompletion();
Future<Staff> getStaffById(String id);
// ... more queries
}
```
**Use Cases:**
```dart
// get_profile_completion_usecase.dart
class GetProfileCompletionUseCase {
GetProfileCompletionUseCase({required StaffConnectorRepository repository});
Future<bool> call() => _repository.getProfileCompletion();
}
```
**Characteristics:**
- Pure Dart, no framework dependencies
- Stable, business-focused contracts
- One interface per connector
- One use case per query or related query group
### Data Layer (`connectors/{name}/data/`)
**Repository Implementation:**
```dart
// staff_connector_repository_impl.dart
class StaffConnectorRepositoryImpl implements StaffConnectorRepository {
final DataConnectService _service;
@override
Future<bool> getProfileCompletion() async {
return _service.run(() async {
final staffId = await _service.getStaffId();
final response = await _service.connector
.getStaffProfileCompletion(id: staffId)
.execute();
return _isProfileComplete(response);
});
}
}
```
**Characteristics:**
- Implements domain repository interface
- Uses `DataConnectService` to execute queries
- Maps backend response types to domain models
- Contains mapping/transformation logic only
- Handles type safety with generated Data Connect types
## Integration Pattern
### Step 1: Feature Needs Data
Feature (e.g., `staff_main`) needs profile completion status.
### Step 2: Use Connector Repository
Instead of creating a local repository, feature uses the connector:
```dart
// staff_main_module.dart
class StaffMainModule extends Module {
@override
void binds(Injector i) {
// Register connector repository from data_connect
i.addSingleton<StaffConnectorRepository>(
StaffConnectorRepositoryImpl.new,
);
// Feature creates its own use case wrapper if needed
i.addSingleton(
() => GetProfileCompletionUseCase(
repository: i.get<StaffConnectorRepository>(),
),
);
// BLoC uses the use case
i.addSingleton(
() => StaffMainCubit(
getProfileCompletionUsecase: i.get<GetProfileCompletionUseCase>(),
),
);
}
}
```
### Step 3: BLoC Uses It
```dart
class StaffMainCubit extends Cubit<StaffMainState> {
StaffMainCubit({required GetProfileCompletionUseCase usecase}) {
_loadProfileCompletion();
}
Future<void> _loadProfileCompletion() async {
final isComplete = await _getProfileCompletionUsecase();
emit(state.copyWith(isProfileComplete: isComplete));
}
}
```
## Export Pattern
Connectors are exported from `krow_data_connect` for easy access:
```dart
// lib/krow_data_connect.dart
export 'src/connectors/staff/domain/repositories/staff_connector_repository.dart';
export 'src/connectors/staff/domain/usecases/get_profile_completion_usecase.dart';
export 'src/connectors/staff/data/repositories/staff_connector_repository_impl.dart';
```
**Features import:**
```dart
import 'package:krow_data_connect/krow_data_connect.dart';
```
## Adding New Queries to Existing Connector
When backend adds `getStaffById()` query to staff connector:
1. **Add to interface:**
```dart
abstract interface class StaffConnectorRepository {
Future<Staff> getStaffById(String id);
}
```
2. **Implement in repository:**
```dart
@override
Future<Staff> getStaffById(String id) async {
return _service.run(() async {
final response = await _service.connector
.getStaffById(id: id)
.execute();
return _mapToStaff(response.data.staff);
});
}
```
3. **Use in features:**
```dart
// Any feature can now use it
final staff = await i.get<StaffConnectorRepository>().getStaffById(id);
```
## Adding New Connector
When backend adds new connector (e.g., `order`):
1. Create directory: `apps/mobile/packages/data_connect/lib/src/connectors/order/`
2. Create domain layer with repository interface and use cases
3. Create data layer with repository implementation
4. Export from `krow_data_connect.dart`
5. Features can immediately start using it
## Benefits
✅ **No Duplication** - Query implemented once, used by many features
✅ **Single Source of Truth** - Backend change → update one place
✅ **Clean Separation** - Connector logic separate from feature logic
✅ **Reusability** - Any feature can request any connector data
✅ **Testability** - Mock the connector repo to test features
✅ **Scalability** - Easy to add new connectors as backend grows
✅ **Mirrors Backend** - Mobile structure mirrors backend structure
## Anti-Patterns
❌ **DON'T**: Implement query logic in feature repository
❌ **DON'T**: Duplicate queries across multiple repositories
❌ **DON'T**: Put mapping logic in features
❌ **DON'T**: Call `DataConnectService` directly from BLoCs
**DO**: Use connector repositories through use cases in features.
## Current Implementation
### Staff Connector
**Location**: `apps/mobile/packages/data_connect/lib/src/connectors/staff/`
**Available Queries**:
- `getProfileCompletion()` - Returns bool indicating if profile is complete
- Checks: personal info, emergency contacts, tax forms, experience (skills/industries)
**Used By**:
- `staff_main` - Guards bottom nav items requiring profile completion
**Backend Queries Used**:
- `backend/dataconnect/connector/staff/queries/profile_completion.gql`
### Shifts Connector
**Location**: `apps/mobile/packages/data_connect/lib/src/connectors/shifts/`
**Available Queries**:
- `listShiftRolesByVendorId()` - Fetches shifts for a specific vendor with status mapping
- `applyForShifts()` - Handles shift application with error tracking
**Backend Queries Used**:
- `backend/dataconnect/connector/shifts/queries/list_shift_roles_by_vendor.gql`
- `backend/dataconnect/connector/shifts/mutations/apply_for_shifts.gql`
## Future Expansion
As the app grows, additional connectors will be added:
- `order_connector_repository` (queries from `backend/dataconnect/connector/order/`)
- `user_connector_repository` (queries from `backend/dataconnect/connector/user/`)
- `emergency_contact_connector_repository` (queries from `backend/dataconnect/connector/emergencyContact/`)
- etc.
Each following the same Clean Architecture pattern implemented for Staff Connector.

View File

@@ -0,0 +1,362 @@
# 📊 Use Case Completion Audit
**Generated:** 2026-02-23
**Auditor Role:** System Analyst / Flutter Architect
**Source of Truth:** `docs/ARCHITECTURE/client-mobile-application/use-case.md`, `docs/ARCHITECTURE/staff-mobile-application/use-case.md`, `docs/ARCHITECTURE/system-bible.md`, `docs/ARCHITECTURE/architecture.md`
**Codebase Checked:** `apps/mobile/packages/features/` (real app) vs `apps/mobile/prototypes/` (prototypes)
---
## 📌 How to Read This Document
| Symbol | Meaning |
|:---:|:--- |
| ✅ | Fully implemented in the real app |
| 🟡 | Partially implemented — UI or domain exists but logic is incomplete |
| ❌ | Defined in docs but entirely missing in the real app |
| ⚠️ | Exists in prototype but has **not** been migrated to the real app |
| 🚫 | Exists in real app code but is **not** documented in use cases |
---
## 🧑‍💼 CLIENT APP
### Feature Module: `authentication`
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 1.1 Initial Startup & Auth Check | System checks session on launch | ✅ | ✅ | ✅ Completed | `client_get_started_page.dart` handles auth routing via Modular. |
| 1.1 Initial Startup & Auth Check | Route to Home if authenticated | ✅ | ✅ | ✅ Completed | Navigation guard implemented in auth module. |
| 1.1 Initial Startup & Auth Check | Route to Get Started if unauthenticated | ✅ | ✅ | ✅ Completed | `client_intro_page.dart` + `client_get_started_page.dart` both exist. |
| 1.2 Register Business Account | Enter company name & industry | ✅ | ✅ | ✅ Completed | `client_sign_up_page.dart` fully implemented. |
| 1.2 Register Business Account | Enter contact info & password | ✅ | ✅ | ✅ Completed | Real app BLoC-backed form with validation. |
| 1.2 Register Business Account | Registration success → Main App | ✅ | ✅ | ✅ Completed | Post-registration redirection intact. |
| 1.3 Business Sign In | Enter email & password | ✅ | ✅ | ✅ Completed | `client_sign_in_page.dart` fully implemented. |
| 1.3 Business Sign In | System validates credentials | ✅ | ✅ | ✅ Completed | Auth BLoC with error states present. |
| 1.3 Business Sign In | Grant access to dashboard | ✅ | ✅ | ✅ Completed | Redirects to `client_main` shell on success. |
---
### Feature Module: `orders` (Order Management)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 2.1 Rapid Order | Tap RAPID → Select Role → Set Qty → Post | ✅ | ✅ | 🟡 Partial | `rapid_order_page.dart` & `RapidOrderBloc` exist with full view. Voice recognition is **simulated** (UI only, no actual voice API). |
| 2.2 Scheduled Orders — One-Time | Create single shift (date, time, role, location) | ✅ | ✅ | ✅ Completed | `one_time_order_page.dart` fully implemented with BLoC. |
| 2.2 Scheduled Orders — Recurring | Create recurring shifts (e.g., every Monday) | ✅ | ✅ | ✅ Completed | `recurring_order_page.dart` fully implemented. |
| 2.2 Scheduled Orders — Permanent | Long-term staffing placement | ✅ | ✅ | ✅ Completed | `permanent_order_page.dart` fully implemented. |
| 2.2 Scheduled Orders | Review cost before posting | ✅ | ✅ | 🟡 Partial | Order summary shown, but real-time cost calculation depends on backend. |
| View & Browse Active Orders | Search & toggle between weeks to view orders | ✅ | ✅ | 🚫 Completed | `view_orders_page.dart` exists with `ViewOrderCard`. Added `eventName` visibility. |
| Modify Posted Orders | Refine staffing needs post-publish | ✅ | ✅ | 🚫 Completed | `OrderEditSheet` handles position updates and entire order cancellation flow. |
---
### Feature Module: `client_coverage` (Operations & Workforce Management)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 3.1 Monitor Today's Coverage | View coverage tab | ✅ | ✅ | ✅ Completed | `coverage_page.dart` exists with coverage header and shift list. |
| 3.1 Monitor Today's Coverage | View percentage filled | ✅ | ✅ | ✅ Completed | `coverage_header.dart` shows fill rate. |
| 3.1 Monitor Today's Coverage | Identify open gaps | ✅ | ✅ | ✅ Completed | Open/filled shift list in `coverage_shift_list.dart`. |
| 3.1 Monitor Today's Coverage | Re-post unfilled shifts | ✅ | ✅ | 🚫 Completed | Action added to shift header on Coverage page. |
| 3.2 Live Activity Tracking | Real-time feed of worker clock-ins | ✅ | ✅ | ✅ Completed | `live_activity_widget.dart` wired to Data Connect. |
| 3.3 Verify Worker Attire | Select active shift → Select worker → Check attire | ✅ | ✅ | ✅ Completed | Action added to coverage view; workers can be verified in real-time. |
| 3.4 Review & Approve Timesheets | Navigate to Timesheets section | ✅ | ✅ | ✅ Completed | Implemented `TimesheetsPage` in billing module for approval workflow. |
| 3.4 Review & Approve Timesheets | Review actual vs. scheduled hours | ✅ | ✅ | ✅ Completed | Viewable in the timesheet approval card. |
| 3.4 Review & Approve Timesheets | Tap Approve / Dispute | ✅ | ✅ | ✅ Completed | Approve/Decline actions implemented in `TimesheetsPage`. |
---
### Feature Module: `reports` (Reports & Analytics)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 4.1 Business Intelligence Reporting | Daily Ops Report | ✅ | ✅ | ✅ Completed | `daily_ops_report_page.dart` fully implemented. |
| 4.1 Business Intelligence Reporting | Spend Report | ✅ | ✅ | ✅ Completed | `spend_report_page.dart` fully implemented. |
| 4.1 Business Intelligence Reporting | Forecast Report | ✅ | ✅ | ✅ Completed | `forecast_report_page.dart` fully implemented. |
| 4.1 Business Intelligence Reporting | Performance Report | ✅ | ✅ | ✅ Completed | `performance_report_page.dart` fully implemented. |
| 4.1 Business Intelligence Reporting | No-Show Report | ✅ | ✅ | ✅ Completed | `no_show_report_page.dart` fully implemented. |
| 4.1 Business Intelligence Reporting | Coverage Report | ✅ | ✅ | ✅ Completed | `coverage_report_page.dart` fully implemented. |
---
### Feature Module: `billing` (Billing & Administration)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 5.1 Financial Management | View current balance | ✅ | ✅ | ✅ Completed | `billing_page.dart` shows `currentBill` and period billing. |
| 5.1 Financial Management | View pending invoices | ✅ | ✅ | ✅ Completed | `PendingInvoicesSection` widget fully wired via `BillingBloc`. |
| 5.1 Financial Management | Download past invoices | ✅ | ✅ | 🟡 Partial | `InvoiceHistorySection` exists but download action is not confirmed wired to a real download handler. |
| 5.1 Financial Management | Update credit card / ACH info | ✅ | ✅ | 🟡 Partial | `PaymentMethodCard` widget exists but update/add payment method form is not present in real app pages. |
---
### Feature Module: `hubs` (Manage Business Locations)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 5.2 Manage Business Locations | View list of client hubs | ✅ | ✅ | ✅ Completed | `client_hubs_page.dart` fully implemented. |
| 5.2 Manage Business Locations | Add new hub (location + address) | ✅ | ✅ | ✅ Completed | `edit_hub_page.dart` serves create + edit. |
| 5.2 Manage Business Locations | Edit existing hub | ✅ | ✅ | ✅ Completed | `edit_hub_page.dart` + `hub_details_page.dart` both present. |
---
### Feature Module: `settings` (Profile & Settings)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 5.3 Profile & Settings Management | Edit personal contact info | ✅ | ✅ | ✅ Completed | Implemented `EditProfilePage` in settings module. |
| 5.1 System Settings | Toggle notification preferences | ✅ | ✅ | ✅ Completed | Implemented notification preference toggles for Push, Email, and SMS. |
---
### Feature Module: `home` (Home Tab)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| Home — Create Order entry point | Select order type and launch flow | ✅ | ✅ | ✅ Completed | `shift_order_form_sheet.dart` (47KB) orchestrates all order types from the home tab. |
| Home — Quick Actions Widget | Display quick action shortcuts | ✅ | ✅ | ✅ Completed | `actions_widget.dart` present. |
| Home — Navigate to Settings | Settings shortcut from Home | ✅ | ✅ | ✅ Completed | `client_home_header.dart` has settings navigation. |
| Home — Navigate to Hubs | Hub shortcut from Home | ✅ | ✅ | ✅ Completed | `actions_widget.dart` navigates to hubs. |
| Customizable Home Dashboard | Reorderable widgets for client overview | ❌ | ✅ | 🚫 Completed | `draggable_widget_wrapper.dart` + `reorder_widget.dart` + `dashboard_widget_builder.dart` exist in real app. |
| Operational Spend Snapshot | View periodic spend summary on home | ❌ | ✅ | 🚫 Completed | `spending_widget.dart` implemented on home dashboard. |
| Coverage Summary Widget | Quick view of fill rates on home | ❌ | ✅ | 🚫 Completed | `coverage_dashboard.dart` widget embedded on home. |
| View Workers Directory | Manage and view staff list | ✅ | ❌ | ⚠️ Prototype Only | `client_workers_screen.dart` in prototype. No `workers` feature package in real app. |
---
---
## 👷 STAFF APP
### Feature Module: `authentication`
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 1.1 App Initialization | Check auth token on startup | ✅ | ✅ | ✅ Completed | `intro_page.dart` + `get_started_page.dart` handle routing. |
| 1.1 App Initialization | Route to Home if valid | ✅ | ✅ | ✅ Completed | Navigation guard in `staff_authentication_module.dart`. |
| 1.1 App Initialization | Route to Get Started if invalid | ✅ | ✅ | ✅ Completed | Implemented. |
| 1.2 Onboarding & Registration | Enter phone number | ✅ | ✅ | ✅ Completed | `phone_verification_page.dart` fully implemented. |
| 1.2 Onboarding & Registration | Receive & verify SMS OTP | ✅ | ✅ | ✅ Completed | OTP verification BLoC wired to real auth backend. |
| 1.2 Onboarding & Registration | Check if profile exists | ✅ | ✅ | ✅ Completed | Routing logic in auth module checks profile completion. |
| 1.2 Onboarding & Registration | Profile Setup Wizard — Personal Info | ✅ | ✅ | ✅ Completed | `profile_info` section: `personal_info_page.dart` fully implemented. |
| 1.2 Onboarding & Registration | Profile Setup Wizard — Role & Experience | ✅ | ✅ | ✅ Completed | `experience` section: `experience_page.dart` implemented. |
| 1.2 Onboarding & Registration | Profile Setup Wizard — Attire Sizes | ✅ | ✅ | ✅ Completed | `attire` section: `attire_page.dart` implemented via `profile_sections/onboarding/attire`. |
| 1.2 Onboarding & Registration | Enter Main App after profile setup | ✅ | ✅ | ✅ Completed | Wizard completion routes to staff main shell. |
| Emergency Contact Management | Setup primary/secondary emergency contacts | ✅ | ✅ | 🚫 Completed | `emergency_contact_screen.dart` in both prototype and real app. |
---
### Feature Module: `home` (Job Discovery)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 2.1 Browse & Filter Jobs | View available jobs list | ✅ | ✅ | ✅ Completed | `find_shifts_tab.dart` in `shifts` renders all available jobs. Fully localized via `core_localization`. |
| 2.1 Browse & Filter Jobs | Filter by Role | ✅ | ✅ | 🟡 Partial | Search by title/location/client name is implemented. Filter by **role** (as in job category) uses type-based tabs (one-day, multi-day, long-term) rather than role selection. |
| 2.1 Browse & Filter Jobs | Filter by Distance | ✅ | ✅ | ✅ Completed | Implemented Geolocator-based radius filtering (5-100 miles). Fixed bug where filter was bypassed for 'All' tab. |
| 2.1 Browse & Filter Jobs | View job card details (Pay, Location, Requirements) | ✅ | ✅ | ✅ Completed | `MyShiftCard` + `shift_details_page.dart` with full shift info. Added `endDate` support for multi-day shifts. |
| 2.3 Set Availability | Select dates/times → Save preferences | ✅ | ✅ | ✅ Completed | `availability_page.dart` fully implemented with `AvailabilityBloc`. |
| Upcoming Shift Quick-Link | Direct access to next shift from home | ✅ | ✅ | 🚫 Completed | `worker_home_page.dart` shows upcoming shifts banner. |
---
### Feature Module: `shifts` (Find Shifts + My Schedule)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 2.2 Claim Open Shift | Tap "Claim Shift" from Job Details | ✅ | ✅ | 🟡 Partial | `AcceptShiftEvent` in `ShiftsBloc` fired correctly. Backend check wired via `ShiftDetailsBloc`. |
| 2.2 Claim Open Shift | System validates eligibility (certs, conflicts) | ✅ | ✅ | 🚫 Completed | Intercept logic added to redirect to Certificates if failure message indicates ELIGIBILITY or COMPLIANCE. |
| 2.2 Claim Open Shift | Prompt to Upload Compliance Docs if missing | ✅ | ✅ | 🚫 Completed | Redirect dialog implemented in `ShiftDetailsPage` on eligibility failure. |
| 3.1 View Schedule | View list of claimed shifts (My Shifts tab) | ✅ | ✅ | ✅ Completed | `my_shifts_tab.dart` fully implemented with shift cards. |
| 3.1 View Schedule | View Shift Details | ✅ | ✅ | ✅ Completed | `shift_details_page.dart` with header, location map, schedule summary, stats. Corrected weekday mapping and added `endDate`. |
| Completed Shift History | View past worked shifts and earnings | ❌ | ✅ | 🚫 Completed | `history_shifts_tab.dart` fully wired in `shifts_page.dart`. |
| Multi-day Schedule View | Visual grouping of spanned shift dates | ❌ | ✅ | 🚫 Completed | Multi-day grouping logic in `_groupMultiDayShifts()` supports `endDate`. |
---
### Feature Module: `clock_in` (Shift Execution)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 3.2 GPS-Verified Clock In | Navigate to Clock In tab | ✅ | ✅ | ✅ Completed | `clock_in_page.dart` is a dedicated tab. |
| 3.2 GPS-Verified Clock In | System checks GPS location vs job site | ✅ | ✅ | ✅ Completed | GPS radius enforced (500m). `SwipeToCheckIn` is disabled until within range. |
| 3.2 GPS-Verified Clock In | "Swipe to Clock In" active when On Site | ✅ | ✅ | ✅ Completed | `SwipeToCheckIn` widget activates when time window is valid. |
| 3.2 GPS-Verified Clock In | Show error if Off Site | ✅ | ✅ | ✅ Completed | UX improved with real-time distance warning and disabled check-in button when too far. |
| 3.2 GPS-Verified Clock In | Contactless NFC Clock-In mode | ❌ | ✅ | 🚫 Completed | `_showNFCDialog()` and NFC check-in logic implemented. |
| 3.3 Submit Timesheet | Swipe to Clock Out | ✅ | ✅ | ✅ Completed | `SwipeToCheckIn` toggles to clock-out mode. `CheckOutRequested` event fires. |
| 3.3 Submit Timesheet | Confirm total hours & break times | ✅ | ✅ | ✅ Completed | `LunchBreakDialog` handles break confirmation. Attire photo captured during clock-in. |
| 3.3 Submit Timesheet | Submit timesheet for client approval | ✅ | ✅ | ✅ Completed | Implemented "Submit for Approval" action on completed `MyShiftCard`. |
---
### Feature Module: `payments` (Financial Management)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 4.1 Track Earnings | View Pending Pay (unpaid earnings) | ✅ | ✅ | ✅ Completed | `PendingPayCard` in `payments_page.dart` shows `pendingEarnings`. |
| 4.1 Track Earnings | View Total Earned (paid earnings) | ✅ | ✅ | ✅ Completed | `PaymentsLoaded.summary.totalEarnings` displayed on header. |
| 4.1 Track Earnings | View Payment History | ✅ | ✅ | ✅ Completed | `PaymentHistoryItem` list rendered from `state.history`. |
| 4.2 Request Early Pay | Tap "Request Early Pay" | ✅ | ✅ | ✅ Completed | `PendingPayCard` has `onCashOut` → navigates to `/early-pay`. |
| 4.2 Request Early Pay | Select amount to withdraw | ✅ | ✅ | ✅ Completed | Implemented `EarlyPayPage` for selecting cash-out amount. |
| 4.2 Request Early Pay | Confirm transfer fee | ✅ | ✅ | ✅ Completed | Fee confirmation included in `EarlyPayPage`. |
| 4.2 Request Early Pay | Funds transferred to bank account | ✅ | ✅ | ✅ Completed | Request submission flow functional. |
---
### Feature Module: `profile` + `profile_sections` (Profile & Compliance)
| Use Case | Sub-Use Case | Prototype | Real App | Status | Notes |
|:---|:---|:---:|:---:|:---:|:---|
| 5.1 Manage Compliance Documents | Navigate to Compliance Menu | ✅ | ✅ | ✅ Completed | `ComplianceSection` in `staff_profile_page.dart` links to sub-modules. |
| 5.1 Manage Compliance Documents | Upload Certificates (take photo / submit) | ✅ | ✅ | ✅ Completed | `certificates_page.dart` + `certificate_upload_modal.dart` fully implemented. |
| 5.1 Manage Compliance Documents | View/Manage Identity Documents | ✅ | ✅ | ✅ Completed | `documents_page.dart` with `documents_progress_card.dart`. |
| 5.2 Manage Tax Forms | Complete W-4 digitally & submit | ✅ | ✅ | ✅ Completed | `form_w4_page.dart` + `FormW4Cubit` fully implemented. |
| 5.2 Manage Tax Forms | Complete I-9 digitally & submit | ✅ | ✅ | ✅ Completed | `form_i9_page.dart` + `FormI9Cubit` fully implemented. |
| 5.3 Krow University Training | Navigate to Krow University | ✅ | ❌ | ❌ Not Implemented | `krow_university_screen.dart` exists **only** in prototype. No `krow_university` or training package in real app feature modules. |
| 5.3 Krow University Training | Select Module → Watch Video / Take Quiz | ✅ | ❌ | ⚠️ Prototype Only | Fully prototyped (courses, categories, XP tracking). Not migrated at all. |
| 5.3 Krow University Training | Earn Badge | ✅ | ❌ | ⚠️ Prototype Only | Prototype only. |
| 5.4 Account Settings | Update Bank Details | ✅ | ✅ | ✅ Completed | `bank_account_page.dart` + `BankAccountCubit` in `profile_sections/finances/staff_bank_account`. |
| 5.4 Account Settings | View Benefits | ✅ | ❌ | ⚠️ Prototype Only | `benefits_screen.dart` exists only in prototype. No `benefits` package in real app. |
| 5.4 Account Settings | Access Support / FAQs | ✅ | ✅ | ✅ Completed | `faqs_page.dart` with `FAQsBloc` and search in `profile_sections/support/faqs`. |
| Timecard & Hours Log | Audit log of clock-in/out events | ✅ | ✅ | 🚫 Completed | `time_card_page.dart` in `profile_sections/finances/time_card`. |
| Privacy & Security Controls | Manage account data and app permissions | ✅ | ✅ | 🚫 Completed | `privacy_security_page.dart` in `support/privacy_security`. |
| Worker Leaderboard | Competitive performance tracking | ✅ | ❌ | ⚠️ Prototype Only | `leaderboard_screen.dart` in prototype. No real app equivalent. |
| In-App Support Chat | Direct messaging with support team | ✅ | ❌ | ⚠️ Prototype Only | `messages_screen.dart` in prototype. Not in real app. |
---
---
## 1⃣ Summary Statistics
### Client App
| Metric | Count |
|:---|:---:|
| **Total documented use cases (sub-use cases)** | 38 |
| ✅ Fully Implemented | 21 |
| 🟡 Partially Implemented | 6 |
| ❌ Not Implemented | 1 |
| ⚠️ Prototype Only (not migrated) | 1 |
| 🚫 Completed (Extra) | 6 |
**Client App Completion Rate (fully implemented):** ~76%
**Client App Implementation Coverage (completed + partial):** ~94%
---
### Staff App
| Metric | Count |
|:---|:---:|
| **Total documented use cases (sub-use cases)** | 45 |
| ✅ Fully Implemented | 23 |
| 🟡 Partially Implemented | 6 |
| ❌ Not Implemented | 2 |
| ⚠️ Prototype Only (not migrated) | 6 |
| 🚫 Completed (Extra) | 8 |
**Staff App Completion Rate (fully implemented):** ~71%
**Staff App Implementation Coverage (completed + partial):** ~85%
---
## 2⃣ Critical Gaps
The following are **high-priority missing flows** that block core business value:
1. **Staff: Krow University & Benefits**
Several modules exist in the prototype but are missing in the real app, including training Modules, XP tracking, and Benefits views.
---
2. **Staff: Benefits View** (`profile`)
The "View Benefits" sub-use case is defined in docs and prototype but absent from the real app.
---
## 3⃣ Architecture Drift
The following inconsistencies between the system design documents and the actual real app implementation were identified:
---
### AD-01: GPS Clock-In Enforcement vs. Time-Window Gate
**Docs Say:** `system-bible.md` §10 — *"No GPS, No Pay: A clock-in event MUST have valid geolocation data attached."*
**Reality:****Resolved**. The real `clock_in_page.dart` now enforces a **500m GPS radius check**. The `SwipeToCheckIn` activation is disabled until the worker is within range.
---
### AD-02: Compliance Gate on Shift Claim
**Docs Say:** `use-case.md` (Staff) §2.2 — *"System validates eligibility (Certificates, Conflicts). If missing requirements, system prompts to Upload Compliance Docs."*
**Reality:****Resolved**. Intercept logic added to `ShiftDetailsPage` to detect eligibility errors and redirect to Certificates/Documents page.
---
### AD-03: "Split Brain" Logic Risk — Client-Side Calculations
**Docs Say:** `system-bible.md` §7 — *"Business logic must live in the Backend, NOT duplicated in the mobile apps."*
**Reality:** `_groupMultiDayShifts()` in `find_shifts_tab.dart` and cost calculation logic in `shift_order_form_sheet.dart` (47KB file) perform grouping/calculation logic on the client. This is a drift from the single-source-of-truth principle. The `shift_order_form_sheet.dart` is also an architectural risk — a 47KB monolithic widget file suggests the order creation logic has not been cleanly separated into BLoC/domain layers for all flows.
---
### AD-04: Timesheet Lifecycle Disconnected
**Docs Say:** `architecture.md` §3 & `system-bible.md` §5 — Approved timesheets trigger payment scheduling. The cycle is: `Clock Out → Timesheet → Client Approve → Payment Processed`.
**Reality:****Resolved**. Added "Submit for Approval" action to Staff app and "Timesheets Approval" view to Client app, closing the operational loop.
---
### AD-05: Undocumented Features Creating Scope Drift
**Reality:** Multiple features exist in real app code with no documentation coverage:
- Home dashboard reordering / widget management (Client)
- NFC clock-in mode (Staff)
- History shifts tab (Staff)
- Privacy & Security module (Staff)
- Time Card view under profile (Staff)
These features represent development effort that has gone beyond the documented use-case boundary. Without documentation, these features carry undefined acceptance criteria, making QA and sprint planning difficult.
---
### AD-06: `client_workers_screen` (View Workers) — Missing Migration
**Docs Show:** `architecture.md` §A and the use-case diagram reference `ViewWorkers` from the Home tab.
**Reality:** `client_workers_screen.dart` exists in the prototype but has **no corresponding `workers` feature package** in the real app. This breaks a documented Home Tab flow.
---
### AD-07: Benefits Feature — Defined in Docs, Absent in Real App
**Docs Say:** `use-case.md` (Staff) §5.4 — *"View Benefits"* is a sub-use case.
**Reality:** `benefits_screen.dart` is fully built in the prototype (insurance, earned time off, etc.) but does not exist in the real app feature packages under `staff/profile_sections/`.
---
## 4⃣ Orphan Prototype Screens (Not Migrated)
The following screens exist **only** in the prototypes and have no real-app equivalent:
### Client Prototype
| Screen | Path |
|:---|:---|
| Workers List | `client/client_workers_screen.dart` |
| Verify Worker Attire | `client/verify_worker_attire_screen.dart` |
### Staff Prototype
| Screen | Path |
|:---|:---|
| Benefits | `worker/benefits_screen.dart` |
| Krow University | `worker/worker_profile/level_up/krow_university_screen.dart` |
| Leaderboard | `worker/worker_profile/level_up/leaderboard_screen.dart` |
| Training Modules | `worker/worker_profile/level_up/trainings_screen.dart` |
| In-App Messages | `worker/worker_profile/support/messages_screen.dart` |
---
## 5⃣ Recommendations for Sprint Planning
### Sprint Focus Areas (Priority Order)
| 🟠 P2 | Migrate Krow University training module from prototype | Large |
| 🟠 P2 | Migrate Benefits view from prototype | Medium |
| 🟡 P3 | Migrate Workers List to real app (`client/workers`) | Medium |
| 🟡 P3 | Formally document undocumented features (NFC, History tab, etc.) | Small |
---
*This document was generated by static code analysis of the monorepo at `apps/mobile` and cross-referenced against all four architecture documents. No runtime behavior was observed. All status determinations are based on the presence/absence of feature packages, page files, BLoC events, and widget implementations.*

266
docs/api-contracts.md Normal file
View File

@@ -0,0 +1,266 @@
# KROW Workforce API Contracts
This document captures all API contracts used by the Staff and Client mobile applications. It serves as a single reference document to understand what each endpoint does, its expected inputs, returned outputs, and any non-obvious details.
---
## Staff Application
### Authentication / Onboarding Pages (Get Started, Intro, Phone Verification, Profile Setup, Personal Info)
#### Setup / User Validation API
| Field | Description |
|---|---|
| **Endpoint name** | `/getUserById` |
| **Purpose** | Retrieves the base user profile to determine authentication status and role access (e.g., if user is STAFF). |
| **Operation** | Query |
| **Inputs** | `id: UUID!` (Firebase UID) |
| **Outputs** | `User { id, email, phone, role }` |
| **Notes** | Required after OTP verification to route users. |
#### Create Default User API
| Field | Description |
|---|---|
| **Endpoint name** | `/createUser` |
| **Purpose** | Inserts a base user record into the system during initial signup. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `role: UserBaseRole` |
| **Outputs** | `id` of newly created User |
| **Notes** | Used explicitly during the "Sign Up" flow if the user doesn't exist. |
#### Get Staff Profile API
| Field | Description |
|---|---|
| **Endpoint name** | `/getStaffByUserId` |
| **Purpose** | Finds the specific Staff record associated with the base user ID. |
| **Operation** | Query |
| **Inputs** | `userId: UUID!` |
| **Outputs** | `Staffs { id, userId, fullName, email, phone, photoUrl, status }` |
| **Notes** | Needed to verify if a complete staff profile exists before fully authenticating. |
#### Update Staff Profile API
| Field | Description |
|---|---|
| **Endpoint name** | `/updateStaff` |
| **Purpose** | Saves onboarding data across Personal Info, Experience, and Preferred Locations pages. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `fullName`, `email`, `phone`, `addres`, etc. |
| **Outputs** | `id` |
| **Notes** | Called incrementally during profile setup wizard. |
### Home Page (worker_home_page.dart) & Benefits Overview
#### Load Today/Tomorrow Shifts
| Field | Description |
|---|---|
| **Endpoint name** | `/getApplicationsByStaffId` |
| **Purpose** | Retrieves applications (shifts) assigned to the current staff member within a specific date range. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!`, `dayStart: Timestamp`, `dayEnd: Timestamp` |
| **Outputs** | `Applications { shift, shiftRole, status, createdAt }` |
| **Notes** | The frontend filters the query response for `CONFIRMED` applications to display "Today's" and "Tomorrow's" shifts. |
#### List Recommended Shifts
| Field | Description |
|---|---|
| **Endpoint name** | `/listShifts` |
| **Purpose** | Fetches open shifts that are available for the staff to apply to. |
| **Operation** | Query |
| **Inputs** | None directly mapped, but filters OPEN shifts purely on the client side at the time. |
| **Outputs** | `Shifts { id, title, orderId, cost, location, startTime, endTime, status }` |
| **Notes** | Limits output to 10 on the frontend. Should ideally rely on a `$status: OPEN` parameter. |
#### Benefits Summary API
| Field | Description |
|---|---|
| **Endpoint name** | `/listBenefitsDataByStaffId` |
| **Purpose** | Retrieves accrued benefits (e.g., Sick time, Vacation) to display on the home screen. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `BenefitsDatas { vendorBenefitPlan { title, total }, current }` |
| **Notes** | Calculates `usedHours = total - current`. |
### Find Shifts / Shift Details Pages (shifts_page.dart)
#### List Available Shifts Filtered
| Field | Description |
|---|---|
| **Endpoint name** | `/filterShifts` |
| **Purpose** | Used to fetch Open Shifts in specific regions when the worker searches in the "Find Shifts" tab. |
| **Operation** | Query |
| **Inputs** | `$status: ShiftStatus`, `$dateFrom: Timestamp`, `$dateTo: Timestamp` |
| **Outputs** | `Shifts { id, title, location, cost, durationDays, order { business, vendor } }` |
| **Notes** | - |
#### Get Shift Details
| Field | Description |
|---|---|
| **Endpoint name** | `/getShiftById` |
| **Purpose** | Gets deeper details for a single shift including exact uniform/managers needed. |
| **Operation** | Query |
| **Inputs** | `id: UUID!` |
| **Outputs** | `Shift { id, title, hours, cost, locationAddress, workersNeeded ... }` |
| **Notes** | - |
#### Apply To Shift
| Field | Description |
|---|---|
| **Endpoint name** | `/createApplication` |
| **Purpose** | Worker submits an intent to take an open shift. |
| **Operation** | Mutation |
| **Inputs** | `shiftId`, `staffId`, `status: APPLIED` |
| **Outputs** | `Application ID` |
| **Notes** | A shift status will switch to `CONFIRMED` via admin approval. |
### Availability Page (availability_page.dart)
#### Get Default Availability
| Field | Description |
|---|---|
| **Endpoint name** | `/listStaffAvailabilitiesByStaffId` |
| **Purpose** | Fetches the standard Mon-Sun recurring availability for a staff member. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `StaffAvailabilities { dayOfWeek, isAvailable, startTime, endTime }` |
| **Notes** | - |
#### Update Availability
| Field | Description |
|---|---|
| **Endpoint name** | `/updateStaffAvailability` (or `createStaffAvailability`) |
| **Purpose** | Upserts availability preferences. |
| **Operation** | Mutation |
| **Inputs** | `staffId`, `dayOfWeek`, `isAvailable`, `startTime`, `endTime` |
| **Outputs** | `id` |
| **Notes** | Called individually per day edited. |
### Payments Page (payments_page.dart)
#### Get Recent Payments
| Field | Description |
|---|---|
| **Endpoint name** | `/listRecentPaymentsByStaffId` |
| **Purpose** | Loads the history of earnings and timesheets completed by the staff. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `Payments { amount, processDate, shiftId, status }` |
| **Notes** | Displays historical metrics under Earnings tab. |
### Compliance / Profiles (Agreements, W4, I9, Documents)
#### Get Tax Forms
| Field | Description |
|---|---|
| **Endpoint name** | `/getTaxFormsByStaffId` |
| **Purpose** | Check the filing status of I9 and W4 forms. |
| **Operation** | Query |
| **Inputs** | `staffId: UUID!` |
| **Outputs** | `TaxForms { formType, isCompleted, updatedDate }` |
| **Notes** | Required for staff to be eligible for shifts. |
#### Update Tax Forms
| Field | Description |
|---|---|
| **Endpoint name** | `/updateTaxForm` |
| **Purpose** | Submits state and filing for the given tax form type. |
| **Operation** | Mutation |
| **Inputs** | `id`, `dataPoints...` |
| **Outputs** | `id` |
| **Notes** | Updates compliance state. |
---
## Client Application
### Authentication / Intro (Sign In, Get Started)
#### Client User Validation API
| Field | Description |
|---|---|
| **Endpoint name** | `/getUserById` |
| **Purpose** | Retrieves the base user profile to determine authentication status and role access (e.g., if user is BUSINESS). |
| **Operation** | Query |
| **Inputs** | `id: UUID!` (Firebase UID) |
| **Outputs** | `User { id, email, phone, userRole }` |
| **Notes** | Must check if `userRole == BUSINESS` or `BOTH`. |
#### Get Business Profile API
| Field | Description |
|---|---|
| **Endpoint name** | `/getBusinessByUserId` |
| **Purpose** | Maps the authenticated user to their client business context. |
| **Operation** | Query |
| **Inputs** | `userId: UUID!` |
| **Outputs** | `Business { id, businessName, email, contactName }` |
| **Notes** | Used to set the working scopes (Business ID) across the entire app. |
### Hubs Page (client_hubs_page.dart, edit_hub.dart)
#### List Hubs
| Field | Description |
|---|---|
| **Endpoint name** | `/listTeamHubsByBusinessId` |
| **Purpose** | Fetches the primary working sites (Hubs) for a client. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `TeamHubs { id, hubName, address, contact, active }` |
| **Notes** | - |
#### Update / Delete Hub
| Field | Description |
|---|---|
| **Endpoint name** | `/updateTeamHub` / `/deleteTeamHub` |
| **Purpose** | Edits or archives a Hub location. |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `hubName`, `address`, etc (for Update) |
| **Outputs** | `id` |
| **Notes** | - |
### Orders Page (create_order, view_orders)
#### Create Order
| Field | Description |
|---|---|
| **Endpoint name** | `/createOrder` |
| **Purpose** | The client submits a new request for temporary staff (can result in multiple Shifts generated on the backend). |
| **Operation** | Mutation |
| **Inputs** | `businessId`, `eventName`, `orderType`, `status` |
| **Outputs** | `id` (Order ID) |
| **Notes** | This creates an order. Shift instances are subsequently created through secondary mutations. |
#### List Orders
| Field | Description |
|---|---|
| **Endpoint name** | `/getOrdersByBusinessId` |
| **Purpose** | Retrieves all ongoing and past staff requests from the client. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `Orders { id, eventName, shiftCount, status }` |
| **Notes** | - |
### Billing Pages (billing_page.dart, pending_invoices)
#### List Invoices
| Field | Description |
|---|---|
| **Endpoint name** | `/listInvoicesByBusinessId` |
| **Purpose** | Fetches "Pending", "Paid", and "Disputed" invoices for the client to review. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `Invoices { id, amountDue, issueDate, status }` |
| **Notes** | Used across all Billing view tabs. |
#### Mark Invoice
| Field | Description |
|---|---|
| **Endpoint name** | `/updateInvoice` |
| **Purpose** | Marks an invoice as disputed or pays it (changes status). |
| **Operation** | Mutation |
| **Inputs** | `id: UUID!`, `status: InvoiceStatus` |
| **Outputs** | `id` |
| **Notes** | Disputing usually involves setting a memo or flag. |
### Reports Page (reports_page.dart)
#### Get Coverage Stats
| Field | Description |
|---|---|
| **Endpoint name** | `/getCoverageStatsByBusiness` |
| **Purpose** | Provides data on fulfillments rates vs actual requests. |
| **Operation** | Query |
| **Inputs** | `businessId: UUID!` |
| **Outputs** | `Stats { totalRequested, totalFilled, percentage }` |
| **Notes** | Driven mostly by aggregated backend views. |
---
*This document reflects the current state of Data Connect definitions implemented across the frontend and mapped manually by reviewing Repository and UI logic.*

BIN
docs/available_gql.txt Normal file

Binary file not shown.

View File

@@ -0,0 +1,87 @@
# 📱 Research: Flutter Integration Testing Evaluation
**Issue:** #533
**Focus:** Maestro vs. Marionette MCP (LeanCode)
**Status:** ✅ Completed
**Target Apps:** `KROW Client App` & `KROW Staff App`
---
## 1. Executive Summary & Recommendation
Following a technical spike implementing full authentication flows (Login/Signup) for both KROW platforms, **Maestro is the recommended integration testing framework.**
While **Marionette MCP** offers an innovative LLM-driven approach for exploratory debugging, it lacks the determinism required for a production-grade CI/CD pipeline. Maestro provides the stability, speed, and native OS interaction necessary to gate our releases effectively.
### Why Maestro Wins for KROW:
* **Zero-Flake Execution:** Built-in wait logic handles Firebase Auth latency without hard-coded `sleep()` calls.
* **Platform Parity:** Single `.yaml` definitions drive both iOS and Android build variants.
* **Non-Invasive:** Maestro tests the compiled `.apk` or `.app` (Black-box), ensuring we test exactly what the user sees.
* **System Level Access:** Handles native OS permission dialogs (Camera/Location/Notifications) which Marionette cannot "see."
---
## 2. Technical Evaluation Matrix
| Criteria | Maestro | Marionette MCP | Winner |
| :--- | :--- | :--- | :--- |
| **Test Authoring** | **High Speed:** Declarative YAML; Maestro Studio recorder. | **Variable:** Requires precise Prompt Engineering. | **Maestro** |
| **Execution Latency** | **Low:** Instantaneous interaction (~5s flows). | **High:** LLM API roundtrips (~45s+ flows). | **Maestro** |
| **Environment** | Works on Release/Production builds. | Restricted to Debug/Profile modes. | **Maestro** |
| **CI/CD Readiness** | Native CLI; easy GitHub Actions integration. | High overhead; depends on external AI APIs. | **Maestro** |
| **Context Awareness** | Interacts with Native OS & Bottom Sheets. | Limited to the Flutter Widget Tree. | **Maestro** |
---
## 3. Spike Analysis & Findings
### Tool A: Maestro (The Standard)
We verified the `login.yaml` and `signup.yaml` flows across both apps. Maestro successfully abstracted the asynchronous nature of our **Data Connect** and **Firebase** backends.
* **Pros:** * **Semantics Driven:** By targeting `Semantics(identifier: '...')` in our `/design_system/`, tests remain stable even if the UI text changes for localization.
* **Automatic Tolerance:** It detects spinning loaders and waits for destination widgets automatically.
* **Cons:** * Requires strict adherence to adding `Semantics` wrappers on all interactive components.
### Tool B: Marionette MCP (The Experiment)
We spiked this using the `marionette_flutter` binding and executing via **Cursor/Claude**.
* **Pros:** * Phenomenal for visual "smoke testing" and live-debugging UI issues via natural language.
* **Cons:** * **Non-Deterministic:** Prone to "hallucinations" during heavy network traffic.
* **Architecture Blocker:** Requires the Dart VM Service to be active, making it impossible to test against hardened production builds.
---
## 4. Implementation & Migration Blueprint
### Phase 1: Semantics Enforcement
We must enforce a linting rule or PR checklist: All interactive widgets in `@krow/design_system` must include a unique `identifier`.
```dart
// Standardized Implementation
Semantics(
identifier: 'login_submit_button',
child: KrowPrimaryButton(
onPressed: _handleLogin,
label: 'Sign In',
),
)
```
### Phase 2: Repository Structure (Implemented)
Maestro flows are co-located with each app:
* `apps/mobile/apps/client/maestro/login.yaml` — Client login
* `apps/mobile/apps/client/maestro/signup.yaml` — Client signup
* `apps/mobile/apps/staff/maestro/login.yaml` — Staff login (phone + OTP)
* `apps/mobile/apps/staff/maestro/signup.yaml` — Staff signup (phone + OTP)
Each directory has a README with run instructions.
**Marionette MCP:** `marionette_flutter` is added to both apps; `MarionetteBinding` is initialized in debug mode. See [marionette-spike-usage.md](marionette-spike-usage.md) for prompts and workflow.
### Phase 3: CI/CD Integration
The Maestro CLI will be added to our **GitHub Actions** workflow to automate quality gates.
* **Trigger:** Every PR targeting `main` or `develop`.
* **Action:** Generate a build, execute `maestro test`, and block merge on failure.

View File

@@ -0,0 +1,84 @@
# How to Run Maestro Integration Tests
## Credentials
| Flow | Credentials |
|------|-------------|
| **Client login** | legendary@krowd.com / Demo2026! |
| **Staff login** | 5557654321 / OTP 123456 |
| **Client signup** | Env vars: `MAESTRO_CLIENT_EMAIL`, `MAESTRO_CLIENT_PASSWORD`, `MAESTRO_CLIENT_COMPANY` |
| **Staff signup** | Env var: `MAESTRO_STAFF_SIGNUP_PHONE` (must be new Firebase test phone) |
---
## Step-by-step: Run login tests
### 1. Install Maestro CLI
```bash
curl -Ls "https://get.maestro.mobile.dev" | bash
```
Or: https://maestro.dev/docs/getting-started/installation
### 2. Add Firebase test phone (Staff app only)
In [Firebase Console](https://console.firebase.google.com) → your project → **Authentication****Sign-in method****Phone****Phone numbers for testing**:
- Add: **+1 5557654321** with verification code **123456**
### 3. Build and install the apps
From the **project root**:
```bash
# Client
make mobile-client-build PLATFORM=apk MODE=debug
adb install apps/mobile/apps/client/build/app/outputs/flutter-apk/app-debug.apk
# Staff
make mobile-staff-build PLATFORM=apk MODE=debug
adb install apps/mobile/apps/staff/build/app/outputs/flutter-apk/app-debug.apk
```
Or run the app on a connected device/emulator: `make mobile-client-dev-android DEVICE=<id>` (then Maestro can launch the already-installed app by appId).
### 4. Run Maestro tests
From the **project root** (`e:\Krow-google\krow-workforce`):
```bash
# Client login (uses legendary@krowd.com / Demo2026!)
maestro test apps/mobile/apps/client/maestro/login.yaml
# Staff login (uses 5557654321 / OTP 123456)
maestro test apps/mobile/apps/staff/maestro/login.yaml
```
### 5. Run signup tests (optional)
**Client signup** — set env vars first:
```bash
$env:MAESTRO_CLIENT_EMAIL="newuser@example.com"
$env:MAESTRO_CLIENT_PASSWORD="YourPassword123!"
$env:MAESTRO_CLIENT_COMPANY="Test Company"
maestro test apps/mobile/apps/client/maestro/signup.yaml
```
**Staff signup** — use a new Firebase test phone:
```bash
# Add +1 555-555-0000 / 123456 in Firebase, then:
$env:MAESTRO_STAFF_SIGNUP_PHONE="5555550000"
maestro test apps/mobile/apps/staff/maestro/signup.yaml
```
---
## Checklist
- [ ] Maestro CLI installed
- [ ] Firebase test phone +1 5557654321 / 123456 added (for staff)
- [ ] Client app built and installed
- [ ] Staff app built and installed
- [ ] Run from project root: `maestro test apps/mobile/apps/client/maestro/login.yaml`
- [ ] Run from project root: `maestro test apps/mobile/apps/staff/maestro/login.yaml`

View File

@@ -0,0 +1,58 @@
# Marionette MCP Spike — Usage Guide
**Issue:** #533
**Purpose:** Document how to run the Marionette MCP spike for auth flows.
## Prerequisites
1. **Marionette MCP server** — Install globally:
```bash
dart pub global activate marionette_mcp
```
2. **Add Marionette to Cursor** — In `.cursor/mcp.json` or global config:
```json
{
"mcpServers": {
"marionette": {
"command": "marionette_mcp",
"args": []
}
}
}
```
3. **Run app in debug mode** — The app must be running with VM Service:
```bash
cd apps/mobile && flutter run -d <device_id>
```
4. **Get VM Service URI** — From the `flutter run` output, copy the `ws://127.0.0.1:XXXX/ws` URI (often shown in the DevTools link).
## Spike flows (AI agent prompts)
Use these prompts with the Marionette MCP connected to the running app.
### Client — Login
> Connect to the app using the VM Service URI. Navigate to the Get Started screen, tap "Sign In", enter legendary@krowd.com and Demo2026!, then tap "Sign In". Verify we land on the home screen.
### Client — Sign up
> Connect to the app. Tap "Create Account", fill in Company, Email, Password (and confirm) with new credentials, then tap "Create Account". Verify we land on the home screen.
### Staff — Login
> Connect to the app. Tap "Log In", enter phone number 5557654321, tap "Send Code", enter OTP 123456, tap "Continue". Verify we reach the staff home screen.
> (Firebase test phone: +1 555-765-4321 / OTP 123456)
### Staff — Sign up
> Connect to the app. Tap "Sign Up", enter a NEW phone number (Firebase test phone), tap "Send Code", enter OTP, tap "Continue". Verify we reach Profile Setup or staff home.
## Limitations observed (from spike)
- **Debug only** — Marionette needs the Dart VM Service; does not work with release builds.
- **Non-deterministic** — LLM-driven actions can vary in behavior and timing.
- **Latency** — Each step involves API roundtrips (~45s+ for full flow vs ~5s for Maestro).
- **Best use** — Exploratory testing, live debugging, smoke checks during development.