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