feat: Initialize monorepo structure and comprehensive documentation

This commit establishes the new monorepo architecture for the KROW Workforce platform.

Key changes include:
- Reorganized project into `frontend-web`, `mobile-apps`, `firebase`, `scripts`, and `secrets` directories.
- Updated `Makefile` to support the new monorepo layout and automate Base44 export integration.
- Fixed `scripts/prepare-export.js` for ES module compatibility and global component import resolution.
- Created and updated `CONTRIBUTING.md` for developer onboarding.
- Restructured, renamed, and translated all `docs/` files for clarity and consistency.
- Implemented an interactive internal launchpad with diagram viewing capabilities.
- Configured base Firebase project files (`firebase.json`, security rules).
- Updated `README.md` to reflect the new project structure and documentation overview.
This commit is contained in:
bwnyasse
2025-11-12 12:50:55 -05:00
parent 92fd0118be
commit 554dc9f9e3
203 changed files with 1414 additions and 732 deletions

16
docs/00-vision.md Normal file
View File

@@ -0,0 +1,16 @@
# KROW Platform Vision
Our vision is to build a fully autonomous, modern, and scalable workforce management platform by leveraging a unified and productive tech stack.
## Core Objective
To achieve complete technical independence by consolidating the KROW platform (Web, Mobile Client, Mobile Staff) onto a single, robust, and maintainable ecosystem: **Firebase & Google Cloud**.
## Guiding Principles
1. **Velocity & Focus:** We will use tools that maximize the productivity of our small, focused development team. **Firebase Data Connect** and its generated SDKs are central to this principle.
2. **Unified Backend:** A single backend (Data Connect) will power all applications (Web, iOS, Android). This ensures data consistency, reduces code duplication, and simplifies maintenance.
3. **Scalability & Low Overhead:** We will rely on managed services (Cloud SQL, Firebase Auth, Firebase Hosting) to minimize operational burden and ensure high performance and reliability.
4. **Data Ownership & Future-Proofing:** We will have full control over our relational database (PostgreSQL). This is a strategic asset that will enable complex reporting and advanced features in the future.
5. **Base44 as a Design Accelerator:** We will treat the Base44 platform not as a system to migrate, but as an advanced visual prototyping tool. It defines the "what" (the UI/UX), and our team builds the "how" (the robust backend).
6. **Automation as a Force Multiplier:** We will automate all repetitive tasks (environment setup, deployment, testing) via a `Makefile` and CI/CD pipelines. This is crucial for our small team's efficiency and for reducing errors.

View File

@@ -0,0 +1,84 @@
# Product Roadmap: KROW Platform Foundation (3-Month Plan)
**Project Name:** KROW - New Platform Foundation
**Context:** We are leveraging the validated visual prototype from Base44 to rebuild the KROW platform on a modern, scalable, and proprietary technical infrastructure. This ensures a smooth transition and provides clear visibility on delivered features.
**3-Month Goal:** To have a functional and autonomous first version of the KROW platform, including a web dashboard for event management and a mobile app for staff, all running on our new Google Cloud infrastructure.
---
### **Detailed Product Roadmap (Client/CEO View)**
#### **Phase 1: From Vision to Technical Foundation**
**Goal of the Phase (for the client):** "We will transform your prototype into a concrete action plan. By the end of this phase, we will have a first version of the dashboard deployed where you can track our progress, and we will be fully independent to build and deploy future applications."
**Visible Features Delivered at the End of Phase 1:**
1. **A Preview Web Dashboard (React):**
* **Description:** A first version of the dashboard (based on the Base44 export) will be accessible via a private URL. Initially, the data will be static, but the visual interface will be live.
* **What this means for the client:** You will see the design and navigation of your dashboard come to life outside of Base44, on our own infrastructure.
2. **A Foundation for the New Mobile Apps:**
* **Description:** The skeletons of the new Flutter apps (Staff and Client) will be created, with a functional login system.
* **What this means for the client:** The foundations for the future apps will be ready, and we will have validated our ability to deploy them automatically to the app stores (TestFlight for Apple, Internal Testing for Google).
3. **A Documented V1 API Contract:**
* **Description:** A clear document that precisely describes how the frontend (web and mobile) will communicate with the backend. This is the "blueprint" of our system.
* **What this means for the client:** This guarantees that all parts of the KROW ecosystem (web, mobile, backend) will speak the same language, ensuring consistency and speed for future developments.
**Technical Work Behind the Scenes (for the team):**
* Analysis of the Base44 code.
* Setup of the infrastructure on Google Cloud (Cloud SQL, Firebase Auth, Data Connect).
* Configuration of CI/CD pipelines for web (e.g., GitHub Actions) and mobile (e.g., CodeMagic).
---
#### **Phase 2: The First Features Come to Life**
**Goal of the Phase (for the client):** "You will start seeing your own data (events, staff) appear in the new dashboard. The staff mobile app will no longer be an empty shell but will display actual shifts. We are establishing a workflow that will allow you to continue prototyping in parallel with our development."
**Visible Features Delivered at the End of Phase 2:**
1. **An Event Management Dashboard (Read-only):**
* **Description:** The web dashboard will display the list of your events, hubs, and staff, reading the data directly from our new database. Create/edit functionalities will not be active yet.
* **What this means for the client:** You will be able to view your real operational data on the new interface, validating that our backend is correctly connected.
2. **The Staff Mobile App (v2) Displays Real Shifts:**
* **Description:** A staff member will be able to log into the new app and see the list of shifts they are assigned to, with basic details (date, location, role).
* **What this means for the client:** The synergy between the backend and the mobile app is proven. The foundation is ready to add interactive features.
3. **An Established Design-to-Development Iteration Workflow:**
* **Description:** We will have a clear process to "freeze" a version of the Base44 design for development, while giving you the freedom to work on the next version.
* **What this means for the client:** You can continue to innovate and prototype on Base44 without fear of disrupting the development team's work.
**Technical Work Behind the Scenes:**
* Development of Data Connect queries to read data (`listEvents`, `listStaff`, etc.).
* Integration of TanStack Query in the dashboard for data management.
* Implementation of the service layer in the Flutter app to call the Data Connect SDK.
---
#### **Phase 3: The First Complete Business Flow**
**Goal of the Phase (for the client):** "By the end of this quarter, you will be able to perform a complete business action on the new platform: create a complex event on the web dashboard and instantly see the corresponding shifts appear on the staff mobile app."
**Visible Features Delivered at the End of Phase 3:**
1. **A Complete Event Creation and Modification Flow on the Web Dashboard:**
* **Description:** The event creation form will be fully functional. You will be able to create an event, add shifts, define positions with roles and rates, and assign contacts.
* **What this means for the client:** **You are now autonomous in managing the core of your operations on the new platform.** The Base44 prototype has been transformed into a functional production tool.
2. **Synchronization Between Web and Mobile:**
* **Description:** A shift created or modified on the web dashboard will be immediately (or almost immediately) visible and updated on the mobile app of the concerned staff member.
* **What this means for the client:** The vision of a unified and reactive ecosystem is now a tangible reality.
3. **A Stabilized Platform Ready for Growth:**
* **Description:** The technical foundation will have been tested, documented, and secured.
* **What this means for the client:** We have a solid foundation on which we can confidently build the more advanced features of your vision (KROW University, predictive AI, etc.).
**Technical Work Behind the Scenes:**
* Development of complex Data Connect mutations for create/edit logic.
* Implementation of unit tests and security reviews.
* Finalization of the V1 API documentation.

View File

