Merge pull request #385 from Oloodi/371-functional-parity-analysis-legacy-vs-new-architectures

Created the system bibles, use case documents and architecture documents for the both legacy and current system
This commit is contained in:
Achintha Isuru
2026-02-06 16:20:26 -05:00
committed by GitHub
23 changed files with 2990 additions and 331 deletions

View File

@@ -55,22 +55,25 @@ help:
@echo ""
@echo " 🗄️ DATA CONNECT & BACKEND (backend/dataconnect)"
@echo " ────────────────────────────────────────────────────────────────────"
@echo " make dataconnect-init Initialize Firebase Data Connect"
@echo " make dataconnect-deploy Deploy Data Connect schemas to Cloud SQL"
@echo " make dataconnect-sql-migrate Apply pending SQL migrations"
@echo " make dataconnect-generate-sdk Regenerate Data Connect client SDK"
@echo " make dataconnect-sync Full sync: deploy + migrate + generate SDK"
@echo " make dataconnect-seed Seed database with test data"
@echo " make dataconnect-clean Delete all data from Data Connect"
@echo " make dataconnect-test Test Data Connect deployment (dry-run)"
@echo " make dataconnect-enable-apis Enable required GCP APIs"
@echo " make dataconnect-bootstrap-db ONE-TIME: Full Cloud SQL + Data Connect setup"
@echo " make dataconnect-init Initialize Firebase Data Connect"
@echo " make dataconnect-deploy [ENV=dev] Deploy Data Connect schemas (dev/staging)"
@echo " make dataconnect-sql-migrate [ENV=dev] Apply pending SQL migrations"
@echo " make dataconnect-generate-sdk [ENV=dev] Regenerate Data Connect client SDK"
@echo " make dataconnect-sync [ENV=dev] Full sync: deploy + migrate + generate SDK"
@echo " make dataconnect-seed [ENV=dev] Seed database with test data"
@echo " make dataconnect-clean [ENV=dev] Delete all data from Data Connect"
@echo " make dataconnect-test [ENV=dev] Test Data Connect deployment (dry-run)"
@echo " make dataconnect-enable-apis [ENV=dev] Enable required GCP APIs"
@echo " make dataconnect-bootstrap-db ONE-TIME: Full Cloud SQL + Data Connect setup (dev)"
@echo " make dataconnect-bootstrap-validation-database ONE-TIME: Setup validation database"
@echo " make dataconnect-backup-dev-to-validation Backup dev database to validation"
@echo ""
@echo " 🛠️ DEVELOPMENT TOOLS"
@echo " ────────────────────────────────────────────────────────────────────"
@echo " make install-melos Install Melos globally (for mobile dev)"
@echo " make install-git-hooks Install git pre-push hook (protect main/dev)"
@echo " make sync-prototypes Sync prototypes from client-krow-poc repo"
@echo " make clean-branches Delete local branches (keeps main/dev/demo/**/protected)"
@echo ""
@echo " HELP"
@echo " ────────────────────────────────────────────────────────────────────"
@@ -79,4 +82,5 @@ help:
@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
@echo " 💡 Tip: Run 'make mobile-install' first for mobile development"
@echo " 💡 Tip: Use 'make dataconnect-sync' after schema changes"
@echo " 💡 Tip: Default ENV=dev, use ENV=staging for staging environment"
@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

5
PROTECTED_BRANCHES.md Normal file
View File

@@ -0,0 +1,5 @@
# Protected Branches
- `main`
- `dev`
- `demo/**`

View File

