feat: Add comprehensive documentation for Krow Platform architecture, including system bible, web application use cases, and mobile agent development rules
- Introduced the Krow Platform System Bible detailing the executive summary, system vision, ecosystem overview, architecture, application responsibilities, use cases, and security model. - Created a detailed use case overview for the Krow Web Application, outlining workflows for Admin, Client, and Vendor roles. - Established non-negotiable agent development rules for mobile applications, emphasizing file structure, naming conventions, logic placement, localization, and error handling. - Defined architecture principles for the Krow mobile platform, focusing on clean architecture, dependency direction, and session management. - Documented design system usage guidelines to ensure UI consistency and adherence to design tokens across applications.
This commit is contained in:
@@ -15,8 +15,6 @@ dependencies:
|
|||||||
google_fonts: ^7.0.2
|
google_fonts: ^7.0.2
|
||||||
lucide_icons: ^0.257.0
|
lucide_icons: ^0.257.0
|
||||||
font_awesome_flutter: ^10.7.0
|
font_awesome_flutter: ^10.7.0
|
||||||
core_localization:
|
|
||||||
path: ../core_localization
|
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
152
docs/ARCHITECTURE/architecture.md
Normal file
152
docs/ARCHITECTURE/architecture.md
Normal 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;
|
||||||
|
```
|
||||||
209
docs/ARCHITECTURE/client-mobile-application/use-case.md
Normal file
209
docs/ARCHITECTURE/client-mobile-application/use-case.md
Normal 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
|
||||||
|
```
|
||||||
208
docs/ARCHITECTURE/staff-mobile-application/use-case.md
Normal file
208
docs/ARCHITECTURE/staff-mobile-application/use-case.md
Normal 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
|
||||||
|
```
|
||||||
251
docs/ARCHITECTURE/system-bible.md
Normal file
251
docs/ARCHITECTURE/system-bible.md
Normal 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.
|
||||||
170
docs/ARCHITECTURE/web-application/use-case.md
Normal file
170
docs/ARCHITECTURE/web-application/use-case.md
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
# 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.
|
||||||
|
3. System determines user role (Admin, Client, or Vendor).
|
||||||
|
4. User is directed to their specific role-based dashboard.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Admin Workflows (Operations Manager)
|
||||||
|
|
||||||
|
### 2.1 Global Operational Oversight
|
||||||
|
* **Actor:** Admin
|
||||||
|
* **Description:** Monitoring the pulse of the entire platform.
|
||||||
|
* **Main Flow:** User accesses Admin Dashboard -> Views all active orders across all clients -> Monitors user registration trends.
|
||||||
|
|
||||||
|
### 2.2 Marketplace & Vendor Management
|
||||||
|
* **Actor:** Admin
|
||||||
|
* **Description:** Expanding the platform's supply network.
|
||||||
|
* **Main Flow:**
|
||||||
|
1. User navigates to Marketplace.
|
||||||
|
2. User invites a new Vendor via email.
|
||||||
|
3. User sets global default rates for roles.
|
||||||
|
4. User audits vendor performance scores.
|
||||||
|
|
||||||
|
### 2.3 System Administration
|
||||||
|
* **Actor:** Admin
|
||||||
|
* **Description:** Configuring platform-wide settings and security.
|
||||||
|
* **Main Flow:** User updates system configurations -> Reviews security audit logs -> Manages internal support tickets.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Client Executive Workflows
|
||||||
|
|
||||||
|
### 3.1 Strategic Insights (Savings Engine)
|
||||||
|
* **Actor:** Client Executive
|
||||||
|
* **Description:** Using AI to optimize labor spend.
|
||||||
|
* **Main Flow:**
|
||||||
|
1. User opens the Savings Engine.
|
||||||
|
2. User reviews identified cost-saving opportunities.
|
||||||
|
3. User clicks "Approve Strategy" to implement recommendations (e.g., vendor consolidation).
|
||||||
|
|
||||||
|
### 3.2 Finance & Billing Management
|
||||||
|
* **Actor:** Client Executive / Finance Admin
|
||||||
|
* **Description:** Managing corporate financial obligations.
|
||||||
|
* **Main Flow:** User views all pending invoices -> Downloads detailed line-item reports -> Processes payments to Krow.
|
||||||
|
|
||||||
|
### 3.3 Operations Overview
|
||||||
|
* **Actor:** Client Executive
|
||||||
|
* **Description:** High-level monitoring of venue operations.
|
||||||
|
* **Main Flow:** User views a summary of their venue orders -> Reviews ratings of assigned staff -> Monitors fulfillment rates.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Vendor Workflows (Staffing Agency)
|
||||||
|
|
||||||
|
### 4.1 Vendor Operations (Order Fulfillment)
|
||||||
|
* **Actor:** Vendor Manager
|
||||||
|
* **Description:** Fulfilling client staffing requests.
|
||||||
|
* **Main Flow:**
|
||||||
|
1. User views incoming shift requests.
|
||||||
|
2. User selects a shift.
|
||||||
|
3. User uses the **Worker Selection Tool** to assign the best-fit staff.
|
||||||
|
4. User confirms assignment.
|
||||||
|
|
||||||
|
### 4.2 Workforce Roster Management
|
||||||
|
* **Actor:** Vendor Manager
|
||||||
|
* **Description:** Maintaining their agency's supply of workers.
|
||||||
|
* **Main Flow:** User navigates to Roster -> Adds new workers -> Updates compliance documents and certifications -> Edits worker profiles.
|
||||||
|
|
||||||
|
### 4.3 Vendor Finance
|
||||||
|
* **Actor:** Vendor Manager
|
||||||
|
* **Description:** Managing agency revenue and worker payouts.
|
||||||
|
* **Main Flow:** User views payout history -> Submits invoices for completed shifts -> Tracks pending payments from Krow.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Shared Functional Modules
|
||||||
|
|
||||||
|
### 5.1 Order Details & History
|
||||||
|
* **Actor:** All Roles
|
||||||
|
* **Description:** Accessing granular data for any specific staffing request.
|
||||||
|
* **Main Flow:** User clicks any order ID -> System displays shift times, roles, assigned staff, and audit history.
|
||||||
|
|
||||||
|
### 5.2 Invoice Detail View
|
||||||
|
* **Actor:** Admin, Client, Vendor
|
||||||
|
* **Description:** Reviewing the breakdown of costs for a billing period.
|
||||||
|
* **Main Flow:** User opens an invoice -> System displays worker names, hours worked, bill rates, and total totals per role.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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 --> ViewAllOrders[View All Orders]
|
||||||
|
GlobalOversight --> ViewAllUsers[View All Users]
|
||||||
|
|
||||||
|
AdminDash --> MarketplaceMgmt[Marketplace Management]
|
||||||
|
MarketplaceMgmt --> OnboardVendor[Onboard Vendor]
|
||||||
|
MarketplaceMgmt --> ManageRates[Manage Global Rates]
|
||||||
|
|
||||||
|
AdminDash --> SystemAdmin[System Administration]
|
||||||
|
SystemAdmin --> ConfigSettings[Configure Settings]
|
||||||
|
SystemAdmin --> AuditLogs[View Audit Logs]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ClientWorkflows [Client Executive Workflows]
|
||||||
|
ClientDash --> ClientInsights[Strategic Insights]
|
||||||
|
ClientInsights --> SavingsEngine[Savings Engine]
|
||||||
|
SavingsEngine --> ViewOpp[View Opportunity]
|
||||||
|
ViewOpp --> ApproveStrategy[Approve Strategy]
|
||||||
|
|
||||||
|
ClientDash --> ClientFinance[Finance & Billing]
|
||||||
|
ClientFinance --> ViewInvoices[View Invoices]
|
||||||
|
ClientFinance --> PayInvoice[Pay Invoice]
|
||||||
|
|
||||||
|
ClientDash --> ClientOps[Operations Overview]
|
||||||
|
ClientOps --> ViewMyOrders[View My Orders]
|
||||||
|
ClientOps --> ViewMyStaff[View Assigned Staff]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph VendorWorkflows [Vendor Workflows]
|
||||||
|
VendorDash --> VendorOps[Vendor Operations]
|
||||||
|
VendorOps --> ViewRequests[View Shift Requests]
|
||||||
|
ViewRequests --> AssignWorker[Assign Worker]
|
||||||
|
VendorOps --> ManageRoster[Manage Worker Roster]
|
||||||
|
ManageRoster --> UpdateWorkerProfile[Update Worker Profile]
|
||||||
|
|
||||||
|
VendorDash --> VendorFinance[Vendor Finance]
|
||||||
|
VendorFinance --> ViewPayouts[View Payouts]
|
||||||
|
VendorFinance --> SubmitInvoice[Submit Invoice]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph SharedModules [Shared Functional Modules]
|
||||||
|
ViewAllOrders -.-> OrderDetail[Order Details]
|
||||||
|
ViewMyOrders -.-> OrderDetail
|
||||||
|
ViewRequests -.-> OrderDetail
|
||||||
|
|
||||||
|
AssignWorker -.-> WorkerSelection[Worker Selection Tool]
|
||||||
|
|
||||||
|
ViewInvoices -.-> InvoiceDetail[Invoice Detail View]
|
||||||
|
SubmitInvoice -.-> InvoiceDetail
|
||||||
|
end
|
||||||
|
```
|
||||||
135
docs/MOBILE/00-agent-development-rules.md
Normal file
135
docs/MOBILE/00-agent-development-rules.md
Normal 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 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.
|
||||||
197
docs/MOBILE/01-architecture-principles.md
Normal file
197
docs/MOBILE/01-architecture-principles.md
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
# 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 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 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**:
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
### 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()`
|
||||||
155
docs/MOBILE/02-design-system-usage.md
Normal file
155
docs/MOBILE/02-design-system-usage.md
Normal 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.
|
||||||
Reference in New Issue
Block a user