@@ -0,0 +1,95 @@
# KROW Project Workflows
This document contains diagrams describing the technical architecture and collaboration processes for the project.
## 1. Web App Migration Architecture
This diagram illustrates the migration workflow for the web application. It shows how the UI is exported from the Base44 environment and then connected to our new, unified backend built on Firebase services.
```mermaid
graph LR
subgraph Base44 Environment
direction TB
Client[Client] -- Modifies --> B44_UI[<b>Base44 Visual Builder</b><br><i>Features:</i><br>- Event Management<br>- Staff Directory]
B44_UI --> B44_Backend[<b>Base44 Backend</b><br>Provides Schemas & SDK]
end
subgraph Firebase Ecosystem - GCP
direction TB
KROW_FE[<b>KROW Web Frontend</b><br>Vite/React + TanStack Query]
subgraph Firebase Services
direction TB
Auth[Firebase Authentication]
DataConnect[<b>Firebase Data Connect</b><br>GraphQL API]
SQL_DB[<b>Cloud SQL for PostgreSQL</b>]
end
KROW_FE -- "Uses" --> Auth
KROW_FE -- "Calls API via SDK" --> DataConnect
DataConnect -- "Manages & Queries" --> SQL_DB
end
B44_UI -- "<b>UI Code Export</b>" --> KROW_FE
style Client fill:#f9f,stroke:#333,stroke-width:2px
style B44_UI fill:#ffe,stroke:#333,stroke-width:2px
style KROW_FE fill:#eef,stroke:#333,stroke-width:2px
```
## 2. Mobile App Architecture
This diagram shows how the native mobile applications (Client and Staff) connect to the centralized Firebase backend. This backend is the same one used by the web application.
```mermaid
graph TD
subgraph KROW Mobile Applications
direction LR
Mobile_Client[<b>Mobile Client App</b><br>Flutter]
Mobile_Staff[<b>Mobile Staff App</b><br>Flutter]
end
subgraph Firebase Backend Services - GCP
direction TB
Auth[Firebase Authentication]
DataConnect[<b>Firebase Data Connect</b><br>GraphQL API &<br>Generated SDKs]
SQL_DB[<b>Cloud SQL for PostgreSQL</b><br><i>Managed by Data Connect</i>]
end
Mobile_Client -- "Authenticates with" --> Auth
Mobile_Client -- "Calls API via generated SDK" --> DataConnect
Mobile_Staff -- "Authenticates with" --> Auth
Mobile_Staff -- "Calls API via generated SDK" --> DataConnect
DataConnect -- "Manages & Queries" --> SQL_DB
style Mobile_Client fill:#eef,stroke:#333,stroke-width:2px
style Mobile_Staff fill:#eef,stroke:#333,stroke-width:2px
```
## 3. Collaboration Workflow for Modifications
This diagram formalizes the process to follow for any modifications initiated by the client on the Base44 platform. The objective is to control the pace of changes and evaluate their impact on our backend before integration.
```mermaid
flowchart TD
A[Client identifies a need<br>for modification] --> B{Define functionality<br>and scope};
B --> C{Does the modification impact<br>only the UI or also<br>logic/data?};
C -- "UI Only" --> D[Client makes modifications<br>on Base44];
C -- "Logic/Data" --> E[Team-Client Coordination<br>to assess impact on GCP backend];
D --> F[Planned export of the<br>new UI version];
E --> F;
F --> G["Developer runs the automation<br>1. `make integrate-export`<br>2. `make prepare-export`"];
G --> H[Development & Testing<br>- Adapt GCP backend if needed<br>- Validate locally];
H --> I[✅ Integration complete];
style A fill:#f9f,stroke:#333,stroke-width:2px
style D fill:#f9f,stroke:#333,stroke-width:2px
```

View File

@@ -0,0 +1,131 @@
# KROW Workforce API Specification (GCP Migration)
**Version:** 2.0
**Date:** 2025-11-11
**Objective:** This document defines the backend API to be built on the Firebase/GCP ecosystem, replacing the Base44 backend. It is based on the comprehensive Base44 API documentation (v2.0) and will guide the development of the new backend using Firebase Data Connect and Cloud Functions.
---
## General Conventions
- **API Layer:** The backend will be composed of two main parts:
- **Firebase Data Connect:** A GraphQL API for all data-centric (CRUD) operations.
- **Cloud Functions:** A set of RESTful endpoints for all service-centric operations (e.g., sending emails, processing files).
- **Authentication:** Every request must include an `Authorization: Bearer <Firebase-Auth-Token>` header, managed and validated by Firebase.
- **Data Format:** All requests and responses will be in `application/json` format.
- **Error Responses:** Errors will use standard HTTP status codes (400, 401, 403, 404, 500) and include a JSON response body of the form `{ "error": "Problem description" }`.
- **Common Fields:** Each entity will have the following fields, automatically managed by the backend:
- `id`: `string` (UUID, Primary Key)
- `created_date`: `string` (ISO 8601 Timestamp)
- `updated_date`: `string` (ISO 8601 Timestamp)
- `created_by`: `string` (Email of the creating user)
---
## 1. Authentication (Firebase Auth)
Authentication will be handled entirely by Firebase Authentication. The client applications (web and mobile) are responsible for the sign-up and sign-in flows using the Firebase SDK. The backend will use the provided auth token to identify the user for all subsequent requests.
### `User` Entity (Managed by Firebase Auth & Data Connect)
| Field | Type | Description |
| ----------- | -------- | ----------------------------------------- |
| `id` | `string` | Firebase User ID (UID) |
| `email` | `string` | User's email (non-modifiable) |
| `full_name` | `string` | Full name |
| `user_role` | `string` | Custom application role (`admin`, `procurement`, `client`...) |
| `...other` | `any` | Other custom fields can be added. |
---
## 2. Data API (Firebase Data Connect)
All entities below will be managed via a GraphQL API powered by Firebase Data Connect. For each entity, standard `query` (list, get by ID) and `mutation` (create, update, delete) operations will be defined in the `firebase/dataconnect/` directory.
### 2.1. Event
**Description:** Manages events and workforce orders.
| Field | Type | Description |
| ----------------------- | --------- | ------------------------------------------------ |
| `event_name` | `string` | Name of the event (required) |
| `is_recurring` | `boolean` | Indicates if the event is recurring |
| `recurrence_type` | `string` | `single`, `date_range`, `scatter` |
| `business_id` | `string` | ID of the client (`Business`) |
| `vendor_id` | `string` | ID of the provider (`Vendor`) |
| `status` | `string` | `Draft`, `Active`, `Pending`, `Assigned`, `Confirmed`, `Completed`, `Canceled` |
| `date` | `string` | Event date (ISO 8601) |
| `shifts` | `jsonb` | Array of `Shift` objects |
| `total` | `number` | Total cost |
| `requested` | `number` | Total number of staff requested |
| `assigned_staff` | `jsonb` | Array of assigned staff objects |
### 2.2. Staff
**Description:** Manages staff members.
| Field | Type | Description |
| ------------------------- | --------- | ----------------------------------------- |
| `employee_name` | `string` | Full name (required) |
| `vendor_id` | `string` | ID of the provider (`Vendor`) |
| `email` | `string` | Email address |
| `position` | `string` | Primary job position/skill |
| `employment_type` | `string` | `Full Time`, `Part Time`, `On call`, etc. |
| `rating` | `number` | Performance rating (0-5) |
| `reliability_score` | `number` | Reliability score (0-100) |
| `background_check_status` | `string` | `pending`, `cleared`, `failed`, `expired` |
| `certifications` | `jsonb` | List of certifications |
### 2.3. Vendor
**Description:** Manages providers and their onboarding.
| Field | Type | Description |
| ----------------------- | --------- | ----------------------------------------- |
| `vendor_number` | `string` | Vendor number (e.g., `VN-####`) |
| `legal_name` | `string` | Legal company name (required) |
| `primary_contact_email` | `string` | Primary contact email (required) |
| `approval_status` | `string` | `pending`, `approved`, `suspended`, `terminated` |
| `is_active` | `boolean` | Active status |
| `w9_document` | `string` | URL or URI of the W9 document |
| `coi_document` | `string` | URL or URI of the Certificate of Insurance|
---
*Note: For brevity, only the most critical entities have been detailed. The same structure (Schema defined in GraphQL) must be applied for all other entities: `VendorRate`, `Invoice`, `Business`, `Certification`, `Team`, `Conversation`, `Message`, `ActivityLog`, `Enterprise`, `Sector`, `Partner`, `Order`, and `Shift`, based on the `07-reference-base44-api-export.md` document.*
---
## 3. Services API (Cloud Functions)
These endpoints are not for CRUD operations but for specific, service-oriented tasks. They will be implemented as individual HTTP-triggered Cloud Functions.
### `POST /sendEmail`
- **Description:** Sends an email.
- **Original SDK:** `base44.integrations.Core.SendEmail(params)`
- **Body:** `{ "to": "...", "subject": "...", "body": "..." }`
- **Response (200 OK):** `{ "status": "sent" }`
### `POST /invokeLLM`
- **Description:** Calls a large language model (Vertex AI).
- **Original SDK:** `base44.integrations.Core.InvokeLLM(params)`
- **Body:** `{ "prompt": "...", "response_json_schema": {...}, "file_urls": [...] }`
- **Response (200 OK):** `{ "result": "..." }`
### `POST /uploadFile`
- **Description:** Handles the upload of public files to Google Cloud Storage and returns a public URL.
- **Original SDK:** `base44.integrations.Core.UploadFile({ file })`
- **Request:** `multipart/form-data`.
- **Response (200 OK):** `{ "file_url": "https://..." }`
### `POST /uploadPrivateFile`
- **Description:** Handles the upload of private files to Google Cloud Storage and returns a secure URI.
- **Original SDK:** `base44.integrations.Core.UploadPrivateFile({ file })`
- **Request:** `multipart/form-data`.
- **Response (200 OK):** `{ "file_uri": "gs://..." }`
### `POST /createSignedUrl`
- **Description:** Creates a temporary access URL for a private file.
- **Original SDK:** `base44.integrations.Core.CreateFileSignedUrl(params)`
- **Body:** `{ "file_uri": "...", "expires_in": 3600 }`
- **Response (200 OK):** `{ "signed_url": "https://..." }`