@@ -59,66 +59,6 @@
"type": "mermaid",
"icon": "bi-geo-alt"
},
{
"path": "assets/diagrams/legacy/staff-mobile-application/overview.mermaid",
"title": "Legacy App Overview",
"type": "mermaid",
"icon": "bi-phone"
},
{
"path": "assets/diagrams/legacy/staff-mobile-application/use-case-flowchart.mermaid",
"title": "Legacy App Use Cases",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/legacy/staff-mobile-application/api-map.mermaid",
"title": "Legacy App API Map",
"type": "mermaid",
"icon": "bi-phone"
},
{
"path": "assets/diagrams/legacy/staff-mobile-application/use-case-flows.mermaid",
"title": "Legacy App Use Cases BE Chart",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/legacy/staff-mobile-application/backend-architecture.mermaid",
"title": "Legacy App Backend Architecture",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/legacy/client-mobile-application/overview.mermaid",
"title": "Legacy App Overview",
"type": "mermaid",
"icon": "bi-phone"
},
{
"path": "assets/diagrams/legacy/client-mobile-application/use-case-flowchart.mermaid",
"title": "Legacy App Use Cases",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/legacy/client-mobile-application/api-map.mermaid",
"title": "Legacy App API Map",
"type": "mermaid",
"icon": "bi-phone"
},
{
"path": "assets/diagrams/legacy/client-mobile-application/use-case-flows.mermaid",
"title": "Legacy App Use Cases BE Chart",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/legacy/client-mobile-application/backend-architecture.mermaid",
"title": "Legacy App Backend Architecture",
"type": "mermaid",
"icon": "bi-diagram-2"
},
{
"path": "assets/diagrams/dataconnect/uml/user_uml_diagram.mmd",
"title": "User UML Diagram Dataconnect",

View File

@@ -1,12 +1,68 @@
[
{
"title": "System Bible",
"path": "./assets/documents/legacy/system-bible.md"
},
{
"title": "Architecture Overview",
"path": "./assets/documents/legacy/architecture.md"
},
{
"title": "Architecture Document & Migration Plan",
"path": "./assets/documents/legacy/staff-mobile-application/architecture.md"
},
{
"title": "Use Case Documentation",
"path": "./assets/documents/legacy/staff-mobile-application/use-case.md"
},
{
"title": "Architecture Document & Migration Plan",
"path": "./assets/documents/legacy/client-mobile-application/architecture.md"
},
{
"title": "Use Case Documentation",
"path": "./assets/documents/legacy/client-mobile-application/use-case.md"
},
{
"title": "Architecture Document & Migration Plan",
"path": "./assets/documents/legacy/web-application/architecture.md"
},
{
"title": "Use Case Documentation",
"path": "./assets/documents/legacy/web-application/use-case.md"
},
{
"title": "System Bible",
"path": "./assets/documents/prototype/system-bible.md"
},
{
"title": "Architecture Overview",
"path": "./assets/documents/prototype/architecture.md"
},
{
"title": "Architecture Overview",
"path": "./assets/documents/prototype/staff-mobile-application/architecture.md"
},
{
"title": "Use Case Overview",
"path": "./assets/documents/prototype/staff-mobile-application/use-case.md"
},
{
"title": "Architecture Overview",
"path": "./assets/documents/prototype/client-mobile-application/architecture.md"
},
{
"title": "Use Case Overview",
"path": "./assets/documents/prototype/client-mobile-application/use-case.md"
},
{
"title": "Architecture Overview",
"path": "./assets/documents/prototype/web-application/architecture.md"
},
{
"title": "Use Case Overview",
"path": "./assets/documents/prototype/web-application/use-case.md"
},
{
"title": "Dataconnect guide",
"path": "./assets/documents/dataconnect/backend_manual.md"

View File

@@ -0,0 +1,107 @@
# Krow System Architecture Overview
## 1. System Purpose: The Digital Workforce Marketplace
The **Krow Ecosystem** is a complete digital solution for the temporary staffing industry. Its primary purpose is to seamlessly connect two groups of people:
1. **Businesses** (restaurants, event venues) who need temporary staff.
2. **Workers** (waiters, security, chefs) who are looking for flexible shifts.
Instead of using agencies, phone calls, or spreadsheets, the Krow system automates the entire process: finding staff, verifying their skills, tracking their work hours on-site, and processing payments. It turns a chaotic manual process into a smooth, transparent digital workflow.
## 2. The Role of Each Application
The system is composed of three distinct applications, each tailored for a specific user:
### A. The Client App (Mobile)
* **User:** Business Owners & Managers.
* **Role:** The "Demand" side. It allows businesses to post jobs ("Shifts"), see who is working for them, monitor attendance in real-time, and handle invoices.
* **Key Analogy:** Like the "Uber" app for a passenger—requesting a service and paying for it.
### B. The Staff App (Mobile)
* **User:** Temporary Workers.
* **Role:** The "Supply" side. It allows workers to build a professional profile, find and accept jobs, and use their phone to "Clock In" and "Clock Out" at venues.
* **Key Analogy:** Like the "Uber Driver" app—accepting jobs and proving the work was done.
### C. The Web Platform (Web & Backend)
* **User:** Krow Operations Team (Admins) & System Logic.
* **Role:** The "Brain" and "Control Tower." It stores all the data, enforces the rules (e.g., "You can't work if your visa is expired"), and provides a dashboard for Krow staff to oversee the entire business.
* **Key Analogy:** The Uber HQ dashboard—managing the market, resolving disputes, and ensuring safety.
## 3. How They Interact
These applications do not speak to each other directly; they all speak to the **Web Platform**.
* **Client to Platform:** When a business posts a shift in the Client App, it sends that request to the Web Platform. The Platform saves it and makes it searchable.
* **Platform to Staff:** The Platform identifies which workers match the new shift (based on skills and location) and makes the job visible in their Staff App.
* **Staff to Platform:** When a worker taps "Accept," the Staff App tells the Platform. The Platform checks if they are still available and confirms the booking.
* **Staff to Client (via Platform):** When a worker scans a QR code to Clock In, the Staff App tells the Platform "I'm here." The Platform instantly updates the Client App, so the manager sees "Active" on their screen.
## 4. Shared Services & Infrastructure
To keep the system fast, secure, and reliable, all three apps share a common foundation:
* **Central Database:** A single source of truth. Whether you look at a shift on the iPhone Client App, Android Staff App, or Web Dashboard, you are looking at the exact same record in the database.
* **GraphQL API:** The "Language" of the system. Its a specialized way for the mobile apps to ask the server for data. It ensures that even if a user has a slow connection, the app remains responsive by asking only for exactly what it needs.
* **Firebase Authentication:** A shared security service. It handles the complex work of storing passwords and verifying emails. This means a users identity is secure across the entire ecosystem.
* **Maps & Geolocation:** All apps use the same mapping services to understand where "Venue A" is and whether "Worker B" is standing inside it.
## 5. Data Ownership & Boundaries
* **The Web Platform Owns Everything:** The mobile apps are just "viewers." They don't permanently own the data. If a phone is lost or the app is deleted, the data (shifts, earnings, invoices) is safe on the server.
* **Client Data Boundary:** A Business can *only* see their own hubs, their own events, and the staff assigned to *their* shifts. They cannot see a worker's history with other businesses.
* **Staff Data Boundary:** A Worker can *only* see shifts they are eligible for and their own financial history. They cannot see internal business details or other workers' pay rates.
## 6. Security & Access Control
The system uses a strict **Role-Based Access Control (RBAC)** model:
* **Authentication (Who are you?):** Handled by Firebase. Every request to the server must include a digital "ID Card" (Token) proving the user is logged in.
* **Authorization (What can you do?):** Handled by the Web Platform. Even if a Staff member tries to "hack" the app to ask for an Invoice, the Server will check their role, see they are "Staff" (not "Client"), and block the request immediately.
* **Verification Gates:** The system includes human-in-the-loop security. A staff member cannot just sign up and work; they enter a "Pending" state until a Krow Admin manually reviews their documents on the Web Platform.
## 7. Critical Dependencies
The ecosystem relies on the **Web Platform** being online.
* **If the Staff App fails:** Only workers are affected.
* **If the Client App fails:** Only businesses are affected.
* **If the Web Platform fails:** The entire system stops. No new shifts can be posted, no one can apply, and real-time clock-ins might fail (though the apps have some offline safeguards).
* **3rd Party Reliance:** The system depends on **Firebase** (for login) and **Payment Gateways** (to move money). If these global services go down, Krow's ability to log users in or pay them will pause.
## 8. Overview Diagram
```mermaid
flowchart LR
%% Define Styles
classDef clientApp fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1
classDef staffApp fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c
classDef backend fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20
classDef db fill:#eee,stroke:#333,stroke-width:2px,color:#333
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
subgraph Mobile_Apps["Mobile Ecosystem"]
direction TB
ClientApp["Client Mobile App<br/>(Business Owners)"]:::clientApp
StaffApp["Staff Mobile App<br/>(Workers)"]:::staffApp
end
subgraph Core_Platform["Krow Web Platform"]
direction TB
AdminPanel["Admin Dashboard<br/>(Operations Team)"]:::backend
APIServer["Central API Server<br/>(GraphQL Logic)"]:::backend
Database[("Central Database")]:::db
Storage["File Storage<br/>(Photos/Docs)"]:::db
end
subgraph External_Services["Cloud Services"]
direction TB
Firebase["Firebase<br/>(Auth & Push)"]:::external
Maps["Google Maps API<br/>(Location)"]:::external
end
%% Communication Flows
ClientApp <-->|Post Shifts, View Invoices| APIServer
StaffApp <-->|Apply for Jobs, Clock In| APIServer
AdminPanel <-->|Manage Users, Resolve Disputes| APIServer
APIServer <-->|Read/Write Data| Database
APIServer <-->|Save/Retrieve Files| Storage
ClientApp -.->|Secure Login| Firebase
StaffApp -.->|Secure Login| Firebase
AdminPanel -.->|Secure Login| Firebase
APIServer -->|Send Notifications| Firebase
APIServer -->|Validate Addresses| Maps
StaffApp -.->|Verify Location| Maps
```

View File

@@ -1,220 +1,133 @@
# Krow Mobile Client App Architecture Document
# Application Overview: Krow Client Mobile App
## A. Introduction
## 1. Executive Summary
The **Krow Client App** is a mobile workforce management tool designed for business owners and managers. Think of it as a "control center" that allows businesses to easily hire, manage, and pay temporary staff for events or shifts.
This document provides a comprehensive overview of the Krow mobile client application's architecture. The Krow app is a Flutter-based mobile application designed to connect staff with work opportunities. It includes features for event management, invoicing, staff rating, and profile management.
Instead of calling agencies or managing spreadsheets, a business user opens this app to:
* Define a job (Event/Shift).
* Request specific roles (e.g., Waiter, Security).
* Monitor staff check-ins and attendance.
* Rate staff performance.
* Handle payments and invoices.
The core purpose of the app is to provide a seamless experience for staff to find, manage, and get paid for work, while allowing clients to manage their events and staff effectively.
## 2. High-Level Architecture
The application follows a **Modern Mobile Architecture** designed for reliability and speed. It acts as a "smart interface" that connects the user to the central Krow platform.
## B. Full Architecture Overview
* **The Frontend (This App):** Handles everything the user sees and touches. It validates inputs (like ensuring a shift end time is after the start time) and displays data beautifully.
* **The Bridge (API Layer):** The app talks to the Krow Cloud Server using **GraphQL**. This allows the app to ask for exactly the data it needs—no more, no less—making it fast even on slower connections.
* **The Backend (The Brain):** All heavy processing (matching staff to jobs, processing payments) happens on the secure server, not on the phone.
The Krow app is built using a layered architecture that separates concerns and promotes modularity. The main layers are the **Presentation Layer**, the **Domain Layer**, and the **Data Layer**, organized into feature-based modules.
## 3. Major Components & Modules
### Key Modules and Layers
The application codebase is structured into two main directories: **Features** (Business Capabilities) and **Core** (Shared Utilities & Foundations).
* **Features:** The `lib/features` directory contains the main features of the app, such as `sign_in`, `events`, `profile`, etc. Each feature directory is further divided into `presentation` and `domain` layers.
* **Presentation Layer:** This layer is responsible for the UI and user interaction. It contains the screens (widgets) and the BLoCs (Business Logic Components) that manage the state of the UI.
* **Domain Layer:** This layer contains the core business logic of the application. It includes the BLoCs, which are responsible for orchestrating the flow of data between the UI and the data layer, and the business objects (entities).
* **Data Layer:** This layer is responsible for all data-related operations. It includes the repositories that fetch data from the backend and the data sources themselves (e.g., GraphQL API, local cache).
* **Core:** The `lib/core` directory contains shared code that is used across multiple features, such as the API client, dependency injection setup, routing, and common widgets.
### A. Features (`lib/features/`)
These modules contain the specific business logic and UI for each distinct part of the application:
### Integration Points
* **assigned_staff_screen**: Manages the view where clients can see staff members assigned to their shifts.
* **clock_manual**: Handles the functionality for manually logging staff work hours (Clock-In/Clock-Out) if automated methods fail or are not used.
* **create_event**: The workflow and forms for creating new events and defining shift requirements.
* **events**: The dashboard and list views for managing existing events (upcoming, active, and past).
* **home**: The main landing screen after login, providing a summary and quick access to key actions.
* **hubs**: Manages the creation and configuration of "Hubs" (locations) and "Departments".
* **invoice**: Handles the display and management of billing, invoices, and payment history.
* **notificatins**: Manages the in-app notification center (alerts, updates, and messages).
* **profile**: User settings, personal information, and business profile management.
* **rate_staff**: The interface for clients to provide ratings and feedback on staff performance after a shift.
* **sign_in**: Handles the authentication flow, including login screens and credential validation.
* **splash**: The initial launch screen that handles app initialization and auth checks.
* **UI to Domain:** The UI (widgets) dispatches events to the BLoCs in the domain layer based on user interactions.
* **Domain to Data:** The BLoCs in the domain layer call methods on the repositories in the data layer to fetch or update data.
* **Data to Backend:** The repositories in the data layer use the `ApiClient` to make GraphQL calls to the backend.
## 4. Component Responsibilities
* **User Interface (UI):** The "Face" of the app. It displays buttons, lists, and forms. It is "dumb" in that it doesn't make decisions; it just shows what it's told.
* **State Management (BLoC):** The "Brain" of the app. When a user taps "Create Event," this component checks if the form is valid, formats the data, and decides what loading spinner to show.
* **Data Repository:** The "Librarian." It decides where to get information. Does the app already have the list of staff saved on the phone? Or does it need to fetch a fresh list from the server?
## C. Backend Architecture
## 5. External System Communication
The app does not live in isolation; it talks to several outside services:
The backend of the Krow app is a hybrid system that leverages both a **GraphQL server** and **Firebase services**.
* **The Krow Backend (GraphQL):** The primary source of truth for all data (Events, Staff profiles, Shifts).
* **Firebase Auth:** Handles secure login (passwords, email verification) so the Krow team doesn't have to build security from scratch.
* **Firebase Remote Config:** Allows the Krow team to change app settings (like feature flags or text) without forcing users to update the app.
* **NFC Services:** Interacts with physical NFC tags, likely for scanning staff badges or verifying presence at a location.
* **Geolocation Services:** Uses the phone's GPS to verify that actions (like creating a hub) are happening at the correct physical address.
## 6. Architectural Patterns
The app uses a **Feature-First, Clean Architecture** approach combined with **BLoC (Business Logic Component)**.
* **Feature-First:** The code is organized by *business capability* (e.g., "Invoices", "Events") rather than technical type. This means if we need to change how Invoices work, we go to the "Invoice" folder, and everything is there.
* **Clean Architecture:** The app is built in layers like an onion. The inner layers (Business Logic) don't know anything about the outer layers (UI). This makes the app highly testable and stable.
* **BLoC:** This pattern strictly separates "Events" (user clicks) from "States" (what the screen shows). It ensures that a glitch in the UI doesn't crash the business logic.
## 7. Key Design Decisions & Impact
### A. GraphQL over REST
* **Decision:** The app asks for specific data trees (e.g., "Give me Event X, its Shifts, and only the Names of assigned staff").
* **Why it matters:** This reduces data usage and loading times. The app doesn't download unnecessary info, making it feel snappier.
### B. Offline Capability (Hive)
* **Decision:** The app uses a local database (`hive`) to store some data on the phone.
* **Why it matters:** If the manager loses internet briefly, the app doesn't go blank. It can show cached data until the connection is restored.
### C. Dependency Injection (`injectable`)
* **Decision:** The app uses a system to "plug in" different tools automatically.
* **Why it matters:** It makes the app easy to update. If we want to swap the Geolocation provider, we change it in one place, and the whole app updates automatically.
## 8. Overview Diagram
```mermaid
flowchart TD
subgraph "Client"
A[Flutter App]
end
%% Define Styles
classDef frontend fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1
classDef logic fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c
classDef data fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
subgraph "Backend"
B[GraphQL Server (e.g., Node.js)]
C[Firebase]
end
subgraph User_Device [Client Mobile App]
direction TB
subgraph "Firebase Services"
C1[Firebase Auth]
C2[Firebase Firestore]
C3[Firebase Storage]
end
A -- "GraphQL Queries/Mutations" --> B
A -- "Authentication" --> C1
B -- "Data Operations" --> C2
B -- "File Operations" --> C3
C1 -- "User Tokens" --> A
C2 -- "Data" --> B
C3 -- "Files" --> B
B -- "Data/Files" --> A
```
### GraphQL
The GraphQL server acts as an intermediary between the Flutter app and the Firebase services. It exposes a set of queries and mutations that the app can use to interact with the backend. This provides a single, unified API for the app to consume, simplifying data fetching and manipulation.
### Firebase Integration
* **Firebase Auth:** Firebase Auth is used for user authentication. The Flutter app interacts directly with Firebase Auth to handle user sign-in, sign-up, and password reset flows. Once authenticated, the app retrieves a Firebase ID token, which is then used to authenticate with the GraphQL server.
* **Firebase Firestore:** Firestore is the primary database for the application. The GraphQL server is responsible for all interactions with Firestore, including fetching, creating, updating, and deleting data.
* **Firebase Storage:** Firebase Storage is used for storing user-generated content, such as profile pictures. The GraphQL server handles file uploads and retrieves file URLs that are then sent to the app.
### End-to-End Communication Flow
1. The Flutter app authenticates the user with Firebase Auth.
2. The app receives a Firebase ID token.
3. For all subsequent API requests, the app sends the Firebase ID token in the authorization header of the GraphQL request.
4. The GraphQL server verifies the token and then executes the requested query or mutation.
5. The GraphQL server interacts with Firestore or Firebase Storage to fulfill the request.
6. The GraphQL server returns the requested data to the app.
## D. API Layer
The API layer is responsible for all communication with the backend. It is built around the `graphql_flutter` package and a custom `ApiClient`.
```mermaid
flowchart TD
subgraph "GraphQL API"
direction LR
subgraph "Queries"
Q1[getEvents]
Q2[getEventDetails]
Q3[getInvoices]
Q4[getInvoiceDetails]
Q5[getNotifications]
Q6[getNotificationDetails]
Q7[getProfile]
Q8[getAssignedStaff]
subgraph Features [Feature Modules]
direction TB
Auth[Sign In & Profile]:::frontend
Hubs[Hubs & Business Mgmt]:::frontend
Events[Event & Shift Mgmt]:::frontend
Staff[Staff Interaction & Rating]:::frontend
Finance[Invoices & Payments]:::frontend
end
subgraph "Mutations"
M1[createEvent]
M2[updateProfile]
M3[rateStaff]
M4[clockIn]
M5[clockOut]
M6[uploadProfilePicture]
subgraph Core_Logic [Business Logic Layer]
direction TB
BLoC[State Management BLoC]:::logic
Validation[Input Validation]:::logic
end
subgraph Data_Layer [Data & Storage]
direction TB
Repos[Repositories]:::data
LocalDB[(Local Storage - Hive)]:::data
API_Client[GraphQL Client]:::data
end
end
subgraph "Firebase"
direction LR
subgraph "Firestore Collections"
FS1[events]
FS2[invoices]
FS3[notifications]
FS4[users]
end
subgraph "Firebase Storage"
FB1[Profile Pictures]
end
subgraph External_Services [External Cloud Ecosystem]
direction TB
Krow_Backend[Krow Backend Server]:::external
Firebase[Firebase Auth & Config]:::external
Maps_NFC[Geolocation & NFC Services]:::external
end
Q1 --> FS1
Q2 --> FS1
Q3 --> FS2
Q4 --> FS2
Q5 --> FS3
Q6 --> FS3
Q7 --> FS4
Q8 --> FS1
Q8 --> FS4
%% Connections
Auth --> BLoC
Hubs --> BLoC
Events --> BLoC
Staff --> BLoC
Finance --> BLoC
M1 --> FS1
M2 --> FS4
M3 --> FS1
M3 --> FS4
M4 --> FS1
M5 --> FS1
M6 --> FB1
```
BLoC --> Validation
BLoC <--> Repos
### API Handling
Repos <--> LocalDB
Repos <--> API_Client
* **Error Handling:** The `ApiClient` uses the `ErrorPolicy.all` policy to catch all GraphQL errors. The BLoCs are responsible for catching these errors and updating the UI state accordingly.
* **Caching:** The `GraphQLCache` with `HiveStore` is used to cache GraphQL query results. The `fetchPolicy` is set to `cacheAndNetwork` to provide a fast user experience while keeping the data up-to-date.
* **Parsing:** The app uses the `json_serializable` package to parse the JSON responses from the GraphQL server into Dart objects.
## E. State Management
The Krow app uses the **BLoC (Business Logic Component)** pattern for state management, powered by the `flutter_bloc` package.
### Why BLoC?
* **Separation of Concerns:** BLoC separates the business logic from the UI, making the code more organized, testable, and maintainable.
* **Testability:** BLoCs are easy to test in isolation from the UI.
* **Reactivity:** BLoC uses streams to manage state, which makes it easy to update the UI in response to state changes.
### State Flow
1. The UI dispatches an event to the BLoC.
2. The BLoC receives the event and interacts with the data layer (repositories) to fetch or update data.
3. The data layer returns data or a success/failure status to the BLoC.
4. The BLoC updates its state based on the result from the data layer.
5. The UI rebuilds itself in response to the new state.
### Integration with the API Layer
The BLoCs do not interact directly with the `ApiClient`. Instead, they go through a repository layer, which abstracts the data source. This makes it possible to switch out the backend without having to change the BLoCs.
## F. Use-Case Flows
The following diagrams illustrate the flow for some of the major use cases in the app.
```mermaid
flowchart TD
subgraph "Sign-In Flow"
A1[User enters credentials] --> B1{SignInBloc};
B1 --> C1[Firebase Auth: signInWithEmailAndPassword];
C1 -- Success --> D1[Navigate to Home];
C1 -- Failure --> E1[Show error message];
end
subgraph "Password Reset Flow"
A2[User requests password reset] --> B2{SignInBloc};
B2 --> C2[Firebase Auth: sendPasswordResetEmail];
C2 -- Email Sent --> D2[User clicks deep link];
D2 --> E2[UI with new password fields];
E2 --> F2{SignInBloc};
F2 --> G2[Firebase Auth: confirmPasswordReset];
G2 -- Success --> H2[Show success message];
G2 -- Failure --> I2[Show error message];
end
subgraph "Event Listing Flow"
A3[User navigates to Events screen] --> B3{EventsBloc};
B3 --> C3[GraphQL Query: getEvents];
C3 --> D3[Firestore: events collection];
D3 -- Returns event data --> C3;
C3 -- Returns data --> B3;
B3 --> E3[Display list of events];
end
subgraph "Create Event Flow"
A4[User submits new event form] --> B4{CreateEventBloc};
B4 --> C4[GraphQL Mutation: createEvent];
C4 --> D4[Firestore: events collection];
D4 -- Success --> C4;
C4 -- Returns success --> B4;
B4 --> E4[Navigate to event details];
end
subgraph "Profile Viewing Flow"
A5[User navigates to Profile screen] --> B5{ProfileBloc};
B5 --> C5[GraphQL Query: getProfile];
C5 --> D5[Firestore: users collection];
D5 -- Returns profile data --> C5;
C5 -- Returns data --> B5;
B5 --> E5[Display profile information];
end
```
API_Client <-->|GraphQL| Krow_Backend
Repos <-->|Auth & Config| Firebase
Repos <-->|Location & Scan| Maps_NFC
```

View File

@@ -0,0 +1,198 @@
# Use Case Documentation: Krow Client Mobile App
## 1. App Initialization
* **Primary Actor:** System (Automated) / Business Client
* **Description:** The initial sequence that determines the user's state (authenticated or not) and routes them to the appropriate starting screen.
* **Preconditions:** User has launched the application.
* **Main Flow:**
1. User opens the app.
2. System checks the local authentication status.
3. **If Authenticated:** System routes the user directly to the **Home Dashboard**.
4. **If Unauthenticated:** System routes the user to the **Authentication Flow**.
---
## 2. User Authentication
* **Primary Actor:** Business Client
* **Description:** The process of logging in to access the platform's features or recovering a lost password.
* **Preconditions:** User is on the Sign-In screen.
* **Main Flow (Sign In):**
1. User enters their registered email and password.
2. User taps "Sign In".
3. System verifies the credentials against the backend.
4. **On Success:** User is redirected to the **Home Dashboard**.
* **Alternative Flow (Forgot Password):**
1. User taps "Forgot Password".
2. User enters their email address.
3. System sends a password reset link.
4. User follows the email instructions to reset credentials.
---
## 3. Main App Navigation
* **Primary Actor:** Business Client
* **Description:** The central hub where users can access different functional areas of the business management suite.
* **Preconditions:** User is logged in and on the Home Dashboard.
* **Main Flow:**
1. User views the dashboard summary.
2. User selects a navigation option:
* **Events:** To manage upcoming shifts.
* **Hubs:** To manage venues and departments.
* **Invoices:** To handle billing and payments.
* **Profile:** To manage business settings and support.
---
## 4. Hub & Venue Management
* **Primary Actor:** Business Client
* **Description:** Configuring the physical locations (Hubs) and internal teams (Departments) where shifts will take place.
* **Preconditions:** User is in the "Hubs" section.
* **Main Flow:**
1. User views the list of existing Hubs.
2. User taps "Add New Hub".
3. User enters venue details (Name, Address, Photo).
4. System validates the address via map services.
5. User adds specific "Departments" (e.g., Kitchen, Bar) to the Hub.
6. User saves the configuration.
---
## 5. Event Management
* **Primary Actor:** Business Client
* **Description:** Creating, publishing, and managing events and their associated staffing requirements.
* **Preconditions:** User is in the "Events" section and has at least one Hub configured.
* **Main Flow:**
1. User views the list of events (Upcoming, Active, Past).
2. User taps "Create New Event".
3. User selects a Hub and sets the date/time.
4. User defines "Shifts" by adding "Positions" (Role, Quantity, Rate).
5. User reviews the estimated cost.
6. User publishes the event to the marketplace.
---
## 6. Operations (Live Management)
* **Primary Actor:** Business Client
* **Description:** Monitoring real-time staff attendance, managing check-ins, and handling operational alerts during an event.
* **Preconditions:** An event is active or upcoming with assigned staff.
* **Main Flow:**
1. User views details of an active event.
2. User monitors the "Assigned Staff" list.
3. User taps a staff member to view their profile, skills, and status.
4. **Manual Action:** If a staff member cannot scan a QR code, the user manually clocks them In/Out.
5. **Alerts:** User receives real-time notifications (e.g., "Staff is Late") and takes action.
---
## 7. Staff Feedback
* **Primary Actor:** Business Client
* **Description:** Providing performance ratings for staff members after their shifts are completed.
* **Preconditions:** A shift has ended.
* **Main Flow:**
1. User selects a completed shift or receives a "Rate Staff" prompt.
2. User selects a staff member.
3. User assigns a star rating (1-5) and optional tags/comments.
4. User submits the rating to the system.
---
## 8. Finance Management
* **Primary Actor:** Business Client
* **Description:** Managing the financial aspects of the account, including viewing invoice history and downloading documents.
* **Preconditions:** User is in the "Invoices" section.
* **Main Flow:**
1. User views a list of all invoices.
2. User checks the status (Paid, Due, Overdue).
3. User selects an invoice to view details.
4. User taps "Download PDF" for accounting records.
---
## 9. Profile Management
* **Primary Actor:** Business Client
* **Description:** Managing business identity, app settings, and accessing support.
* **Preconditions:** User is in the "Profile" section.
* **Main Flow:**
1. User views their business profile details.
2. **Edit Details:** User updates business name, logo, or contact info.
3. **Notifications:** User toggles push notification preferences.
4. **Support:** User accesses the Help Center or contacts customer support.
---
# Use Case Diagram
```mermaid
flowchart TD
subgraph AppInitialization
A[Start App] --> B{Check Auth Status};
B -- Authenticated --> C[Go to Home];
B -- Unauthenticated --> D[Go to Auth];
end
subgraph UserAuthentication
D --> G[Sign In Screen];
G --> H{Action};
H -- Sign In --> I[Enter Email & Password];
I --> J[Verify Credentials];
J -- Success --> C;
H -- Forgot Password --> K[Reset via Email];
end
subgraph MainApp
C --> AC[Home Dashboard];
AC --> AD{Navigate};
AD -- Events --> AE[Event Management];
AD -- Hubs --> AF[Hub & Venue Management];
AD -- Invoices --> AG[Finance & Invoices];
AD -- Profile --> AH[Profile Management];
end
subgraph HubManagement
AF --> AI[View Hubs List];
AI --> AJ[Add New Hub/Venue];
AJ --> AK[Configure Departments];
end
subgraph EventManagement
AE --> AL[View Events List];
AL --> AM[Create New Event];
AM --> AN[Define Shifts & Positions];
AN --> AO[Review & Publish Shift];
end
subgraph Operations
AL --> AP[Active/Upcoming Event Details];
AP --> AQ[Monitor Assigned Staff];
AQ --> AR[View Staff Profile & Status];
AQ --> AS[Manual Clock In/Out];
AP --> AT[Receive Real-time Alerts];
end
subgraph StaffFeedback
AS --> AU[Post-Shift Rating];
AU --> AV[Rate Staff Performance];
end
subgraph FinanceManagement
AG --> AW[View Invoices];
AW --> AX[Check Payment Status];
AW --> AY[Download Invoice PDF];
end
subgraph ProfileManagement
AH --> AZ[View Business Profile];
AZ --> BA[Edit Business Details];
AZ --> BB[Manage Notifications];
AZ --> BC[Access Support];
end
```

View File

@@ -1,87 +1,134 @@
# Krow Mobile Staff App - Architecture Document
# Application Overview: Krow Staff Mobile App
## A. Introduction
## 1. Executive Summary
The **Krow Staff App** is the mobile companion for the workforce—the people picking up shifts and performing the work. It operates as a "gig economy" platform where individuals can find flexible work, manage their schedule, and track their income.
This document outlines the architecture of the Krow Mobile Staff App, a Flutter application designed to connect staff with job opportunities. The app provides features for staff to manage their profiles, view and apply for shifts, track earnings, and complete necessary paperwork.
For a staff member (e.g., a waiter, chef, or event security), this app is their digital office. They use it to:
* Browse and apply for available shifts in their area.
* Manage their professional profile (skills, certificates, experience).
* Complete pre-shift compliance checks (uniform, equipment).
* Check in and out of job sites (using QR codes or NFC).
* Track their earnings and payment history.
The core purpose of the app is to streamline the process of finding and managing temporary work, providing a seamless experience for staff from onboarding to payment.
## 2. High-Level Architecture
Like the Client App, this application is built on a **Modern Mobile Architecture** that prioritizes offline resilience and real-time accuracy.
## B. Full Architecture Overview
* **The Frontend (The App):** A polished, user-friendly interface that guides staff through complex workflows (like onboarding or shift execution) simply.
* **The Bridge (API Layer):** Communicates with the Krow Cloud via **GraphQL**, allowing the app to fetch personalized job feeds and update work status efficiently.
* **The Backend (The Engine):** Manages the "marketplace" logic—matching staff skills to event requirements, calculating pay rates, and processing compliance rules.
The application follows a **Clean Architecture** pattern, separating concerns into three main layers: **Presentation**, **Domain**, and **Data**. This layered approach promotes a separation of concerns, making the codebase more maintainable, scalable, and testable.
## 3. Major Components & Modules
The app is structured into "Features" (functional areas) and "Core" (shared tools), ensuring a clean separation of concerns.
- **Presentation Layer:** This layer is responsible for the UI and user interaction. It consists of widgets, screens, and Blocs that manage the UI state. The Presentation Layer depends on the Domain Layer to execute business logic.
### A. Features (`lib/features/`)
These modules handle the specific tasks a staff member needs to perform:
- **Domain Layer:** This layer contains the core business logic of the application. It consists of use cases (interactors), entities (business objects), and repository interfaces. The Domain Layer is independent of the other layers.
* **auth**: Handles existing user login, ensuring secure access to personal data.
* **check_list**: A compliance tool that ensures staff are "job-ready." It likely includes steps for verifying uniform, equipment, or health and safety requirements before a shift begins.
* **earning**: The financial dashboard where staff can see their total earnings, payment history, and details for specific pay periods.
* **home**: The main landing page, likely summarizing upcoming shifts, active jobs, and quick actions.
* **profile**: Manages the user's professional identity, including their skills, certificates, bio, and account settings.
* **qr_scanner**: A critical operational tool used for "Clocking In" and "Clocking Out" at the venue, providing digital proof of presence.
* **shifts**: The core marketplace and schedule manager. It allows staff to:
* **Browse:** See available shifts ("Open Jobs").
* **Manage:** View accepted shifts ("My Schedule").
* **Execute:** See details for the current shift (address, contacts).
* **sign_up**: A dedicated onboarding flow for new users, guiding them through registration, profile creation, and initial verification.
* **splash**: The app's entry point, handling initialization, updates, and authentication checks.
* **support**: Provides access to help resources or direct support channels for resolving issues.
- **Data Layer:** This layer is responsible for data retrieval and storage. It consists of repository implementations, data sources (API clients, local database), and data transfer objects (DTOs). The Data Layer depends on the Domain Layer and implements the repository interfaces defined in it.
## 4. Component Responsibilities
* **User Interface (UI):** Focused on clarity and speed. It presents job opportunities attractively and makes the "Clock-In" process frictionless.
* **State Management (BLoC):** Handles the logic of the app. For example, when a user scans a QR code, the BLoC validates the scan, sends the timestamp to the server, and updates the UI to "Shift Started" mode.
* **Data Repository:** intelligent data handling. It knows when to fetch new jobs from the internet and when to show the saved schedule from the local database (crucial for venues with poor reception).
### Integration Points
## 5. External System Communication
* **The Krow Backend (GraphQL):** The central authority for job listings, user profiles, and time/attendance records.
* **Firebase Auth:** Secure identity management for login and signup.
* **Firebase Remote Config:** Allows dynamic updates to app behavior (e.g., maintenance mode messages).
* **Geolocation & Maps:** Verifies that the staff member is physically at the venue when clocking in and provides directions to the job site.
* **Camera/NFC:** Hardware access for scanning QR codes or interacting with NFC tags for check-ins.
- **UI → Domain:** The UI (e.g., a button press) triggers a method in a Bloc. The Bloc then calls a use case in the Domain Layer to execute the business logic.
- **Domain → Data:** The use case calls a method on a repository interface.
- **Data → External:** The repository implementation, located in the Data Layer, communicates with external data sources (GraphQL API, Firebase, local storage) to retrieve or store data.
## 6. Architectural Patterns
The app adheres to **Clean Architecture** with **BLoC**, ensuring long-term maintainability.
## C. Backend Architecture
* **Separation of Concerns:** The code that draws the "Accept Shift" button is completely separate from the code that sends the "Accept" message to the internet.
* **Reactive UI:** The interface automatically reacts to changes in state (e.g., a new job appearing) without manual refreshing.
The backend is built on a combination of a **GraphQL server** and **Firebase services**.
## 7. Key Design Decisions & Impact
- **GraphQL Server:** The primary endpoint for the Flutter app. It handles most of the business logic and data aggregation. The server is responsible for communicating with Firebase services to fulfill requests.
### A. Offline-First Approach
* **Decision:** Critical data (like "My Schedule") is cached locally.
* **Why it matters:** Event venues often have bad signal (basements, remote fields). Staff must still be able to see where they need to be and valid their start time even if the internet drops.
- **Firebase Services:**
- **Firebase Auth:** Used for user authentication, primarily with phone number verification.
- **Firebase Firestore:** The main database for storing application data, such as user profiles, shifts, and earnings.
- **Firebase Storage:** Used for storing user-generated content, such as profile avatars.
- **Firebase Cloud Messaging:** Used for sending push notifications to users.
- **Firebase Remote Config:** Used for remotely configuring app parameters.
### B. Strict Compliance Checks (`check_list`)
* **Decision:** Forcing a checklist flow before a shift can start.
* **Why it matters:** Ensures quality control for the business client. The app acts as a remote manager, ensuring the staff member confirms they have their uniform before they walk in the door.
### API Flow
### C. Feature-Based Folder Structure
* **Decision:** Grouping files by `feature` (e.g., `earning`, `shifts`) rather than by type (e.g., `screens`, `controllers`).
* **Why it matters:** Makes the codebase easy to navigate for new developers. If there is a bug with payments, you go straight to the `earning` folder.
1. **Flutter App to GraphQL:** The Flutter app sends GraphQL queries and mutations to the GraphQL server.
2. **GraphQL to Firebase:** The GraphQL server resolves these operations by interacting with Firebase services. For example, a `getShifts` query will fetch data from Firestore, and an `updateStaffPersonalInfoWithAvatar` mutation will update a document in Firestore and upload a file to Firebase Storage.
3. **Response Flow:** The data flows back from Firebase to the GraphQL server, which then sends it back to the Flutter app.
## 8. Overview Diagram
```mermaid
flowchart TD
%% Define Styles
classDef frontend fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1
classDef logic fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c
classDef data fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
## D. API Layer
subgraph User_Device [Staff Mobile App]
direction TB
The API layer is responsible for all communication with the backend.
subgraph Features [Feature Modules]
direction TB
Auth[Auth & Sign Up]:::frontend
Shifts[Shift Marketplace & Schedule]:::frontend
CheckList[Compliance & Uniform Checks]:::frontend
QR_NFC[QR Scanner & Clock-In]:::frontend
Earnings[Earnings & History]:::frontend
Profile[Profile & Skills]:::frontend
end
- **GraphQL Operations:** The app uses the `graphql_flutter` package to interact with the GraphQL server. Queries, mutations, and subscriptions are defined in `.dart` files within each feature's `data` directory.
subgraph Core_Logic [Business Logic Layer]
direction TB
BLoC[State Management BLoC]:::logic
Validation[Rules Engine]:::logic
end
- **API Error Handling:** The `ApiClient` class is responsible for handling API errors. It catches exceptions and returns a `Failure` object, which is then handled by the Bloc in the Presentation Layer to show an appropriate error message to the user.
subgraph Data_Layer [Data & Storage]
direction TB
Repos[Repositories]:::data
LocalDB[(Local Storage - Hive)]:::data
API_Client[GraphQL Client]:::data
end
end
- **Caching:** The `graphql_flutter` client provides caching capabilities. The app uses a `HiveStore` to cache GraphQL responses, reducing the number of network requests and improving performance.
subgraph External_Services [External Cloud Ecosystem]
direction TB
Krow_Backend[Krow Backend Server]:::external
Firebase[Firebase Auth & Config]:::external
Geo_Maps[Geolocation & Maps]:::external
Hardware[Camera & NFC Hardware]:::external
end
- **Parsing:** JSON responses from the API are parsed into Dart objects using the `json_serializable` package.
%% Connections
Auth --> BLoC
Shifts --> BLoC
CheckList --> BLoC
QR_NFC --> BLoC
Earnings --> BLoC
Profile --> BLoC
## E. State Management
BLoC --> Validation
BLoC <--> Repos
The application uses the **Bloc** library for state management.
Repos <--> LocalDB
Repos <--> API_Client
- **Why Bloc?** Bloc is a predictable state management library that helps to separate business logic from the UI. It enforces a unidirectional data flow, making the app's state changes predictable and easier to debug.
- **State Flow:**
1. **UI Event:** The UI dispatches an event to the Bloc.
2. **Bloc Logic:** The Bloc receives the event, executes the necessary business logic (often by calling a use case), and emits a new state.
3. **UI Update:** The UI listens to the Bloc's state changes and rebuilds itself to reflect the new state.
- **Integration with API Layer:** Blocs interact with the API layer through use cases. When a Bloc needs to fetch data from the backend, it calls a use case, which in turn calls a repository that communicates with the API.
## F. Use-Case Flows
### User Authentication
1. **UI:** The user enters their phone number.
2. **Logic:** The `AuthBloc` sends the phone number to Firebase Auth for verification.
3. **Backend:** Firebase Auth sends a verification code to the user's phone.
4. **UI:** The user enters the verification code.
5. **Logic:** The `AuthBloc` verifies the code with Firebase Auth.
6. **Backend:** Firebase Auth returns an auth token.
7. **Logic:** The app sends the auth token to the GraphQL server to get the user's profile.
8. **Response:** The GraphQL server returns the user's data, and the app navigates to the home screen.
### Shift Management
1. **UI:** The user navigates to the shifts screen.
2. **Logic:** The `ShiftsBloc` requests a list of shifts.
3. **Backend:** The use case calls the `ShiftsRepository`, which sends a `getShifts` query to the GraphQL server. The server fetches the shifts from Firestore.
4. **Response:** The GraphQL server returns the list of shifts, which is then displayed on the UI.
API_Client <-->|GraphQL| Krow_Backend
Repos <-->|Auth & Config| Firebase
Repos <-->|Location| Geo_Maps
QR_NFC -.->|Scan| Hardware
```

View File

@@ -0,0 +1,251 @@
# Use Case Documentation: Krow Staff Mobile App
## 1. App Initialization
* **Primary Actor:** System (Automated) / Staff Member
* **Description:** The initial sequence that determines the user's state (authenticated, verified, or pending) and routes them to the appropriate starting screen.
* **Preconditions:** User has launched the application.
* **Main Flow:**
1. User opens the app.
2. System checks the local authentication and verification status.
3. **If Authenticated & Active:** System routes to **Home Dashboard**.
4. **If Unauthenticated:** System routes to **Authentication Flow**.
5. **If Pending Admin:** System routes to **Waiting Validation**.
6. **If Incomplete Profile:** System routes to **Checklist**.
---
## 2. User Authentication
* **Primary Actor:** Staff Member
* **Description:** The process of logging in or registering a new account.
* **Preconditions:** User is on the Welcome Screen.
* **Main Flow:**
1. User selects "Sign In" or "Sign Up".
2. **Sign In:** User enters email and verifies via code/link.
3. **Sign Up:** User enters details and proceeds to **User Onboarding**.
---
## 3. User Onboarding
* **Primary Actor:** New Staff Member
* **Description:** Collecting initial necessary data to create a profile account.
* **Preconditions:** User is in the Sign-Up flow.
* **Main Flow:**
1. User enters personal information (Name, Phone).
2. User verifies email address.
3. User adds emergency contacts.
4. User defines their address and working radius.
5. User selects their primary roles (e.g., Waiter, Chef).
6. System moves user to **Profile Completion**.
---
## 4. Profile Completion (Checklist)
* **Primary Actor:** Staff Member
* **Description:** A mandatory list of tasks to complete before the profile can be submitted for review.
* **Preconditions:** User is in the "Checklist" state.
* **Main Flow:**
1. User views the list of outstanding items.
2. User uploads certificates (RSA, Hygiene).
3. User confirms possession of required Role Kit (Uniform, Tools).
4. User sets schedule availability.
5. User enters bank account details for payroll.
6. User fills out tax and wage forms.
7. Once all items are done, user submits for **Admin Verification**.
---
## 5. Admin Verification
* **Primary Actor:** Staff Member (Passive) / Admin
* **Description:** The waiting state while Krow admins review the submitted profile.
* **Preconditions:** Profile submitted.
* **Main Flow:**
1. User sees "Waiting for Admin Review" screen.
2. **Approved:** User status becomes "Active" and can access the **Main App**.
3. **Rejected:** User is sent back to **Profile Completion** to fix issues.
---
## 6. Main App Navigation
* **Primary Actor:** Staff Member
* **Description:** The central hub for accessing work and profile management.
* **Preconditions:** User is logged in and verified.
* **Main Flow:**
1. User views the Home Dashboard.
2. User navigates to:
* **Marketplace:** To find new work.
* **My Shifts:** To view upcoming schedule.
* **Earnings:** To track pay.
* **Profile:** To manage settings.
---
## 7. Shift Discovery (Marketplace)
* **Primary Actor:** Staff Member
* **Description:** Finding and accepting new work opportunities.
* **Preconditions:** User is in the Marketplace tab.
* **Main Flow:**
1. User browses available shifts.
2. User filters by date, location, or role.
3. User views shift details (pay, uniform requirements).
4. User applies for or accepts the shift.
5. Shift is added to **My Shifts**.
---
## 8. Pre-Shift Operations
* **Primary Actor:** Staff Member
* **Description:** Compliance steps to ensure readiness before the shift starts.
* **Preconditions:** Shift is upcoming.
* **Main Flow:**
1. User views "My Shifts".
2. User selects the active/upcoming shift.
3. User completes the "Pre-Shift Checklist" (Uniform check, etc.).
4. User confirms attendance.
---
## 9. Live Operations
* **Primary Actor:** Staff Member
* **Description:** The on-site workflow for tracking hours.
* **Preconditions:** User is at the venue.
* **Main Flow:**
1. User arrives at the venue.
2. User taps **Clock In** and scans Supervisor's QR/NFC.
3. Shift enters "In Progress" state.
4. When finished, user taps **Clock Out** and scans QR/NFC.
5. User reports any issues or breaks.
---
## 10. Post-Shift Finance
* **Primary Actor:** Staff Member
* **Description:** Tracking the financial outcome of completed work.
* **Preconditions:** Shift is completed.
* **Main Flow:**
1. User navigates to "Earnings".
2. User views "Earnings Summary" (Total Earned).
3. User views "History" to see individual shift pay.
4. User checks payment status (Processing, Paid).
---
## 11. Profile Management
* **Primary Actor:** Staff Member
* **Description:** Maintaining account details and getting help.
* **Preconditions:** User is in Profile tab.
* **Main Flow:**
1. User views profile details.
2. User updates Skills or Certificates.
3. User changes Availability.
4. User updates Bank Details.
5. User accesses **Support** for help.
---
# Use Case Diagram
```mermaid
flowchart TD
subgraph AppInitialization [App Initialization]
A[Start App] --> B{Check Auth Status}
B -- Authenticated --> C[Go to Home]
B -- Unauthenticated --> D[Go to Auth]
B -- "Admin Validation" --> E[Go to Waiting Validation]
B -- "Prepare Profile" --> F[Go to Checklist]
end
subgraph UserAuthentication [User Authentication]
D --> G[Welcome Screen]
G --> H{Select Sign In/Up}
H -- "Sign In" --> I[Sign In With Email]
I --> J[Verify Email Code]
J -- Success --> C
H -- "Sign Up" --> K[Go to User Onboarding]
end
subgraph UserOnboarding [User Onboarding]
K --> L[Collect Personal Info]
L --> M[Verify Email]
M --> N[Add Emergency Contacts]
N --> O[Enter Address]
O --> P[Define Working Area]
P --> Q[Select Role & Skills]
Q -- Success --> F
end
subgraph ProfileCompletion [Profile Completion]
F --> R[View Checklist]
R --> S[Complete Personal Info]
R --> T[Upload Certificates]
R --> U[Manage Role Kit/Tools]
R --> V[Set Schedule Availability]
R --> W[Manage Bank Account]
R --> X[Fill Out Tax/Wage Forms]
X -- "All Complete" --> E
end
subgraph AdminVerification [Admin Verification]
E --> Y[Waiting for Admin Review]
Y -- Approved --> C
Y -- Rejected --> F
end
subgraph MainApp [Main Application Shell]
C --> Z[Home Dashboard]
Z --> AA{Navigate}
AA -- Marketplace --> AB[Job Marketplace]
AA -- "My Shifts" --> AC[Schedule & Shifts]
AA -- Earnings --> AD[Earnings & History]
AA -- Profile --> AE[Profile Management]
end
subgraph ShiftDiscovery [Shift Discovery]
AB --> AF[Browse Available Shifts]
AF --> AG[Filter by Date/Location]
AF --> AH[View Shift Details]
AH --> AI[Apply/Accept Shift]
AI --> AC
end
subgraph PreShiftOps [Pre-Shift Operations]
AC --> AJ[View Upcoming Shifts]
AJ --> AK[Select Active Shift]
AK --> AL[Complete Compliance Checklist]
AL --> AM[Verify Uniform & Tools]
AM --> AN[Confirm Attendance]
end
subgraph LiveOperations [Live Operations]
AN --> AO[Arrive at Venue]
AO --> AP["Clock In (QR/NFC)"]
AP --> AQ[Shift In Progress]
AQ --> AR["Clock Out (QR/NFC)"]
AR --> AS[Report Issues/Breaks]
end
subgraph PostShiftFinance [Post-Shift Finance]
AD --> AT[View Earnings Summary]
AT --> AU[View Earnings History]
AU --> AV[Check Payment Status]
AS --> AT
end
subgraph ProfileManagement [Profile Management]
AE --> AW[View Profile]
AW --> AX[Manage Skills & Certificates]
AW --> AY[Update Availability]
AW --> AZ[Manage Bank Details]
AW --> BA[Access Support]
BA --> BB["Contact Support/FAQ"]
end
```

View File

@@ -0,0 +1,235 @@
# Krow Legacy Ecosystem: System Bible
**Status:** Official System Constitution
**Version:** 1.0.0
**Date:** 2026-02-06
**Scope:** Krow Legacy Ecosystem (Client App, Staff App, Web Platform)
---
## 1. Executive Summary
The **Krow Legacy Ecosystem** is a comprehensive digital marketplace designed to revolutionize the temporary staffing industry. It eliminates the friction of traditional agencies by directly connecting **businesses** (restaurants, event organizers) with **temporary workers** (wait staff, security, chefs) through a unified, automated platform.
**Why It Exists:**
The traditional staffing model is slow, opaque, and manual (spreadsheets, phone calls). This ecosystem digitizes the entire lifecycle—from finding staff and verifying their skills to tracking attendance and processing payments—creating a transparent, efficient market for flexible work.
**Who It Serves:**
1. **Business Owners ("Clients"):** Who need on-demand, vetted staff without the administrative burden.
2. **Workers ("Staff"):** Who seek flexible shifts, instant access to job opportunities, and reliable payment.
3. **Operations Teams:** Who manage the marketplace, ensuring quality, compliance, and dispute resolution.
**Value Proposition:**
"A trusted, transparent, and real-time workforce marketplace where businesses get reliability and workers get flexibility, powered by a single source of truth."
---
## 2. System Vision & Product Principles
### Core Goals
1. **Frictionless Connection:** Reduce the time to fill a shift from days to minutes.
2. **Trust through Transparency:** Both sides (Client and Staff) must have total visibility into profiles, ratings, and attendance.
3. **Operational Excellence:** Automate low-value tasks (invoicing, timesheets) so humans can focus on high-value tasks (quality assurance, service).
### Product Principles
* **Mobile-First for Users:** The primary interaction point for Clients and Staff is their phone. The experience must be fast, intuitive, and resilient to poor network conditions.
* **Centralized Truth:** Business logic lives on the Server, not the Client. Mobile apps are "smart viewers" but never the final authority.
* **Compliance is Mandatory:** The system must strictly enforce legal and operational requirements (e.g., "No uniform, no work").
* **Offline Resilience:** Staff must be able to perform critical actions (Clock In/Out) even in basements or fields with no signal.
### What We Solve vs. What We Don't
* **WE SOLVE:** Shift discovery, booking, attendance verification, invoicing, and payout calculation.
* **WE DO NOT SOLVE:** Direct employment contracts (staff are independent contractors or agency employees), specialized tax advice, or instant banking transfers (we facilitate, we don't hold funds).
---
## 3. Ecosystem Overview
The ecosystem is composed of three distinct applications that function as a single organic unit.
| Application | Name | Primary User | Platform | Core Responsibility |
| :--- | :--- | :--- | :--- | :--- |
| **1. Client App** | `pineDev_krow-mobile-client-app` | Business Owners | Mobile (Flutter) | **Demand Generation.** Posting shifts, managing venues, verifying staff presence. |
| **2. Staff App** | `pineDev_krow-mobile-staff-app` | Temporary Workers | Mobile (Flutter) | **Supply Fulfilment.** Finding work, proving compliance, executing shifts. |
| **3. Web Platform** | `pineDev_legendary-web-app` | Admin / System | Web (Laravel) | **The Brain.** Marketplace orchestration, data storage, financial processing, admin control. |
**Conceptual Fit:**
Imagine a ride-sharing service. The **Client App** is the passenger requesting a ride. The **Staff App** is the driver accepting the ride. The **Web Platform** is the dispatch center managing the map, prices, and safety.
---
## 4. System Architecture Overview
The system follows a **Hub-and-Spoke** architecture. The Web Platform is the central Hub; the mobile applications are the Spokes.
### Architecture Style
* **Monolithic Backend / Smart Mobile Clients:** We utilize a robust, monolithic backend (Laravel) to ensure data integrity and simplified deployment, coupled with rich mobile clients (Flutter) that handle UI/UX complexity.
* **GraphQL Communication:** All apps communicate via a strictly typed GraphQL API. This decoupling allows mobile apps to evolve their UI without constantly requiring backend changes.
### System Boundaries
* **Network Boundary:** The Mobile Apps communicate over the public internet to the Web Platform's API Gateway.
* **Security Boundary:** Authentication (Firebase) happens at the edge. No request passes to the core logic without a valid identity token.
* **Data Boundary:** Mobile apps cache data but own nothing. The Database behind the Web Platform is the only permanent record.
### Architecture Diagram
```mermaid
flowchart TD
%% Define Styles
classDef clientApp fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1
classDef staffApp fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c
classDef backend fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20
classDef db fill:#eee,stroke:#333,stroke-width:2px,color:#333
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
subgraph Mobile_Apps["Mobile Ecosystem"]
direction TB
ClientApp["Client App<br/>(Business)"]:::clientApp
StaffApp["Staff App<br/>(Workers)"]:::staffApp
end
subgraph Core_Platform["Krow Web Platform"]
direction TB
AdminPanel["Admin Dashboard<br/>(Laravel Nova)"]:::backend
APIServer["GraphQL API<br/>(Laravel Lighthouse)"]:::backend
Database[("Central Database<br/>(PostgreSQL)")]:::db
end
subgraph External_Services["Cloud Services"]
direction TB
Firebase["Firebase<br/>(Auth/Push)"]:::external
Maps["Google Maps<br/>(Location)"]:::external
end
%% Communication Flows
ClientApp <-->|GraphQL| APIServer
StaffApp <-->|GraphQL| APIServer
AdminPanel <-->|Internal| APIServer
APIServer <-->|SQL| Database
Mobile_Apps -.->|Auth| Firebase
Mobile_Apps -.->|Location| Maps
```
---
## 5. Application Responsibility Matrix
This matrix prevents "logic creep" where business rules accidentally migrate into the mobile apps.
| Feature Domain | Client App | Staff App | Web Platform (Backend) |
| :--- | :--- | :--- | :--- |
| **User Accounts** | Sign In / Profile Edit | Sign In / Profile Edit | **MASTER RECORD.** Validation, Ban/Approve. |
| **Events/Shifts** | **CREATE / EDIT.** Define needs. | **READ / ACCEPT.** Browse & Book. | **VALIDATE.** Ensure availability, match skills. |
| **Staff Selection** | View assigned staff. | N/A | Match algorithms, Notification triggers. |
| **Attendance** | View status, Manual Override. | **EXECUTE.** QR Scan / Check-in. | **VERIFY.** Validate Time & Geolocation. |
| **Payments** | View Invoices, Pay. | View Earnings. | **CALCULATE.** Rates * Hours + Tax + Fees. |
| **Notifications** | Receive alerts. | Receive alerts. | **DISPATCH.** Decide who gets alerted and when. |
| **Compliance** | N/A | Upload Docs, Complete Checklists. | **AUDIT.** Verify docs, enforce expiry rules. |
**Crucial Rule:** Mobile Apps **DISPLAY** and **REQUEST**. The Web Platform **DECIDES** and **COMMITS**.
---
## 6. Use Cases (Core Canon)
These are the officially recognized system workflows.
### Group A: Onboarding & Identity
* **UC-01: Staff Registration & Verification** (Staff App -> Web Platform)
* Staff signs up, uploads docs. Web Platform holds status as "Pending" until Admin approves.
* **UC-02: Client Business Setup** (Client App -> Web Platform)
* Client creates account, defines venues (Hubs). Web Platform validates addresses via Maps.
### Group B: The Marketplace Loop
* **UC-03: Shift Creation** (Client App -> Web Platform)
* Client defines role, time, rate. Web Platform publishes to eligible staff.
* **UC-04: Shift Discovery & Booking** (Staff App -> Web Platform)
* Staff sees job, accepts it. Web Platform locks the slot and confirms booking.
### Group C: Operational Execution
* **UC-05: Pre-Shift Compliance** (Staff App -> Web Platform)
* Staff confirms uniform/tools. App blocks clock-in until done.
* **UC-06: Attendance (Clock In/Out)** (Staff App -> Client App -> Web Platform)
* Staff scans Client QR. Platform records timestamp & location. Updates Client view instantly.
* **UC-07: Live Monitoring** (Client App -> Web Platform)
* Client sees who is on-site, late, or missing.
### Group D: Finance & Closeout
* **UC-08: Ratings & Feedback** (Client App -> Web Platform)
* Client rates staff performance. Platform updates Staff reputation score.
* **UC-09: Payroll Calculation** (Web Platform Internal)
* System calculates final pay based on verified hours.
* **UC-10: Invoicing** (Web Platform -> Client App)
* System generates PDF invoice. Client views/downloads in app.
---
## 7. Cross-Application Interaction Rules
1. **No Direct P2P:** The Client App and Staff App **NEVER** talk directly to each other. They communicate exclusively through the Web Platform.
* *Why?* Security and audit trails.
2. **QR/NFC Exception:** The only "direct" interaction is the physical scanning of a QR code or NFC tag. This creates a data packet sent to the server, not a direct network connection between phones.
3. **Push, Don't Poll:** Apps should not constantly ask "Is there an update?". The Platform sends Push Notifications to trigger a data refresh.
4. **Graceful Degradation:** If the Web Platform is unreachable, mobile apps must allow read-only access to cached data (e.g., "My Schedule") but disable write actions (e.g., "Accept Shift").
---
## 8. Data Ownership & Source of Truth
| Data Domain | Source of Truth | Read Access | Write Access |
| :--- | :--- | :--- | :--- |
| **Staff Profile** | Web Database | Staff App (Own), Client App (Assigned), Admin | Staff (Draft), Admin (Approve) |
| **Events/Shifts** | Web Database | Client App (Own), Staff App (Public) | Client (Create), Admin (Override) |
| **Timesheets** | Web Database | Client & Staff (View) | System (Automated), Admin (Correction) |
| **Financials** | Web Database | Client (Invoices), Staff (Earnings) | System (Calculated Only) |
| **Chat/Msgs** | Web Database | Relevant Users | Sender |
**Principle:** "If it isn't in the Web Database, it didn't happen." Local storage on phones is temporary cache only.
---
## 9. Security & Access Model
### Authentication
* **Provider:** Firebase Authentication.
* **Philosophy:** "Trust but Verify." We trust Firebase to say *who* someone is (Identity). We trust our own database to say *what* they can do (Permissions).
### Authorization (RBAC)
* **Role: Client:** Can only see *their* Hubs, *their* Events, and Staff *assigned* to them.
* **Role: Staff:** Can only see *public* shifts they qualify for, and *their own* financial data.
* **Role: Admin:** Has god-mode access via the Web Panel, audited by logs.
### Trust Boundaries
* **Mobile Apps are Untrusted:** We assume the mobile app could be hacked or modified. Therefore, the API validates EVERY request. (e.g., A hacked Staff App sending "I worked 24 hours" will be rejected by server logic).
---
## 10. Non-Negotiables & Guardrails
1. **No Business Logic in UI:** Flutter widgets must never calculate pay, taxes, or availability. They only display values provided by the API.
2. **Strict Typing:** GraphQL schemas must be strictly typed. No `JSON` blobs unless absolutely necessary.
3. **English Only:** Code, comments, and database columns must be in English. Localization happens at the UI layer only.
4. **Immutable Financials:** Once a shift is "Paid," its record can never be modified, only reversed via a new "Correction" transaction.
5. **Location Required:** Clock-in actions MUST include GPS coordinates. If GPS is missing, the action is flagged for review.
---
## 11. Known Constraints & Assumptions
* **Assumption:** Clients and Staff have smartphones with working cameras (for QR) and GPS.
* **Assumption:** Internet connectivity is available for Shift Creation and Booking. (Only Clock-in supports temporary offline mode).
* **Constraint:** The system currently handles a single currency per deployment.
* **Constraint:** Notifications are "best effort" via Firebase; they are not guaranteed to arrive instantly.
---
## 12. Glossary
* **Hub:** A physical location or venue owned by a Client (e.g., "Downtown Stadium").
* **Shift:** A specific time block requiring a worker (e.g., "Friday 18:00-22:00").
* **Position:** A specific role required for a shift (e.g., "Head Waiter").
* **Clock-In:** The digital act of starting work, verified by location and time.
* **Admin Panel:** The web interface for Krow operations staff.
* **Marketplace:** The collection of all open, unassigned shifts visible to staff.
* **BLoC:** (Business Logic Component) The code pattern used in the mobile apps to manage state.
* **GraphQL:** The data query language used for API communication.

View File

@@ -0,0 +1,133 @@
# Application Overview: Krow Web Platform (Backend)
## 1. Executive Summary
The **Krow Web Platform** is the central "brain" and "command center" of the entire Krow ecosystem. While the mobile apps are the tools used in the field, this web application is the engine that powers them.
It serves two primary functions:
1. **The Engine:** It processes all data from the mobile apps—saving new events, finding available staff, handling payments, and verifying check-ins.
2. **The Control Tower (Admin Panel):** It provides a powerful website where Krow administrators can oversee the entire business, manage users, resolve disputes, and configure system-wide settings.
## 2. High-Level Architecture
The application follows a **Monolithic Web Architecture** using the **Laravel** framework. This is a battle-tested, robust structure ideal for building complex, data-heavy business platforms.
* **The API Server (The Voice):** It listens for requests from the mobile apps (using **GraphQL**). When a phone asks "Show me my shifts," this server understands the question, fetches the answer, and sends it back.
* **The Database (The Memory):** A centralized vault where all information (User profiles, Shift details, Invoices) is safely stored.
* **The Admin Interface (The Dashboard):** A secure website (built with **Laravel Nova**) that allows internal staff to view and edit this data directly without writing code.
## 3. Major Components & Modules
The system is divided into logical "domains" representing different parts of the business.
### A. Core Business Logic (`app/Models`, `app/Actions`)
* **Purpose:** The rules of the business.
* **Key Functions:** Defining what an "Event" is, how a "Shift" relates to a "Position," and ensuring that a Staff member cannot be in two places at once.
### B. API Layer (`app/GraphQL`)
* **Purpose:** The communication hub for mobile apps.
* **Key Functions:**
* **Client API:** specialized endpoints for business owners to create jobs.
* **Staff API:** specialized endpoints for workers to find jobs.
* **Authentication:** Verifying who is asking for data.
### C. Administration Panel (`app/Nova`)
* **Purpose:** Internal management tool.
* **Key Functions:**
* **User Management:** Approving new staff, verifying documents.
* **Content Management:** Managing skills lists, certificate types, and system tags.
* **Audit Logs:** Viewing history of who did what.
### D. Financial Engine (`app/Models/Payroll`, `app/Models/Invoice`)
* **Purpose:** Money management.
* **Key Functions:** Calculating staff pay based on hours worked, generating invoices for clients, and tracking payment status.
### E. Notification System (`app/Notifications`)
* **Purpose:** Keeping everyone in the loop.
* **Key Functions:** Sending emails, SMS, or push notifications when shifts are accepted, cancelled, or when payments are processed.
## 4. Component Responsibilities
* **Controllers/Resolvers:** These receive a request (e.g., "Create Shift"), validate it (e.g., "Is the date in the future?"), and pass it to the Logic layer.
* **Service Classes:** These perform specific complex tasks, like "Calculate total cost for this event including tax and service fees."
* **Eloquent Models:** These represent the data tables. The `Staff` model knows how to talk to the `staff` table in the database.
* **Nova Resources:** These define how data looks in the Admin Panel. A `StaffResource` defines that a staff member has a name, photo, and rating, and tells the admin panel how to display them.
## 5. External System Communication
* **Firebase:** Uses Firebase Authentication for secure user identity and Firebase Cloud Messaging for push notifications.
* **Database (MySQL/PostgreSQL):** The primary storage for all application data.
* **Storage (AWS S3 / DO Spaces):** Stores user uploaded files like profile photos and certificates.
* **Payment Gateway (Stripe/Similar):** (Implied) Handles the actual processing of credit card transactions and payouts.
* **Maps/Geolocation APIs:** Used to validate addresses and calculate distances between staff and venues.
## 6. Architectural Patterns
* **MVC (Model-View-Controller):** The traditional Laravel pattern, adapted here where "View" is mostly replaced by the GraphQL API or the Nova Admin panel.
* **Action-Based Domain Logic:** Complex business operations (like "Assign Staff to Shift") are often encapsulated in single "Action" classes rather than hidden inside massive models.
* **GraphQL Schema-First:** The API is defined by a typed schema (`.graphql` files), ensuring a strict contract between the frontend and backend.
## 7. Key Design Decisions & Impact
### A. GraphQL (Lighthouse)
* **Decision:** Using GraphQL instead of traditional REST API endpoints.
* **Why it matters:** Allows the mobile apps to be very efficient. They can ask for deep, related data (Event -> Shifts -> Staff -> Ratings) in a single network request, making the apps faster.
### B. Laravel Nova
* **Decision:** Using a pre-built administration package instead of building a custom admin panel from scratch.
* **Why it matters:** Drastically reduced development time. It provides a professional, secure, and feature-rich dashboard out of the box, allowing the team to focus on the unique app features.
### C. Role-Based Access Control (Spatie Permissions)
* **Decision:** Implementing a granular permission system.
* **Why it matters:** Security. It ensures that a "Client" can never see "Admin" data, and a "Staff" member can only see shifts relevant to them.
## 8. Overview Diagram
```mermaid
flowchart TD
%% Define Styles
classDef interface fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1
classDef logic fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c
classDef data fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20
classDef external fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
subgraph Server_Application [Krow Web Platform]
direction TB
subgraph Interfaces [Access Layers]
direction TB
Admin_Panel[Admin Panel (Laravel Nova)]:::interface
GraphQL_API[GraphQL API (Lighthouse)]:::interface
end
subgraph Domain_Logic [Core Business Engine]
direction TB
Models[Data Models]:::logic
Actions[Business Actions & Rules]:::logic
Notifications[Notification System]:::logic
Payroll[Payroll & Invoicing Engine]:::logic
end
subgraph Data_Storage [Persistence Layer]
direction TB
MySQL[(Main Database)]:::data
Storage[File Storage (S3/DO Spaces)]:::data
end
end
subgraph External_World [External Ecosystem]
direction TB
Mobile_Apps[Mobile Apps (Client & Staff)]:::external
Firebase[Firebase (Auth & Push)]:::external
Maps_API[Maps & Geolocation]:::external
end
%% Connections
Mobile_Apps <-->|GraphQL Requests| GraphQL_API
Admin_Panel --> Actions
GraphQL_API --> Actions
Actions --> Models
Actions --> Payroll
Actions --> Notifications
Models <--> MySQL
Models <--> Storage
Notifications -->|Send Push/Email| Firebase
Actions -->|Validate Location| Maps_API
```

View File

@@ -0,0 +1,154 @@
# Use Case Documentation: Krow Web Platform (Admin Panel)
## 1. Admin Login
* **Primary Actor:** System Administrator / Operations Manager
* **Description:** The secure entry point for accessing the backend management system.
* **Preconditions:** User has admin credentials.
* **Main Flow:**
1. User accesses the Admin URL.
2. User enters email and password.
3. System verifies credentials.
4. **Success:** Redirects to **Admin Dashboard**.
5. **Failure:** Returns to Login Screen with error.
---
## 2. Dashboard Navigation
* **Primary Actor:** Admin
* **Description:** The central hub for accessing different management modules.
* **Preconditions:** User is logged in.
* **Main Flow:**
1. User views the dashboard summary.
2. User selects a module:
* **Staff Mgmt:** To approve and manage workers.
* **Client Mgmt:** To onboard businesses.
* **Operations:** To monitor live events.
* **Finance:** To handle money.
* **Configuration:** To change system settings.
---
## 3. Staff Management
* **Primary Actor:** Operations Manager
* **Description:** The process of validating new staff members.
* **Preconditions:** User is in Staff Management module.
* **Main Flow:**
1. User filters list for "Pending" applications.
2. User reviews documents and profile photos.
3. **Approve:** Staff becomes "Active" and can work.
4. **Reject:** Staff is notified to fix their profile.
---
## 4. Client Management
* **Primary Actor:** Operations Manager
* **Description:** Setting up new business accounts.
* **Preconditions:** User is in Client Management module.
* **Main Flow:**
1. User views existing clients.
2. User creates a new Business entity.
3. User sets up billing details and credit limits.
4. User creates the initial Owner account for the client.
---
## 5. Live Operations
* **Primary Actor:** Operations Manager
* **Description:** Monitoring real-time activity and solving problems.
* **Preconditions:** Events are active.
* **Main Flow:**
1. User views the Active Events map/list.
2. User monitors staff attendance statuses.
3. **Issue:** If a problem arises (e.g., no-show), user intervenes.
4. **No Issue:** Shift completes normally.
---
## 6. Finance & Payroll
* **Primary Actor:** Finance Manager
* **Description:** Processing payments and charging clients.
* **Preconditions:** Shifts are completed.
* **Main Flow:**
1. User reviews completed shifts.
2. User resolves any pending disputes.
3. User runs the "Payroll Process" to pay staff.
4. User generates invoices for clients.
5. User sends invoices via email.
---
## 7. Configuration
* **Primary Actor:** Super Admin
* **Description:** Managing the system's rules and settings.
* **Preconditions:** User has high-level permissions.
* **Main Flow:**
1. **Skills:** User adds new skills or certificate requirements.
2. **Permissions:** User updates what other admins can do.
3. **Audit:** User reviews logs for security checks.
---
# Use Case Diagram
```mermaid
flowchart TD
subgraph AdminLogin
A[Start Admin Panel] --> B[Login Screen];
B --> C[Enter Credentials];
C --> D{Verify Auth};
D -- Success --> E[Admin Dashboard];
D -- Failure --> B;
end
subgraph DashboardNavigation
E --> F{Select Module};
F -- Staff Mgmt --> G[Staff Management];
F -- Client Mgmt --> H[Business Clients];
F -- Operations --> I[Live Operations];
F -- Finance --> J[Payroll & Invoicing];
F -- Config --> K[System Configuration];
end
subgraph StaffManagement
G --> L[Filter Pending Staff];
L --> M[Review Profile & Docs];
M --> N{Decision};
N -- Approve --> O[Mark Active];
N -- Reject --> P[Request Changes];
end
subgraph ClientManagement
H --> Q[View Clients];
Q --> R[Create New Business];
R --> S[Setup Billing/Credit];
S --> T[Create Owner Account];
end
subgraph LiveOperations
I --> U[View Active Events Map];
U --> V[Monitor Attendance];
V --> W{Issue Detected?};
W -- Yes --> X[Resolve Dispute/Issue];
W -- No --> Y[Shift Completed];
end
subgraph Finance
J --> Z[View Completed Shifts];
Z --> AA[Resolve Disputes];
AA --> AB[Process Payroll Run];
AB --> AC[Generate Client Invoices];
AC --> AD[Send Invoices];
end
subgraph Configuration
K --> AE[Manage Skills/Certs];
K --> AF[Manage Roles/Permissions];
K --> AG[View Audit Logs];
end
```

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,161 @@
# Client Mobile Application: Architecture Overview
## 1. Executive Summary
The **Client Mobile Application** is a specialized tool designed for business owners and managers ("Clients") to effortlessly manage their temporary workforce. It serves as the command center for staffing operations, allowing clients to request new staff, monitor active shifts in real-time, handle billing, and analyze operational performance.
Think of it as the "Uber for Staffing" from the business perspective—providing on-demand access to a workforce, real-time tracking, and administrative control in a pocket-sized interface.
## 2. High-Level Architecture
The application is built using **Flutter**, a cross-platform framework that allows a single codebase to run natively on both iOS and Android devices.
The architecture follows a **Feature-First Layered approach**. This means the code is organized primarily by the business features (e.g., "Creating an Order," "Viewing Reports") rather than just technical file types. This structure makes the app easier to navigate and maintain as it grows.
At a high level, the system operates in three layers:
1. **Presentation Layer (UI):** What the user sees and interacts with (Screens, Buttons, Forms).
2. **Logic Layer (State Management):** The "brain" that handles user inputs and decides what to show next (currently managed via Riverpod and local widget state).
3. **Data Layer (Infrastructure):** The connection points to the backend database and external services (currently simulated with mock data for the prototype).
## 3. Major Components & Modules
The application is broken down into several key functional modules:
### A. Authentication Module
* **Responsibility:** Handles secure user entry into the app.
* **Key Features:** `Sign In`, `Sign Up`, and `Get Started` onboarding flows.
* **Purpose:** Ensures only authorized business personnel can access sensitive staffing and billing data.
### B. Dashboard & Home Module
* **Responsibility:** Provides an immediate "pulse check" of the business's staffing status.
* **Key Features:** `Live Activity` feed, `Spending Insights`, `Today's Coverage` summary, and `Quick Actions` for common tasks.
* **Purpose:** Gives managers the critical info they need within seconds of opening the app.
### C. Order Management Module
* **Responsibility:** The core engine for requesting staff.
* **Key Features:**
* **Rapid Order:** For urgent, same-day needs.
* **One-Time Order:** For specific upcoming events.
* **Recurring Order:** For regular weekly needs.
* **Permanent Order:** For long-term staffing solutions.
* **Purpose:** Simplifies the complex logistics of scheduling shifts into intuitive, guided forms.
### D. Workforce Management Module
* **Responsibility:** Managing the people and their time.
* **Key Features:**
* **Shifts:** View upcoming, active, and past shifts.
* **Workers:** Directory of assigned staff.
* **Timesheets:** Review and approve work hours.
* **Verify Attire:** Tools to ensure staff meet dress code compliance.
### E. Analytics & Reporting Module
* **Responsibility:** Business intelligence and data visualization.
* **Key Features:** Reports for `Daily Operations`, `Spending`, `Forecasting`, `Performance`, and `Attendance` (No-shows).
* **Purpose:** Empowers clients to make data-driven decisions about their staffing budget and strategy.
### F. Administration Module
* **Responsibility:** Account and configuration management.
* **Key Features:** `Billing` management, `Settings`, and `Hubs` (managing different business locations).
## 4. Component Responsibilities
| Component | Primary Responsibility | Example Task |
| :--- | :--- | :--- |
| **Router (GoRouter)** | Navigation traffic cop | Directs the user from the "Login" screen to the "Home" dashboard upon success. |
| **Screens (UI)** | Displaying information | Renders the "Create Order" form and captures the user's input for date and time. |
| **Providers (Riverpod)** | Data management & State | Holds the list of today's active shifts so multiple screens can access it without reloading. |
| **Widgets** | Reusable UI building blocks | A "Shift Card" widget that displays shift details effectively, used in multiple lists throughout the app. |
## 5. Data Flow
1. **User Action:** A client taps "Post Shift" on the Create Order screen.
2. **Input Processing:** The app validates the input (e.g., checking if the start time is before the end time).
3. **State Update:** The app updates its internal "State" to reflect that a submission is in progress (showing a loading spinner).
4. **Data Transmission (Future State):** The app sends a structured request to the backend server (API).
5. **Confirmation:** Upon success, the app navigates the user back to the Home screen and updates the "Live Activity" feed to show the newly created open shift.
6. **Read Action:** When viewing the Dashboard, the app requests the latest coverage metrics to display the "80% Covered" status.
## 6. External System Communication
While currently operating as a high-fidelity prototype with mock data, the architecture is designed to connect with:
* **Backend API (Firebase/Cloud Functions):** The app will communicate with a cloud backend to store and retrieve data. It uses `Firebase Core` and `Data Connect`.
* **Authentication Service:** Manages user identities securely.
* **Notification Service:** Sends push notifications to the client when a worker clocks in or if a shift is missed.
## 7. Architectural Patterns
* **Model-View-ViewModel (MVVM) Inspiration:** The app separates the **View** (UI Screens) from the **Data Models**.
* **Declarative UI:** Using Flutter, the UI is built by describing *what* it should look like based on the current state, rather than manually updating elements.
* **Provider Pattern (Riverpod):** Used for Dependency Injection and State Management. This allows different parts of the app to share data (like the current user's profile) without tightly coupling components together.
* **Feature-Based Folder Structure:** Code is organized by "what it does" (e.g., `screens/client/reports`) rather than just technical type, making it easier for new developers to understand the business logic.
## 8. Key Design Decisions
* **Flutter Framework:** chosen for its ability to produce high-performance, native-feeling apps for both iOS and Android from a single codebase, reducing development time and cost.
* **GoRouter for Navigation:** A modern routing package that handles complex navigation scenarios (like deep linking and sub-routes) which are essential for a multi-layered app like this.
* **Riverpod for State Management:** A robust solution that catches programming errors at compile-time (while writing code) rather than run-time (while using the app), increasing app stability.
* **Mock Data Services:** The decision to use extensive mock data allows for rapid UI/UX iteration and testing of business flows without waiting for the full backend infrastructure to be built.
## 9. Overview Diagram
```mermaid
flowchart TD
subgraph ClientMobileApp["Client Mobile Application"]
direction TB
subgraph PresentationLayer["Presentation Layer (UI)"]
direction TB
Router["GoRouter Navigation"]
subgraph FeatureModules["Feature Modules"]
AuthUI["Auth Screens"]
DashUI["Dashboard & Home"]
OrderUI["Order Management"]
WorkUI["Workforce Management"]
ReportUI["Analytics & Reporting"]
AdminUI["Administration"]
end
Router --> FeatureModules
end
subgraph LogicLayer["Logic Layer (State Management)"]
direction TB
Providers["Riverpod Providers"]
State["App State"]
Validation["Input Validation"]
end
subgraph DataLayer["Data Layer (Infrastructure)"]
direction TB
Repositories["Repositories"]
Models["Data Models"]
MockService["Mock Data Service"]
end
PresentationLayer --> LogicLayer
LogicLayer --> DataLayer
end
subgraph ExternalSystems["External Systems"]
direction TB
Firebase["Firebase Backend"]
AuthService["Auth Service"]
Notify["Notification Service"]
CloudFunc["Cloud Functions"]
end
DataLayer --> ExternalSystems
%% Relationships & Data Flow
AuthUI -- "Login/Signup" --> Providers
OrderUI -- "Create Shift" --> Validation
Validation --> Providers
Providers -- "Update State" --> State
State -- "Notify UI" --> PresentationLayer
Repositories -- "Fetch Data" --> MockService
Repositories -. "Future Connection" .-> Firebase
classDef layer fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
classDef module fill:#fff9c4,stroke:#fbc02d,stroke-width:1px,color:#000
classDef system fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
class PresentationLayer,LogicLayer,DataLayer layer
class AuthUI,DashUI,OrderUI,WorkUI,ReportUI,AdminUI module
class ExternalSystems system
```

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,159 @@
# Staff Mobile Application: Architecture Overview
## 1. Executive Summary
The **Staff Mobile Application** is the dedicated companion for the temporary workforce. It is designed to be the "one-stop-shop" for workers to find employment, manage their work life, and get paid.
For a worker, this app replaces the traditional agency corkboard and paper timesheets. It allows them to browse available shifts in their area, claim jobs that fit their schedule, clock in and out using their phone, and track their earnings instantly. It also handles all the necessary administrative tasks like tax forms and certifications.
## 2. High-Level Architecture
Like its client-facing counterpart, this application is built on **Flutter**, ensuring a high-quality, native experience on both Android and iOS devices from a single codebase.
The architecture is **User-Centric and Feature-Driven**. It is organized around the daily lifecycle of a worker: finding work, doing work, getting paid, and growing their career.
The system is structured into three main logical layers:
1. **UI Layer:** The screens and interactive elements (The "Face" of the app).
2. **Application Logic:** The state management that handles user sessions, shift status, and data updates (The "Brain").
3. **Data & Service Layer:** The connection to backend systems for authentication, job listings, and payments (The "Backbone").
## 3. Major Components & Modules
### A. Onboarding & Authentication Module
* **Responsibility:** bringing new workers into the ecosystem securely.
* **Key Features:** `Get Started`, `Phone Verification` (OTP), and `Profile Setup`.
* **Purpose:** Verifies identity and collects essential initial information to create a trustable worker profile.
### B. Marketplace (Jobs) Module
* **Responsibility:** connecting workers with open opportunities.
* **Key Features:** `Jobs Screen` for browsing open shifts, filtering by location/role, and viewing `Shift Details`.
* **Purpose:** Acts as the job board where supply meets demand.
### C. Shift Management Module
* **Responsibility:** managing the "doing" of the work.
* **Key Features:**
* **Shifts:** A personalized schedule of upcoming and past commitments.
* **Clock In/Out:** GPS-enabled time tracking to verify attendance.
* **Availability:** Tools for workers to set when they can and cannot work.
### D. Financial Module
* **Responsibility:** handling compensation and benefits.
* **Key Features:**
* **Earnings:** Visual breakdown of income.
* **Payments:** Transaction history and bank account management.
* **Early Pay:** Feature allowing access to wages before the standard payday.
* **Benefits:** Access to worker perks and insurance.
### E. Profile & Compliance Module
* **Responsibility:** managing the professional identity and legal requirements.
* **Key Features:**
* **Compliance:** Uploading and verifying `Certificates`, `Documents`, and Tax Forms (`I-9`, `W-4`).
* **Level Up:** `Krow University` for training and a `Leaderboard` for gamification.
* **Support:** `FAQs`, `Privacy`, and `Messages`.
## 4. Component Responsibilities
| Component | Primary Responsibility | Example Task |
| :--- | :--- | :--- |
| **Authentication Screens** | Security & Entry | Validates the 6-digit code sent to the user's phone during login. |
| **Shift Provider** | Data State Management | Keeps track of which shift is currently "Active" so the Clock-In button appears on the Home screen. |
| **Router** | Navigation | Deep-links a user directly to a specific "Shift Detail" page from a push notification. |
| **Mock Service** | Data Simulation | Generates a realistic list of "Available Jobs" nearby for the prototype to display. |
## 5. Data Flow
1. **Discovery:** The worker opens the `Jobs` screen. The app requests "Available Shifts" from the Data Layer.
2. **Action:** The worker taps "Accept Shift".
3. **Processing:** The app updates the shift status locally to "Scheduled" and adds it to the worker's `My Shifts` list.
4. **Execution:** On the day of the job, the worker opens the `Clock In` screen. The app checks their geolocation.
5. **Verification:** If the location matches the job site, the "Clock In" action is allowed.
6. **Completion:** After clocking out, the data flows to the `Earnings` module, updating the "Pending Pay" balance.
## 6. External System Communication
The architecture is designed to interface with several critical external systems:
* **Identity Services:** For SMS-based phone verification and secure login.
* **Maps & Geolocation:** Uses device location services to verify "Clock In" actions are performed on-site.
* **Banking/Payment APIs:** Connects to payment processors for "Early Pay" and direct deposit functions.
* **Document Verification Services:** (Future State) To automatically validate uploaded IDs and certifications.
* **Backend Database (Firebase):** Stores the "Single Source of Truth" for user profiles, shift history, and compliance status.
## 7. Architectural Patterns
* **Feature-First Organization:** The codebase is grouped by feature (e.g., `worker_profile/compliance`, `worker_profile/finances`). This "vertical slice" architecture keeps related code together.
* **State Management with Riverpod:** Used to manage global application state (like "Is the user logged in?" or "What is my current location?") in a clean, testable way.
* **Repository Pattern (Implied):** The service layer (`mock_service.dart`) acts as a repository, abstracting the data source so the UI doesn't care if data comes from a mock file or a real server.
## 8. Key Design Decisions
* **Flutter for Mobile:** Ensures the app is responsive and performs well on the wide variety of devices low-wage workers might own.
* **Strict Compliance Separation:** Dedicating a specific sub-module to `Compliance` (Tax forms, I-9) highlights the importance of legal adherence in the staffing industry.
* **Gamification (Level Up):** The inclusion of `Krow University` and `Leaderboards` is a deliberate design choice to drive worker engagement and retention.
* **Offline-First Capabilities (Planned):** The architecture supports local data caching, which is critical for workers who may have spotty data connections while on job sites.
## 9. Overview Diagram
```mermaid
flowchart TD
subgraph StaffMobileApp["Staff Mobile Application"]
direction TB
subgraph PresentationLayer["Presentation Layer (UI)"]
direction TB
Router["GoRouter Navigation"]
subgraph FeatureModules["Feature Modules"]
AuthUI["Auth & Onboarding"]
MarketUI["Marketplace & Jobs"]
ShiftUI["Shift Management"]
FinanceUI["Financial & Benefits"]
ProfileUI["Profile & Compliance"]
end
Router --> FeatureModules
end
subgraph LogicLayer["Application Logic (State)"]
direction TB
Providers["Riverpod Providers"]
AuthState["Auth State"]
LocState["Geolocation State"]
ShiftState["Shift State"]
end
subgraph DataLayer["Data & Service Layer"]
direction TB
MockService["Mock Data Service"]
Repos["Repositories"]
end
PresentationLayer --> LogicLayer
Providers --> AuthState
Providers --> LocState
Providers --> ShiftState
LogicLayer --> DataLayer
end
subgraph ExternalServices["External Services"]
direction TB
Firebase["Firebase Backend"]
Identity["Identity/SMS Service"]
Maps["Google Maps/Geolocation"]
Banking["Payment Processor"]
DocVerify["Doc Verification"]
end
DataLayer --> ExternalServices
%% Specific Data Flows
AuthUI -- "Verify OTP" --> Identity
MarketUI -- "Find Jobs" --> Repos
ShiftUI -- "Clock In" --> Maps
FinanceUI -- "Get Paid" --> Banking
ProfileUI -- "Upload Docs" --> DocVerify
Repos -- "Sync Data" --> Firebase
classDef layer fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
classDef module fill:#fff9c4,stroke:#fbc02d,stroke-width:1px,color:#000
classDef system fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
class PresentationLayer,LogicLayer,DataLayer layer
class AuthUI,MarketUI,ShiftUI,FinanceUI,ProfileUI module
class ExternalServices system
```

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,154 @@
# Web Application: Architecture Overview
## 1. Executive Summary
The **Krow Web Application** is the "Mission Control" for the entire Krow platform. It acts as a powerful administrative dashboard where clients and internal operations teams can see the "Big Picture" that mobile apps can't provide.
While the mobile apps are for *doing* the work (checking in, posting a shift), the web app is for *managing* the business of that work. It allows users to analyze workforce performance, manage complex vendor relationships, handle high-volume invoicing, and use AI to optimize staffing strategies.
## 2. High-Level Architecture
The application is a modern **Single Page Application (SPA)** built using **React**. This means it loads once in the browser and then dynamically updates as the user interacts with it, providing a snappy, app-like experience without constantly reloading pages.
It follows a **Component-Based Architecture**, where the user interface is built from small, reusable pieces (like buttons, charts, and tables) combined into complex dashboards.
The system is structured into three primary layers:
1. **Presentation Layer (Views):** The dashboards and reports the user sees.
2. **State Management Layer (Store):** The "memory" of the app that keeps track of data while the user navigates (using Redux Toolkit).
3. **Data Access Layer (Services):** The bridge that fetches data from the backend or mock services (using React Query).
## 3. Major Components & Modules
### A. Dashboard & Overview Module
* **Responsibility:** Providing immediate situational awareness.
* **Key Features:** High-level metrics (Spend, Fill Rate), recent activity feeds, and quick access to critical alerts.
* **Purpose:** The landing page that answers "Is everything running smoothly right now?"
### B. Analytics & Intelligence Module
* **Responsibility:** Turning raw data into actionable insights.
* **Key Features:**
* **Savings Engine:** AI-driven recommendations to cut costs.
* **Performance Matrix:** Evaluating vendor and worker reliability.
* **Smart Strategies:** Data-backed suggestions for operational improvements.
### C. Workforce & Operations Module
* **Responsibility:** Managing the people and the work.
* **Key Features:**
* **Workforce Directory:** Searching and managing staff profiles.
* **Shift Management:** Overseeing schedules and assignments.
* **Time & Attendance:** Verifying hours worked.
### D. Finance & Marketplace Module
* **Responsibility:** The "Business" side of the platform.
* **Key Features:**
* **Invoicing:** Generating and paying bills.
* **Marketplace:** Finding and onboarding new staffing vendors.
* **Wallet:** Managing payment methods and transactions.
### E. Support & Communication Module
* **Responsibility:** Facilitating help and interaction.
* **Key Features:** Help center, ticketing system, and potentially chat/messaging interfaces.
## 4. Component Responsibilities
| Component | Primary Responsibility | Example Task |
| :--- | :--- | :--- |
| **React Router** | Navigation | Switches the main view from "Dashboard" to "Invoices" when the sidebar link is clicked. |
| **Redux Store** | Global State | Remembers the user's "Dark Mode" preference across all pages. |
| **React Query** | Data Fetching & Caching | Fetches the "Monthly Spend" data once and keeps it ready so it doesn't need to reload every time the user looks at it. |
| **Tailwind CSS** | Styling | Ensures all buttons are the exact same shade of blue and responsive on mobile devices. |
| **Recharts** | Visualization | Draws the "Spend vs. Budget" line graph on the analytics page. |
## 5. Data Flow
1. **Trigger:** An Operations Manager selects "Last 30 Days" on the Analytics Dashboard.
2. **Request:** The "Analytics Component" asks the "Data Layer" (React Query) for data matching that date range.
3. **Fetch:** The Data Layer checks if it already has this info. If not, it calls the API (or mock service).
4. **Processing:** The API returns raw numbers. The "Business Logic" calculates the percentage growth.
5. **Update:** The application state updates with the new figures.
6. **Render:** The charts on the screen automatically redraw themselves to show the new trend lines.
## 6. External System Communication
The Web App serves as the central hub connecting various services:
* **Backend API:** The primary source of truth for all business data.
* **Authentication Provider:** Secures access to the dashboard.
* **Data Analysis Services:** Connects to AI/ML engines for the "Smart Strategies" and savings recommendations.
* **Payment Gateways:** Integrates with financial providers for processing large invoice payments.
## 7. Architectural Patterns
* **Feature-Sliced Design:** The project structure groups files by *feature* (e.g., `features/finance`, `features/analytics`) rather than technology. This means all the code related to "Invoicing" (the UI, the logic, the data calls) is in one place, making it easier to maintain.
* **Container/Presentational Pattern:** Logic-heavy components ("Containers") fetch data and pass it down to simple UI components ("Presentational") that just display it.
* **Single Source of Truth:** Uses Redux and React Query to ensure that if data changes in one place (e.g., a new invoice is created), every part of the app viewing that data updates instantly.
## 8. Key Design Decisions
* **React + Vite:** Chosen for blazing-fast development speed and high performance in the browser.
* **Tailwind CSS:** A "utility-first" styling framework that allows for rapid UI development and easy maintenance of a consistent design system.
* **React Query (TanStack Query):** Handles the complex job of fetching, caching, and synchronizing server data, significantly reducing the amount of "boilerplate" code developers need to write.
* **Mock Data Services:** Similar to the mobile apps, the web app uses a robust mock data layer (`services/mocks.ts`) to simulate complex scenarios (like thousands of data points for analytics) without needing a full backend during the prototype phase.
## 9. Overview Diagram
```mermaid
flowchart TD
subgraph WebApplication["Krow Web Application"]
direction TB
subgraph PresentationLayer["Presentation Layer (UI)"]
direction TB
Router["React Router"]
subgraph FeatureModules["Feature Modules"]
DashUI["Dashboard & Overview"]
AnalyticsUI["Analytics & Intelligence"]
WorkforceUI["Workforce & Operations"]
FinanceUI["Finance & Marketplace"]
SupportUI["Support & Communication"]
end
Router --> FeatureModules
end
subgraph StateManagement["State Management Layer"]
direction TB
Redux["Redux Store"]
ReactQuery["React Query Cache"]
end
subgraph DataLayer["Data Access Layer"]
direction TB
APIServices["API Services"]
MockServices["Mock Data Generator"]
end
PresentationLayer --> StateManagement
StateManagement --> DataLayer
end
subgraph ExternalSystems["External Systems"]
direction TB
BackendAPI["Backend API"]
AuthService["Auth Provider"]
AI_Engine["Data Analysis/AI Service"]
PaymentGateway["Payment Gateway"]
end
DataLayer --> ExternalSystems
%% Relationships & Data Flow
DashUI -- "Check Status" --> Redux
AnalyticsUI -- "Request Report" --> ReactQuery
ReactQuery -- "Fetch Data" --> APIServices
APIServices -- "API Call" --> BackendAPI
APIServices -- "Get AI Insights" --> AI_Engine
APIServices -- "Process Payment" --> PaymentGateway
MockServices -. "Simulation Mode" .-> ReactQuery
classDef layer fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
classDef module fill:#fff9c4,stroke:#fbc02d,stroke-width:1px,color:#000
classDef system fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
class PresentationLayer,StateManagement,DataLayer layer
class DashUI,AnalyticsUI,WorkforceUI,FinanceUI,SupportUI module
class ExternalSystems system
```

View 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
```

View File

@@ -149,14 +149,57 @@
/* Mermaid diagram styling */
.mermaid-diagram-wrapper {
position: relative;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
cursor: grab;
}
.mermaid-diagram-wrapper:active {
cursor: grabbing;
}
.mermaid-diagram-wrapper svg {
max-width: 100%;
max-width: none;
height: auto;
}
.mermaid-zoom-controls {
position: absolute;
top: 0.5rem;
right: 0.5rem;
display: flex;
gap: 0.25rem;
background: white;
border-radius: 0.5rem;
padding: 0.25rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
z-index: 10;
}
.mermaid-zoom-btn {
padding: 0.375rem;
background: white;
border: 1px solid #e5e7eb;
border-radius: 0.375rem;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.mermaid-zoom-btn:hover {
background-color: #f3f4f6;
}
.mermaid-zoom-btn svg {
width: 1rem;
height: 1rem;
color: #4b5563;
}
/* Loading Overlay */
#auth-loading {
@@ -494,6 +537,9 @@
let panzoomInstance = null;
let currentScale = 1;
// Track mermaid diagram panzoom instances
const mermaidPanzoomInstances = new Map();
// Initialize Mermaid
mermaid.initialize({
@@ -706,6 +752,63 @@
activeLink.classList.remove('text-gray-700');
activeLink.classList.add('bg-primary-50', 'border', 'border-primary-200', 'text-primary-700');
}
// Create zoom controls for mermaid diagrams
function createMermaidZoomControls(wrapper, svgElement, diagramId) {
const controls = document.createElement('div');
controls.className = 'mermaid-zoom-controls';
controls.innerHTML = `
<button class="mermaid-zoom-btn" data-action="zoom-in" title="Zoom In">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v6m3-3H7"></path>
</svg>
</button>
<button class="mermaid-zoom-btn" data-action="zoom-out" title="Zoom Out">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM13 10H7"></path>
</svg>
</button>
<button class="mermaid-zoom-btn" data-action="reset" title="Reset View">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
</button>
`;
wrapper.appendChild(controls);
// Wait for next frame to ensure DOM is fully updated before initializing Panzoom
requestAnimationFrame(() => {
// Initialize panzoom for this mermaid diagram
const panzoom = Panzoom(svgElement, {
canvas: true,
maxScale: 10,
minScale: 0.3,
startScale: 1
});
mermaidPanzoomInstances.set(diagramId, panzoom);
// Add event listeners
controls.querySelector('[data-action="zoom-in"]').addEventListener('click', (e) => {
e.stopPropagation();
panzoom.zoomIn();
});
controls.querySelector('[data-action="zoom-out"]').addEventListener('click', (e) => {
e.stopPropagation();
panzoom.zoomOut();
});
controls.querySelector('[data-action="reset"]').addEventListener('click', (e) => {
e.stopPropagation();
panzoom.reset();
});
// Add wheel zoom
wrapper.addEventListener('wheel', panzoom.zoomWithWheel);
});
}
async function showView(viewName, navLink, filePath, title, type = 'svg') {
setActiveNav(navLink);
@@ -713,6 +816,11 @@
panzoomInstance.destroy();
panzoomInstance = null;
}
// Clean up mermaid panzoom instances when switching views
mermaidPanzoomInstances.forEach(instance => instance.destroy());
mermaidPanzoomInstances.clear();
diagramContainer.innerHTML = '';
documentContainer.innerHTML = '';
// Reset iframe
@@ -841,10 +949,18 @@
const pre = block.parentElement;
try {
const { svg } = await mermaid.render(`mermaid-doc-${Date.now()}-${i}`, mermaidCode);
const diagramId = `mermaid-doc-${Date.now()}-${i}`;
const { svg } = await mermaid.render(diagramId, mermaidCode);
const wrapper = document.createElement('div');
wrapper.className = 'mermaid-diagram-wrapper bg-white p-4 rounded-lg border border-gray-200 my-4 overflow-x-auto';
wrapper.className = 'mermaid-diagram-wrapper bg-white p-4 rounded-lg border border-gray-200 my-4';
wrapper.innerHTML = svg;
const svgElement = wrapper.querySelector('svg');
if (svgElement) {
// Add zoom controls for this mermaid diagram
createMermaidZoomControls(wrapper, svgElement, diagramId);
}
pre.replaceWith(wrapper);
} catch (err) {
console.error('Mermaid rendering error:', err);

View File

@@ -2,7 +2,7 @@
.PHONY: launchpad-dev deploy-launchpad-hosting
launchpad-dev: sync-prototypes
launchpad-dev:
@echo "--> Starting local Launchpad server using Firebase Hosting emulator..."
@echo " - Generating secure email hashes..."
@node scripts/generate-allowed-hashes.js

View File

@@ -1,6 +1,6 @@
# --- Development Tools ---
.PHONY: install-git-hooks sync-prototypes install-melos
.PHONY: install-git-hooks sync-prototypes install-melos clean-branches
install-melos:
@if ! command -v melos >/dev/null 2>&1; then \
@@ -18,3 +18,39 @@ install-git-hooks:
sync-prototypes:
@echo "--> Synchronizing prototypes from external repository..."
@./scripts/sync-prototypes.sh
clean-branches:
@echo "--> Cleaning up local branches (keeping protected branches)..."
@CURRENT_BRANCH=$$(git branch --show-current); \
if [ "$$CURRENT_BRANCH" != "main" ] && [ "$$CURRENT_BRANCH" != "dev" ]; then \
echo "❌ Error: This command can only be run from 'main' or 'dev' branch."; \
echo " Current branch: $$CURRENT_BRANCH"; \
echo " Please checkout 'main' or 'dev' first."; \
exit 1; \
fi
@if [ ! -f "PROTECTED_BRANCHES.md" ]; then \
echo "⚠️ PROTECTED_BRANCHES.md not found. Aborting."; \
exit 1; \
fi
@echo "\nProtected branches (will NOT be deleted):"
@grep -E '^- `[^`]+`' PROTECTED_BRANCHES.md | sed 's/^- `\(.*\)`/ - \1/' 2>/dev/null || true
@echo "\n⚠ This will delete all other local branches."
@read -p "Are you sure? (y/N): " confirm && [ "$$confirm" = "y" ] || [ "$$confirm" = "Y" ] || (echo "Aborted." && exit 1)
@CURRENT_BRANCH=$$(git branch --show-current); \
if [ "$$CURRENT_BRANCH" != "main" ] && [ "$$CURRENT_BRANCH" != "dev" ] && ! echo "$$CURRENT_BRANCH" | grep -q '^demo/'; then \
echo "\n⚠ You are on branch '$$CURRENT_BRANCH' which will be deleted."; \
echo "Switching to 'dev' branch first..."; \
git checkout dev || (echo "❌ Failed to checkout dev branch" && exit 1); \
fi
@echo "\nDeleting branches..."
@DELETED=0; SKIPPED=0; \
for branch in $$(git branch | sed 's/^[* ] //' | grep -v '^main$$' | grep -v '^dev$$' | grep -v '^demo/'); do \
if grep -qE "^- \`$$branch\`" PROTECTED_BRANCHES.md 2>/dev/null; then \
echo " ⏭️ Skipping protected: $$branch"; \
SKIPPED=$$((SKIPPED + 1)); \
else \
echo " 🗑️ Deleting: $$branch"; \
git branch -D "$$branch" 2>/dev/null && DELETED=$$((DELETED + 1)) || echo " ⚠️ Failed to delete $$branch"; \
fi; \
done; \
echo "\n✅ Done! Deleted $$DELETED branch(es), skipped $$SKIPPED protected branch(es)."