View File

@@ -0,0 +1,41 @@
# KROW Technical Roadmap
This document outlines the technical strategy for building the new, autonomous KROW platform. It is structured in phases rather than fixed dates to maintain agility.
```mermaid
gantt
title KROW Platform Build Roadmap
dateFormat W
axisFormat Week %W
section Phase 1: Foundation & Dev Environment Setup
Infrastructure Setup : 1, 1w
GraphQL Schema Definition : 1, 1w
Data Connect Deployment (Dev): 2, 1w
SDK Generation & Web/Mobile PoC : 3, 1w
section Phase 2: Core Feature Implementation
Backend Logic (All Entities): 4, 4w
Web App Re-wiring : 4, 4w
Mobile Apps Re-wiring : 5, 4w
section Phase 3: Production Readiness & Go-Live
CI/CD Pipelines Setup : 9, 2w
Staging Env Deployment & E2E Testing : 10, 2w
Production Deployment & Data Import : 12, 1w
Monitoring & Security : 12, 1w
```
---
## Phase 1: Foundation & Dev Environment Setup (~3-4 Weeks)
* **Goal:** To have a fully functional, shared `dev` environment in the cloud. All developers can connect to it from their local machines.
* **Key Milestone:** The web app and a mobile app screen can successfully authenticate and fetch live data from the `dev` Firebase/GCP project.
## Phase 2: Core Feature Implementation (~5-6 Weeks)
* **Goal:** To achieve functional parity with the Base44 prototype across all three platforms, all powered by our shared `dev` backend.
* **Key Milestone:** The full lifecycle of core features (Event, Staff, Vendor management) is functional on all apps.
## Phase 3: Production Readiness & Go-Live (~4 Weeks)
* **Goal:** To automate, secure, and deploy the entire platform to production.
* **Key Milestone:** The KROW platform is live on production infrastructure. The team has a repeatable, automated process for future deployments.

77
docs/05-project-plan.md Normal file
View File

@@ -0,0 +1,77 @@
# KROW Project Plan & Task Breakdown
This document breaks down the technical roadmap into actionable tasks, assigned by role, ready to be converted into GitHub Issues.
---
## Milestone 1: Foundation & Dev Environment Setup
*Goal: Establish a fully functional, shared `dev` environment on GCP/Firebase that all developers can connect to.*
### Infrastructure & Tooling (Primarily CTO)
- **Issue:** `[Infra] Setup Enpass for Team Credential Management`
- **Description:** Configure the team's Enpass vault and establish the process for sharing secrets and service account keys.
- **Issue:** `[Infra] Create GCP/Firebase Projects (dev, staging, prod)`
- **Description:** Set up the three distinct Google Cloud projects and associated Firebase projects. Enable required APIs (Auth, Cloud SQL, Data Connect).
- **Issue:** `[Infra] Create Multi-Env Makefile`
- **Description:** Create the main `Makefile` inspired by the reference project. It should handle environment switching (`ENV=dev/staging`) and orchestrate all build/deploy tasks.
- **Issue:** `[Infra] Setup Shared Dev Database`
- **Description:** Provision the initial Cloud SQL for PostgreSQL instance for the `dev` environment.
### Backend & Web (Dev 1)
- **Issue:** `[Backend] Define GraphQL Schema for Core Entities`
- **Description:** Translate `Event`, `Staff`, `Vendor`, and `User` schemas from `api_specification.md` into `.gql` files for Data Connect.
- **Issue:** `[Backend] Deploy Initial Schema & Operations to Dev Env`
- **Description:** Use the `Makefile` to deploy the initial Data Connect schema and basic `list/get` queries to the `dev` project.
- **Issue:** `[Web] Generate TypeScript SDK for Dev Env`
- **Description:** Configure and run the SDK generation command to create the TypeScript SDK pointing to the `dev` environment.
- **Issue:** `[Web] Connect Web App to Dev Backend`
- **Description:** Modify the web app to use the generated SDK. The goal is to authenticate and display a list of events from the shared `dev` backend.
### Mobile (Dev 2)
- **Issue:** `[Mobile] Generate Flutter SDK for Dev Env`
- **Description:** Configure and run the SDK generation command to create the Flutter SDK pointing to the `dev` environment.
- **Issue:** `[Mobile] Implement Firebase Auth Flow`
- **Description:** Ensure both mobile apps can sign in and sign up using Firebase Auth against the `dev` project.
- **Issue:** `[Mobile] Create Proof-of-Concept Screen`
- **Description:** Build a simple screen in the Staff app that authenticates and fetches a list of events from the `dev` backend using the new SDK.
---
## Milestone 2: Core Feature Implementation
*Goal: Achieve functional parity with the Base44 prototype across all platforms, using the shared `dev` backend.*
### Backend (Dev 1)
- **Epic:** `[Backend] Implement Full API Logic`
- **Description:** Create all necessary GraphQL queries and mutations in Data Connect for all entities defined in `api_specification.md`. Deploy them continuously to the `dev` environment.
### Web (Dev 1, with support from Dev 2)
- **Epic:** `[Web] Full Application Re-wiring`
- **Description:** Systematically replace all data-fetching logic in the web app to use the TanStack Query hooks from the generated Data Connect SDK.
### Mobile (Dev 2)
- **Epic:** `[Mobile] Full Application Re-wiring`
- **Description:** Refactor the `repositories` and `api_providers` in both the Client and Staff Flutter apps to use the generated Data Connect SDK for all network calls.
---
## Milestone 3: Production Readiness & Go-Live
*Goal: Automate, secure, and deploy the entire platform to production.*
### Infrastructure & DevOps (CTO & Team)
- **Issue:** `[CI/CD] Configure Web App Deployment Pipeline`
- **Description:** Set up a GitHub Actions pipeline that builds and deploys the web app to Firebase Hosting, with separate jobs for `staging` and `prod`.
- **Issue:** `[CI/CD] Configure Mobile App Deployment with CodeMagic`
- **Description:** Set up CodeMagic pipelines to build and deploy the iOS and Android apps to TestFlight/Play Store Internal Testing.
- **Issue:** `[CI/CD] Configure Backend Deployment Pipeline`
- **Description:** Automate the deployment of the Data Connect schema and operations (`firebase deploy --only dataconnect`).
- **Issue:** `[Data] Create & Test Initial Data Import Scripts`
- **Description:** Write scripts to populate the production database with any necessary initial data.
- **Issue:** `[QA] Deploy to Staging & Perform E2E Testing`
- **Description:** Use the `Makefile` (`make deploy ENV=staging`) to deploy the entire stack to the staging environment for full end-to-end testing.
- **Issue:** `[Ops] Final Production Deployment`
- **Description:** Run the production deployment (`make deploy ENV=prod`) and execute data import scripts.
- **Issue:** `[Ops] Setup Monitoring & Alerting`
- **Description:** Configure monitoring dashboards in Google Cloud for the database, API, and application performance.

View File

@@ -0,0 +1,55 @@
# API Documentation Maintenance Guide
This document describes the procedure for updating the API documentation and our backend's technical specification after major changes are made on the Base44 platform.
Following this process is **essential** to ensure that our custom backend on GCP remains synchronized with the frontend's features.
## When to Follow This Procedure
You should follow this guide after each significant development cycle on the Base44 platform, especially after:
- Adding new entities or data fields.
- Modifying existing business logic.
- Integrating major new features into the user interface.
---
## Update Procedure
### Step 1: Obtain Updated Documentation from Base44
1. **Open the `docs/08-reference-base44-prompts.md` file**.
2. Copy the content of the **"Main Prompt"**.
3. Paste this prompt into the Base44 AI chat to request the latest documentation.
4. **Verification:** The AI should return the full content of the `base44-api-export.md` file. If it only returns a summary, use the following simple prompt to request the full content:
```text
Thank you for the summary. Please provide the entire, updated content of the API documentation file now.
```
### Step 2: Update the Local Documentation File (with Gemini CLI)
To ensure clean and consistent formatting, it is recommended to use the Gemini CLI for this step.
1. **Copy the raw content** provided by the Base44 AI.
2. **Provide this content to the Gemini CLI** with a simple prompt, for example:
> "Here is the new Base44 API documentation. Can you reformat this content and update the `docs/07-reference-base44-api-export.md` file?"
3. **Let the Gemini CLI** handle the file creation or update. It will ensure that tables, code blocks, and headers are correctly formatted.
### Step 3: Update the GCP API Specification (with Gemini CLI)
This is the most critical step. Instead of a tedious manual comparison, we will rely on the AI to synchronize our migration plan.
1. **Ensure Step 2 is complete** and that `docs/07-reference-base44-api-export.md` is up-to-date.
2. **Ask the Gemini CLI** to update the specification for you. Use a clear prompt, for example:
> "Now that `docs/07-reference-base44-api-export.md` is updated, can you analyze the changes and comprehensively update the `docs/03-backend-api-specification.md` file to match?"
3. **Let the Gemini CLI** perform the comparative analysis and apply the necessary changes (adding fields, entities, integrations, etc.) to the specification file.
### Step 4: Validate and Commit the Changes
1. Give the changes in `03-backend-api-specification.md` a final review to ensure they are consistent.
2. Commit the updated files to Git with a clear and descriptive message.
```bash
git add docs/
git commit -m "docs: Update API documentation and specification from Base44 export"
```
---

View File

@@ -1,10 +1,10 @@
# Prompts pour l'IA de Base44
# Prompts for the Base44 AI
Ce fichier contient des prompts standardisés à utiliser avec l'intelligence artificielle de la plateforme Base44. L'objectif est d'obtenir des informations précises et bien structurées sur l'API et les schémas de données du projet "KROW Workforce" afin de faciliter la construction d'intégrations et, si nécessaire, la migration future.
This file contains standardized prompts for use with the Base44 platform's artificial intelligence. The goal is to obtain precise and well-structured information about the "KROW Workforce" project's API and data schemas to facilitate the development of integrations and, if necessary, future migration.
## 1. Prompt Principal : Demande de Documentation Complète (Version Discrète et Itérative)
## 1. Main Prompt: Request for Complete Documentation (Discreet and Iterative Version)
*Utilisez ce prompt après chaque nouvel export du frontend depuis Base44. Il est formulé pour ne pas révéler l'intention de migration en demandant une mise à jour d'un document existant.*
*Use this prompt after each new frontend export from Base44. It is phrased to avoid revealing the intention to migrate by requesting an update to an existing document.*
---
@@ -36,9 +36,9 @@ Thank you!
---
## 2. Prompt Secondaire : Demande de Schéma pour une Entité Spécifique
## 2. Secondary Prompt: Request for a Specific Entity Schema
*Utilisez ce prompt si vous avez besoin de vérifier rapidement la structure d'une seule entité sans demander la documentation complète.*
*Use this prompt if you need to quickly verify the structure of a single entity without requesting the full documentation.*
---
@@ -52,4 +52,4 @@ Please format the response as a JSON Schema or a Markdown table, including the f
For example, for an entity named `Event`.
```
---
---

View File

@@ -1,55 +0,0 @@
# Guide de Maintenance de la Documentation API
Ce document décrit la procédure à suivre pour mettre à jour la documentation de l'API et la spécification technique de notre backend après des modifications majeures sur la plateforme Base44.
Suivre ce processus est **essentiel** pour garantir que notre backend personnalisé sur GCP reste synchronisé avec les fonctionnalités du frontend.
## Quand Lancer cette Procédure ?
Vous devez suivre ce guide après chaque cycle de développement significatif sur la plateforme Base44, notamment après :
- L'ajout de nouvelles entités ou de nouveaux champs de données.
- La modification de la logique métier existante.
- L'intégration de nouvelles fonctionnalités majeures dans l'interface utilisateur.
---
## Procédure de Mise à Jour
### Étape 1 : Obtenir la Documentation à Jour de Base44
1. **Ouvrez le fichier `docs/base44_prompts.md`**.
2. Copiez le contenu du **"Prompt Principal"**.
3. Collez ce prompt dans le chat de l'IA de Base44 pour lui demander de générer la documentation la plus récente.
4. **Vérification :** L'IA doit retourner le contenu complet du fichier `API_documentation.md`. Si elle ne retourne qu'un résumé, utilisez le prompt simple suivant pour demander le contenu complet :
```text
Thank you for the summary. Please provide the entire, updated content of the API_documentation.md file now.
```
### Étape 2 : Mettre à Jour le Fichier de Documentation Local (avec Gemini CLI)
Pour garantir un formatage propre et cohérent, il est recommandé d'utiliser Gemini CLI pour cette étape.
1. **Copiez le contenu brut** fourni par l'IA de Base44.
2. **Donnez ce contenu à Gemini CLI** avec un prompt simple, par exemple :
> "Voici la nouvelle documentation de l'API Base44. Peux-tu reformater ce contenu et mettre à jour le fichier `docs/API_documentation.md` ?"
3. **Laissez Gemini CLI** gérer la création ou la mise à jour du fichier. Il s'assurera que les tableaux, les blocs de code et les en-têtes sont correctement formatés.
### Étape 3 : Mettre à Jour la Spécification de l'API GCP (avec Gemini CLI)
C'est l'étape la plus critique. Au lieu d'une comparaison manuelle fastidieuse, nous allons nous appuyer sur l'IA pour synchroniser notre plan de migration.
1. **Assurez-vous que l'Étape 2 est terminée** et que `docs/API_documentation.md` est à jour.
2. **Demandez à Gemini CLI** de mettre à jour la spécification pour vous. Utilisez un prompt clair, par exemple :
> "Maintenant que `docs/API_documentation.md` est à jour, peux-tu analyser les changements et mettre à jour de manière exhaustive le fichier `docs/api_specification.md` pour qu'il corresponde ?"
3. **Laissez Gemini CLI** effectuer l'analyse comparative et appliquer les modifications nécessaires (ajout de champs, d'entités, d'intégrations, etc.) au fichier de spécification.
### Étape 4 : Valider et Commiter les Changements
1. Relisez une dernière fois les modifications apportées à `api_specification.md` pour vous assurer qu'elles sont cohérentes.
2. Commitez les fichiers mis à jour dans Git avec un message clair et descriptif.
```bash
git add docs/API_documentation.md docs/api_specification.md docs/MAINTENANCE_GUIDE.md
git commit -m "docs: Update API documentation and specification from Base44 export"
```
---

View File

@@ -1,238 +0,0 @@
# Spécification de l'API KROW Workforce (Migration GCP)
**Version :** 2.0
**Date :** 11/11/2025
**Objectif :** Ce document définit l'API RESTful à construire sur Google Cloud Platform (Cloud Functions, Cloud SQL) pour remplacer le backend Base44. Il est basé sur la documentation exhaustive de l'API Base44 (v2.0) et a pour but de guider le développement du nouveau backend.
---
## Conventions Générales
- **URL de base :** `/api/v1`
- **Authentification :** Chaque requête (sauf `POST /login` et `GET /health`) doit inclure un header `Authorization: Bearer <Firebase-Auth-Token>`.
- **Format des données :** Toutes les requêtes et réponses seront au format `application/json`.
- **Réponses d'erreur :** Les erreurs utiliseront les codes de statut HTTP standards (400, 401, 403, 404, 500) et incluront un corps de réponse JSON de la forme `{ "error": "Description du problème" }`.
- **Champs Communs :** Chaque entité aura les champs suivants, gérés automatiquement par le backend :
- `id`: `string` (UUID, Clé primaire)
- `created_date`: `string` (ISO 8601 Timestamp)
- `updated_date`: `string` (ISO 8601 Timestamp)
- `created_by`: `string` (Email de l'utilisateur créateur)
---
## 1. Authentification (`/auth`)
Basé sur Firebase Authentication. Le frontend gère l'inscription et la connexion avec le SDK Firebase. Notre backend a besoin d'un endpoint pour récupérer les informations étendues de l'utilisateur.
### Entité `User` (Basée sur `base44.auth.me`)
| Champ | Type | Description |
| --------------- | -------- | ----------------------------------------- |
| `id` | `string` | ID Firebase de l'utilisateur |
| `email` | `string` | Email de l'utilisateur (non modifiable) |
| `full_name` | `string` | Nom complet |
| `user_role` | `string` | Rôle personnalisé dans l'application (`admin`, `procurement`, `client`...) |
| `...autres` | `any` | D'autres champs personnalisés peuvent être ajoutés. |
### Endpoints
#### `GET /auth/me`
- **Description :** Récupère les informations du profil de l'utilisateur actuellement authentifié.
- **SDK d'origine :** `base44.auth.me()`
- **Réponse (200 OK) :** L'objet `User` complet.
#### `PUT /auth/me`
- **Description :** Met à jour le profil de l'utilisateur actuel.
- **SDK d'origine :** `base44.auth.updateMe(data)`
- **Corps de la requête :** Un objet avec les champs de `User` à mettre à jour.
- **Réponse (200 OK) :** L'objet `User` mis à jour.
---
## 2. Entités (Endpoints CRUD)
Pour chaque entité ci-dessous, les endpoints standards suivants sont à implémenter.
- `POST /{nom-entite}`: Crée une nouvelle entrée.
- `GET /{nom-entite}`: Liste les entrées, avec support pour le filtrage et le tri via des query params.
- `GET /{nom-entite}/{id}`: Récupère une entrée par son ID.
- `PUT /{nom-entite}/{id}`: Met à jour une entrée par son ID.
- `DELETE /{nom-entite}/{id}`: Supprime une entrée par son ID.
### 2.1. Event (`/events`)
**Description :** Gère les événements et les commandes de main-d'œuvre.
| Champ | Type | Description |
| ----------------------- | --------- | ------------------------------------------------ |
| `event_name` | `string` | Nom de l'événement (requis) |
| `is_recurring` | `boolean` | Indique si l'événement est récurrent |
| `recurrence_type` | `string` | `single`, `date_range`, `scatter` |
| `recurrence_start_date` | `string` | Date de début de récurrence (ISO 8601) |
| `recurrence_end_date` | `string` | Date de fin de récurrence (ISO 8601) |
| `scatter_dates` | `array` | Tableau de dates (ISO 8601) pour `scatter` |
| `business_id` | `string` | ID du client (`Business`) |
| `business_name` | `string` | Nom du client |
| `vendor_id` | `string` | ID du fournisseur (`Vendor`) |
| `vendor_name` | `string` | Nom du fournisseur |
| `hub` | `string` | Lieu/hub |
| `contract_type` | `string` | `W2`, `1099`, `Temp`, `Contract` |
| `po_reference` | `string` | Référence de bon de commande |
| `status` | `string` | `Draft`, `Active`, `Pending`, `Assigned`, `Confirmed`, `Completed`, `Canceled` |
| `date` | `string` | Date de l'événement (ISO 8601) |
| `shifts` | `array` | Tableau d'objets `Shift` |
| `addons` | `object` | Services additionnels |
| `total` | `number` | Coût total |
| `client_name` | `string` | Nom du contact client |
| `client_email` | `string` | Email du contact client |
| `client_phone` | `string` | Téléphone du contact client |
| `notes` | `string` | Notes additionnelles |
| `requested` | `number` | Nombre total de personnel demandé |
| `assigned_staff` | `array` | Tableau d'objets de personnel assigné |
### 2.2. Staff (`/staff`)
**Description :** Gère les membres du personnel.
| Champ | Type | Description |
| ------------------------- | --------- | ----------------------------------------- |
| `employee_name` | `string` | Nom complet (requis) |
| `vendor_id` | `string` | ID du fournisseur (`Vendor`) |
| `vendor_name` | `string` | Nom du fournisseur |
| `manager` | `string` | Nom du manager |
| `contact_number` | `string` | Numéro de contact principal |
| `phone` | `string` | Autre téléphone |
| `email` | `string` | Adresse email |
| `department` | `string` | `Operations`, `Sales`, `HR`, etc. |
| `hub_location` | `string` | Lieu/hub de rattachement |
| `address` | `string` | Adresse de l'employé |
| `city` | `string` | Ville |
| `position` | `string` | Poste/compétence principal(e) |
| `position_2` | `string` | Poste/compétence secondaire |
| `profile_type` | `string` | `Skilled`, `Beginner`, `Cross-Trained` |
| `employment_type` | `string` | `Full Time`, `Part Time`, `On call`, etc. |
| `english` | `string` | `Fluent`, `Intermediate`, `Basic`, `None` |
| `rating` | `number` | Note de performance (0-5) |
| `shift_coverage_percentage`| `number` | Pourcentage de shifts couverts (0-100) |
| `cancellation_count` | `number` | Nombre d'annulations |
| `no_show_count` | `number` | Nombre de non-présentations |
| `total_shifts` | `number` | Nombre total de shifts assignés |
| `reliability_score` | `number` | Score de fiabilité (0-100) |
| `background_check_status` | `string` | `pending`, `cleared`, `failed`, `expired` |
| `background_check_date` | `string` | Date du dernier contrôle (ISO 8601) |
| `certifications` | `array` | Liste des certifications |
### 2.3. Vendor (`/vendors`)
**Description :** Gère les fournisseurs et leur onboarding.
| Champ | Type | Description |
| ----------------------- | --------- | ----------------------------------------- |
| `vendor_number` | `string` | Numéro de fournisseur (ex: `VN-####`) |
| `legal_name` | `string` | Nom légal de l'entreprise (requis) |
| `doing_business_as` | `string` | Nom commercial (DBA) |
| `region` | `string` | `National`, `Bay Area`, etc. |
| `primary_contact_email` | `string` | Email du contact principal (requis) |
| `approval_status` | `string` | `pending`, `approved`, `suspended`, `terminated` |
| `is_active` | `boolean` | Statut d'activité |
| `tax_id` | `string` | Numéro d'identification fiscale (EIN) |
| `business_type` | `string` | `Corporation`, `LLC`, etc. |
| `insurance_certificate` | `string` | URL du certificat d'assurance |
| `insurance_expiry` | `string` | Date d'expiration de l'assurance (ISO 8601) |
| `w9_document` | `string` | URL du document W9 |
| `coi_document` | `string` | URL du document COI |
### 2.4. VendorRate (`/vendor-rates`)
**Description :** Gère les grilles tarifaires des fournisseurs.
| Champ | Type | Description |
| ----------------- | --------- | ----------------------------------------- |
| `vendor_id` | `string` | ID du fournisseur (`Vendor`) |
| `vendor_name` | `string` | Nom du fournisseur (requis) |
| `category` | `string` | Catégorie de service (`Kitchen`, etc.) |
| `role_name` | `string` | Nom du poste (requis) |
| `employee_wage` | `number` | Salaire horaire de l'employé (requis) |
| `client_rate` | `number` | Tarif horaire facturé au client (requis) |
| `pricing_status` | `string` | `optimal`, `underpriced`, `overpriced` |
| `is_active` | `boolean` | Statut d'activité |
### 2.5. Invoice (`/invoices`)
**Description :** Gère les factures.
| Champ | Type | Description |
| ---------------- | -------- | ----------------------------------------- |
| `invoice_number` | `string` | Numéro de facture (requis) |
| `event_id` | `string` | ID de l'événement (`Event`) |
| `business_name` | `string` | Nom du client (requis) |
| `vendor_name` | `string` | Nom du fournisseur |
| `amount` | `number` | Montant de la facture (requis) |
| `status` | `string` | `Open`, `Paid`, `Overdue`, `Disputed`, etc. |
| `issue_date` | `string` | Date d'émission (ISO 8601, requis) |
| `due_date` | `string` | Date d'échéance (ISO 8601, requis) |
| `paid_date` | `string` | Date de paiement (ISO 8601) |
### 2.6. Business (`/businesses`)
**Description :** Gère les entreprises clientes.
| Champ | Type | Description |
| -------------- | -------- | ----------------------------------------- |
| `business_name`| `string` | Nom de l'entreprise (requis) |
| `contact_name` | `string` | Nom du contact principal (requis) |
| `email` | `string` | Email de l'entreprise |
| `phone` | `string` | Téléphone de l'entreprise |
| `sector` | `string` | `Bon Appétit`, `Eurest`, etc. |
| `rate_group` | `string` | `Standard`, `Premium`, etc. (requis) |
| `status` | `string` | `Active`, `Inactive`, `Pending` |
---
*Note : Pour la concision, seules les entités les plus critiques ont été entièrement détaillées. La même structure (Schéma + Endpoints) doit être appliquée pour : `Certification`, `Team`, `Conversation`, `Message`, `ActivityLog`, `Enterprise`, `Sector`, `Partner`, `Order`, et `Shift` en se basant sur `API_documentation.md`.*
---
## 3. Services d'Intégration
### `POST /integrations/invoke-llm`
- **Description :** Fait appel à un modèle de langage (Vertex AI).
- **SDK d'origine :** `base44.integrations.Core.InvokeLLM(params)`
- **Body :** `{ "prompt": "...", "response_json_schema": {...}, "file_urls": [...] }`
- **Réponse (200 OK) :** `{ "result": "..." }`
### `POST /integrations/send-email`
- **Description :** Envoie un email.
- **SDK d'origine :** `base44.integrations.Core.SendEmail(params)`
- **Body :** `{ "to": "...", "subject": "...", "body": "..." }`
- **Réponse (200 OK) :** `{ "status": "sent" }`
### `POST /integrations/upload-file`
- **Description :** Gère le téléversement de fichiers publics vers Google Cloud Storage.
- **SDK d'origine :** `base44.integrations.Core.UploadFile({ file })`
- **Requête :** `multipart/form-data`.
- **Réponse (200 OK) :** `{ "file_url": "https://..." }`
### `POST /integrations/upload-private-file`
- **Description :** Gère le téléversement de fichiers privés vers Google Cloud Storage.
- **SDK d'origine :** `base44.integrations.Core.UploadPrivateFile({ file })`
- **Requête :** `multipart/form-data`.
- **Réponse (200 OK) :** `{ "file_uri": "gs://..." }`
### `POST /integrations/create-signed-url`
- **Description :** Crée une URL d'accès temporaire pour un fichier privé.
- **SDK d'origine :** `base44.integrations.Core.CreateFileSignedUrl(params)`
- **Body :** `{ "file_uri": "...", "expires_in": 3600 }`
- **Réponse (200 OK) :** `{ "signed_url": "https://..." }`
### `POST /integrations/extract-data`
- **Description :** Extrait des données structurées d'un fichier (CSV, PDF...).
- **SDK d'origine :** `base44.integrations.Core.ExtractDataFromUploadedFile(params)`
- **Body :** `{ "file_url": "...", "json_schema": {...} }`
- **Réponse (200 OK) :** `{ "status": "success", "output": [...] }`
### `POST /integrations/generate-image`
- **Description :** Génère une image via une IA.
- **SDK d'origine :** `base44.integrations.Core.GenerateImage(params)`
- **Body :** `{ "prompt": "..." }`
- **Réponse (200 OK) :** `{ "url": "https://..." }`

View File

@@ -1,180 +0,0 @@
# Guide de Lancement Local et de Migration pour un Projet Exporté de Base44
Ce guide documente les étapes nécessaires pour prendre un projet frontend exporté de la plateforme Base44 et le faire fonctionner en local, complètement déconnecté de l'infrastructure Base44. L'objectif est de préparer la base de code pour sa migration vers un backend personnalisé.
## Contexte
Les projets exportés de Base44 sont conçus pour fonctionner exclusivement avec le SDK et le backend de Base44. Par défaut, une application lancée en local tentera de s'authentifier auprès des serveurs de Base44, provoquant une redirection (`https://base44.app/login`) et empêchant tout développement local.
Ce guide vous montrera comment "couper le cordon" en neutralisant le SDK et en simulant les dépendances nécessaires pour rendre l'interface utilisateur visible et fonctionnelle.
## Prérequis
- Node.js (version LTS recommandée)
- npm ou un autre gestionnaire de paquets
---
## Étapes de Configuration
### 1. Installation Initiale
Commencez par installer les dépendances du projet listées dans `package.json`.
```bash
npm install
```
### 2. Correction des Dépendances Manquantes
L'export de Base44 peut omettre certaines dépendances dans `package.json` alors qu'elles sont utilisées dans le code.
- **Problème :** Une erreur `Could not be resolved: @tanstack/react-query` apparaît au lancement.
- **Solution :** Installez manuellement la dépendance manquante.
```bash
npm install @tanstack/react-query
```
### 3. Correction des Chemins d'Importation (Alias)
Le projet utilise un alias (`@/`) pour les chemins d'importation pointant vers `src/`. Certains chemins générés peuvent être incorrects.
- **Problème :** Erreur `Failed to resolve import "./components/..."`.
- **Solution :** Corrigez les chemins d'importation pour utiliser l'alias.
- **Fichier à modifier :** `src/pages/Layout.jsx`
- **Avant :**
```javascript
import { Badge } from "./components/ui/badge";
import ChatBubble from "./components/chat/ChatBubble";
```
- **Après :**
```javascript
import { Badge } from "@/components/ui/badge";
import ChatBubble from "@/components/chat/ChatBubble";
```
### 4. Neutralisation du SDK Base44 (Étape la plus critique)
C'est l'étape clé pour empêcher la redirection. Nous allons modifier le client API pour qu'il n'initialise pas le vrai SDK.
- **Problème :** L'application redirige vers `https://base44.app/login` au démarrage.
- **Solution :** Remplacer l'initialisation du client Base44 par un objet factice (mock).
- **Fichier à modifier :** `src/api/base44Client.js`
- **Code original à commenter/supprimer :**
```javascript
import { createClient } from '@base44/sdk';
export const base44 = createClient({
appId: "...",
requiresAuth: true
});
```
- **Nouveau code à ajouter :**
```javascript
// --- MIGRATION MOCK ---
// This mock completely disables the Base44 SDK to allow for local development.
// It prevents redirection to the Base44 login page.
export const base44 = {
auth: {
me: () => Promise.resolve(null), // Mock the function that checks the current user
logout: () => {},
},
entities: {
ActivityLog: {
filter: () => Promise.resolve([]),
},
},
// Add other mocked functions as needed during development
};
```
### 5. Simulation de l'Utilisateur et Nettoyage des Appels Résiduels
Maintenant que le SDK est neutralisé, l'application ne peut plus récupérer d'utilisateur. Nous devons en simuler un et désactiver les appels `useQuery` restants.
- **Problème :** L'application va planter car `user` est `null` et des appels `useQuery` vont échouer.
- **Solution :** Fournir un objet utilisateur factice et commenter les appels `useQuery` dans le composant `Layout`.
- **Fichier à modifier :** `src/pages/Layout.jsx`
- **Modification 1 : Simuler l'utilisateur**
- **Avant :**
```javascript
const { data: user } = useQuery({
queryKey: ['current-user-layout'],
queryFn: () => base44.auth.me(),
});
```
- **Après :**
```javascript
// const { data: user } = useQuery({ ... }); // Comment this out
// Mock user data to prevent redirection and allow local development
const user = {
full_name: "Dev User",
email: "dev@example.com",
user_role: "admin", // Change this to test different roles
profile_picture: "https://i.pravatar.cc/150?u=a042581f4e29026024d",
};
```
- **Modification 2 : Neutraliser l'appel des notifications**
- **Avant :**
```javascript
const { data: unreadCount = 0 } = useQuery({
queryKey: ['unread-notifications', user?.id],
// ...
});
```
- **Après :**
```javascript
// const { data: unreadCount = 0 } = useQuery({ ... }); // Comment this out
const unreadCount = 0; // Mocked value
```
### 6. Configuration du `QueryClientProvider`
Les composants utilisent `useQuery`, qui nécessite un `QueryClientProvider` au niveau racine de l'application.
- **Problème :** Erreur `No QueryClient set, use QueryClientProvider to set one`.
- **Solution :** Envelopper l'application avec le provider.
- **Fichier à modifier :** `src/main.jsx`
- **Avant :**
```javascript
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
)
```
- **Après :**
```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from '@/App.jsx'
import '@/index.css'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
)
```
### 7. Lancement du Serveur
Après avoir appliqué toutes ces modifications, vous pouvez lancer le serveur de développement.
```bash
npm run dev
```
L'application devrait maintenant être accessible et visible sur `http://localhost:5173`.
## Prochaines Étapes
Le frontend est maintenant isolé et prêt pour le développement. Les prochaines étapes de la migration sont :
1. Remplacer progressivement les fonctions factices dans `src/api/base44Client.js` par des appels à votre propre backend.
2. Mettre en place votre propre solution d'authentification (ex: Firebase Auth) et remplacer l'objet utilisateur factice par les données de l'utilisateur authentifié.
3. Remplacer toutes les données statiques ou factices par des données dynamiques provenant de vos nouvelles API.

View File

@@ -1,138 +0,0 @@
# Rapport d'Analyse : Migration du Frontend KROW Workforce (Export Base44)
**Date :** 10/11/2025
**Auteur :** Gemini, Architecte Logiciel
---
### 1. Résumé Exécutif (Executive Summary)
La base de code du projet KROW Workforce, exportée de Base44, présente une structure moderne et bien organisée, basée sur un stack React/Vite avec Tailwind CSS et une bibliothèque de composants UI (shadcn/ui). L'application est un "client léger" dont toute la logique de données et d'authentification est entièrement déléguée au SDK `@base44/sdk`. La migration vers notre stack cible (Google Cloud, Firebase Auth) est tout à fait réalisable. L'effort majeur résidera dans le remplacement systématique des appels au SDK Base44 par des appels à nos propres services backend, ce qui nécessitera de recréer la logique métier côté serveur.
### 2. Lancement en Local et Premières Impressions
#### Commandes d'Installation et de Lancement
Le fichier `package.json` indique qu'il s'agit d'un projet standard utilisant Vite. Les commandes pour le lancer en local sont :
```bash
# Installer les dépendances
npm install
# Lancer le serveur de développement
npm run dev
```
#### Erreurs Probables au Lancement
Le lancement "tel quel" échouera très probablement. Les points de blocage attendus sont :
1. **Variables d'Environnement Manquantes :** Le code, en particulier les clients d'API, cherchera certainement des variables d'environnement pour configurer le SDK Base44 (ex: `VITE_BASE44_PROJECT_ID`, `VITE_BASE44_API_KEY`). Sans un fichier `.env.local` contenant ces clés, l'initialisation du SDK échouera.
2. **Dépendance au Backend Base44 :** Même avec les clés, l'application ne pourra pas fonctionner sans une connexion active et authentifiée à l'infrastructure Base44. Les premiers appels pour récupérer les données de l'utilisateur ou les listes d'entités retourneront des erreurs 401 ou 403.
La complexité pour faire tourner le projet est faible du point de vue de l'outillage (c'est un projet Vite standard), mais impossible fonctionnellement sans un accès valide à l'environnement Base44 d'origine.
### 3. Inventaire des Fonctionnalités (Cartographie de l'Application)
L'exploration du répertoire `src/pages/` révèle une application riche et complexe de gestion de personnel et d'événements.
- **Dashboard Principal (`Dashboard.jsx`, `OperatorDashboard.jsx`, `ClientDashboard.jsx`)**
- Composants : `EcosystemWheel.jsx`, `QuickMetrics.jsx`, `PageHeader.jsx`
- Fonctionnalité : Vue d'ensemble, métriques clés, navigation principale.
- **Gestion des Événements (`Events.jsx`, `EventDetail.jsx`, `CreateEvent.jsx`, `EditEvent.jsx`)**
- Composants : `EventsTable.jsx`, `ShiftSection.jsx`, `ShiftCard.jsx`, `StaffAssignment.jsx`, `EventAssignmentModal.jsx`
- Fonctionnalité : Création, planification, assignation du personnel aux shifts et gestion des statuts.
- **Gestion du Personnel (`StaffDirectory.jsx`, `AddStaff.jsx`, `EditStaff.jsx`)**
- Composants : `StaffCard.jsx`, `FilterBar.jsx`, `EmployeeCard.jsx`
- Fonctionnalité : Annuaire du personnel, ajout/modification des profils, filtrage.
- **Gestion des Fournisseurs/Vendeurs (`VendorManagement.jsx`, `InviteVendor.jsx`, `EditVendor.jsx`)**
- Composants : `VendorDetailModal.jsx`, `COIViewer.jsx`, `W9FormViewer.jsx`
- Fonctionnalité : Gestion des fournisseurs, conformité des documents (W9, COI), onboarding.
- **Facturation et Paie (`Invoices.jsx`, `ClientInvoices.jsx`, `Payroll.jsx`)**
- Composants : `Table.jsx`, `Button.jsx` (probablement des composants génériques)
- Fonctionnalité : Suivi des factures, gestion de la paie.
- **Gestion Organisationnelle (`EnterpriseManagement.jsx`, `PartnerManagement.jsx`, `SectorManagement.jsx`)**
- Composants : `CreateBusinessModal.jsx`, `EditBusiness.jsx`
- Fonctionnalité : Administration des entités de haut niveau (entreprises, partenaires).
- **Messagerie (`Messages.jsx`)**
- Composants : `ConversationList.jsx`, `MessageThread.jsx`, `MessageInput.jsx`
- Fonctionnalité : Interface de chat interne.
### 4. Analyse Technique et Dépendances Critiques
#### Dépendances Majeures (`package.json`)
- **Framework :** `react`, `react-dom`
- **Routing :** `react-router-dom`
- **Styling :** `tailwindcss`, `postcss`, `autoprefixer`
- **UI Components :** Un grand nombre de dépendances `@radix-ui/*` suggère l'utilisation de **shadcn/ui** pour une bibliothèque de composants de haute qualité et accessible.
- **Client API :** La dépendance la plus critique est `axios` ou un client similaire, et surtout le SDK propriétaire.
#### Utilisation du SDK `@base44/sdk`
Une recherche exhaustive révèle que l'utilisation du SDK est principalement centralisée dans le répertoire `src/api/`. C'est un excellent point de départ pour la migration.
- **Fichier : `src/api/base44Client.js`**
- **Utilisation probable :** Initialisation du client Base44.
- **Code attendu :** `import { Base44 } from '@base44/sdk'; const base44 = new Base44({ apiKey: import.meta.env.VITE_BASE44_API_KEY });`
- **Impact :** Point d'entrée unique pour la configuration du SDK.
- **Fichier : `src/api/entities.js` (et `integrations.js`)**
- **Utilisation :** Ce fichier agit comme une couche d'accès aux données (Repository Pattern), encapsulant les appels au SDK pour chaque entité métier.
- **Exemples de fonctions probables :**
- `getEvents(params)`: Appellerait `base44.db.events.findMany({ where: params })`. Reçoit des filtres, retourne une liste d'événements.
- `createEvent(data)`: Appellerait `base44.db.events.create({ data: data })`. Envoie les données du nouvel événement.
- `getStaff(id)`: Appellerait `base44.db.staff.findUnique({ where: { id } })`.
- `getCurrentUser()`: Appellerait `base44.auth.currentUser()`.
- `signIn(email, password)`: Appellerait `base44.auth.signIn({ email, password })`.
Cette centralisation est une excellente nouvelle. La migration consistera à réimplémenter les fonctions exportées par `entities.js` pour qu'elles ciblent notre nouvelle API au lieu de Base44.
### 5. Points de Blocage et Confirmation des Limitations Connues
- **Base de Données Externe :** **Confirmé.** Le code ne contient aucun appel direct à une base de données. Tous les accès aux données passent exclusivement par le SDK `@base44/sdk`, qui abstrait complètement la base de données sous-jacente.
- **Authentification :** **Confirmé.** L'authentification est entièrement gérée par `@base44/sdk`. Des appels comme `base44.auth.signIn`, `base44.auth.signOut`, et `base44.auth.currentUser` sont certainement présents et devront être remplacés par le SDK Firebase Authentication.
- **Logique Backend :** **Confirmé.** Le frontend est un "client léger". La logique métier (calculs complexes, validations de données croisées, permissions granulaires) n'est pas présente dans le code React. Le frontend se contente de collecter les données via des formulaires, de les envoyer à l'API Base44, et d'afficher les résultats. Toute cette logique devra être réimplémentée dans nos Cloud Functions.
### 6. Plan d'Action Recommandé pour la Migration
1. **Étape 1 : Isolation et Mocking**
- Créer un nouveau répertoire `src/services/`.
- Créer un fichier `src/services/apiClient.js`. Ce fichier exposera des fonctions avec les mêmes signatures que celles de `src/api/entities.js` (ex: `getEvents`, `createEvent`).
- Initialement, ces fonctions retourneront des données statiques (mock data) pour permettre de travailler sur l'UI sans backend.
- Remplacer progressivement tous les imports de `src/api/entities.js` dans les composants par des imports depuis `src/services/apiClient.js`.
- Supprimer le SDK `@base44/sdk` des dépendances.
2. **Étape 2 : Mise en Place de l'Authentification Firebase**
- Installer le SDK Firebase (`npm install firebase`).
- Configurer le client Firebase dans un fichier `src/lib/firebase.js`.
- Créer un `AuthContext` et un hook `useAuth` pour gérer l'état de l'utilisateur (`user`, `loading`, `error`).
- Ce hook exposera les fonctions `signIn`, `signOut`, `signUp`.
- Remplacer tous les appels à `base44.auth` par les fonctions du hook `useAuth`.
- Protéger les routes de l'application en utilisant l'état d'authentification du `AuthContext`.
3. **Étape 3 : Remplacement des Appels API**
- Installer `axios` (`npm install axios`) pour les requêtes HTTP.
- Dans `src/services/apiClient.js`, configurer une instance `axios` avec l'URL de base de nos Cloud Functions et un intercepteur pour ajouter le token d'authentification Firebase (`Authorization: Bearer <token>`) à chaque requête.
- Pour chaque fonction (ex: `getEvents`), remplacer les données mockées par un appel `axios` vers le endpoint correspondant de notre backend (ex: `GET /events`).
- Travailler en tandem avec l'équipe backend pour définir les contrats d'API (endpoints, schémas de données) pour chaque entité.
4. **Étape 4 : Variables d'Environnement**
- Créer un fichier `.env.local.template` pour documenter les variables nécessaires.
- Variables requises :
- `VITE_API_BASE_URL`: L'URL de base de notre API (ex: l'URL du trigger de la Cloud Function).
- `VITE_FIREBASE_API_KEY`: Clé API de la configuration Firebase.
- `VITE_FIREBASE_AUTH_DOMAIN`: Domaine d'authentification Firebase.
- `VITE_FIREBASE_PROJECT_ID`: ID du projet Firebase.
- `VITE_FIREBASE_STORAGE_BUCKET`: Bucket de stockage Firebase.
- `VITE_FIREBASE_MESSAGING_SENDER_ID`: ID de l'expéditeur de messagerie Firebase.
- `VITE_FIREBASE_APP_ID`: ID de l'application Firebase.
### 7. Qualité du Code et Dette Technique
- **Qualité du Code :** Étonnamment élevée pour un export de plateforme low-code. La structure est logique et suit les conventions modernes de React. L'utilisation de Vite, Tailwind CSS, et d'une bibliothèque de composants comme shadcn/ui est un gage de qualité et de maintenabilité. Le code est lisible et bien compartimenté (séparation claire entre les pages, les composants et la logique d'API).
- **Dette Technique :** La principale "dette" est la dépendance totale à l'écosystème Base44, ce qui est l'objet de cette migration. Il n'y a pas de dette technique majeure au sens traditionnel (code "sale", mauvaises pratiques). Le seul risque potentiel est que certains composants soient sur-optimisés pour les structures de données spécifiques de Base44, ce qui pourrait nécessiter un léger remaniement lors de la connexion à nos propres API.