diff --git a/docs/API_documentation.md b/docs/API_documentation.md index b9cb4e1d..02ff9b2a 100644 --- a/docs/API_documentation.md +++ b/docs/API_documentation.md @@ -1,254 +1,1732 @@ -Voici le contenu reformaté en Markdown pour une meilleure lisibilité : +# KROW Workforce Platform - API Documentation -# KROW Workforce Control Tower - Documentation de l'API +**Version:** 2.0 +**Last Updated:** 2025-11-11 +**Project:** KROW Workforce Control Tower -**Version :** 1.0.0 -**Dernière mise à jour :** Décembre 2024 -**URL de base :** `base44.entities` et `base44.integrations` +## Table of Contents +1. [Overview](#overview) +2. [Authentication](#authentication) +3. [Entity Schemas](#entity-schemas) +4. [SDK Operations](#sdk-operations) +5. [Core Integrations](#core-integrations) +6. [Data Models Reference](#data-models-reference) +7. [Code Examples](#code-examples) +8. [Best Practices](#best-practices) +9. [Security Considerations](#security-considerations) +10. [Rate Limits & Quotas](#rate-limits--quotas) +11. [Changelog](#changelog) +12. [Support & Resources](#support--resources) --- -## Table des matières - -1. [Introduction](#introduction) -2. [Authentification](#authentication) -3. [API des Entités](#entities-api) -4. [API des Intégrations](#integrations-api) -5. [Meilleures Pratiques](#best-practices) -6. [Gestion des Erreurs](#error-handling) -7. [Exemples](#examples) - ---- - -## Introduction - -L'API KROW Workforce Control Tower fournit une plateforme complète pour la gestion des opérations de la main-d'œuvre, des événements, des fournisseurs, de la conformité, et plus encore. Construite sur la plateforme Base44, elle offre : - -* **Architecture multi-locataire** supportant les entreprises, les secteurs, les partenaires, les fournisseurs et la main-d'œuvre. -* Gestion des données en **temps réel** avec l'intégration de React Query. -* **Contrôle d'accès basé sur les rôles** (Admin, Achats, Opérateur, Secteur, Client, Fournisseur, Main-d'œuvre). -* Suivi de la **conformité** et gestion des certifications. -* Gestion des événements et des commandes avec des modèles récurrents. -* Optimisation des cartes de tarifs et de la tarification. - ---- - -## Authentification - -### Utilisateur Actuel +## Overview +KROW Workforce is a comprehensive workforce management platform built on Base44. This documentation provides complete API specifications for all entities, SDK methods, and integration endpoints. +### Base44 Client Import ```javascript -import { base44 } from '@/api/base44Client'; +import { base44 } from "@/api/base44Client"; +``` -// Obtenir l'utilisateur actuellement authentifié +--- + +## Authentication + +### User Authentication Methods +```javascript +// Get current authenticated user const user = await base44.auth.me(); -// Retourne : { id, email, full_name, role, user_role, company_name, ... } -// Vérifier si l'utilisateur est authentifié -const isAuthenticated = await base44.auth.isAuthenticated(); -// Retourne : boolean - -// Mettre à jour le profil de l'utilisateur actuel +// Update current user await base44.auth.updateMe({ full_name: "John Doe", - phone: "(555) 123-4567" - // Note : Impossible de remplacer les champs intégrés (id, email, role) + custom_field: "value" }); -// Déconnexion -base44.auth.logout(); // Recharge la page -base44.auth.logout('/login'); // Redirige vers une URL spécifique +// Logout +base44.auth.logout(redirectUrl?: string); -// Rediriger vers la page de connexion -base44.auth.redirectToLogin(); // Page actuelle comme nextUrl -base44.auth.redirectToLogin('/dashboard'); // nextUrl personnalisé +// Redirect to login +base44.auth.redirectToLogin(nextUrl?: string); + +// Check authentication status +const isAuthenticated = await base44.auth.isAuthenticated(); ``` -### Rôles des Utilisateurs - -* **admin** - Administrateur de la plateforme avec un accès complet. -* **procurement** - Gère les fournisseurs, les partenaires et la conformité. -* **operator** - Supervise plusieurs secteurs. -* **sector** - Gère une branche/localisation spécifique. -* **client** - Demande des services de main-d'œuvre. -* **vendor** - Fournit des services de main-d'œuvre. -* **workforce** - Membres individuels du personnel. +### User Object Structure +```json +{ + "id": "string", + "email": "string", + "full_name": "string", + "role": ""admin" | "user"", + "user_role": "string", // Custom role field + "created_date": "timestamp", + "updated_date": "timestamp", + // ... custom fields +} +``` --- -## API des Entités +## Entity Schemas -Toutes les entités suivent le même modèle CRUD avec des champs intégrés : +### 1. User Entity (Built-in) +Description: Core user entity with authentication and role management. -* `id` (string, généré automatiquement) -* `created_date` (timestamp ISO 8601) -* `updated_date` (timestamp ISO 8601) -* `created_by` (email du créateur) +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :--------------------------------------- | +| `id` | `string` | Unique user identifier | Auto-generated, unique | +| `email` | `string` | User email address | Required, unique, email format | +| `full_name`| `string` | User's full name | Required | +| `role` | `string` | Base role | Enum: "admin", "user" | +| `user_role`| `string` | Custom application role | Optional, custom values | +| `created_date`| `timestamp`| Account creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update timestamp | Auto-updated | -### Opérations Générales sur les Entités +JSON Schema: +```json +{ + "type": "object", + "properties": { + "email": {"type": "string", "format": "email"}, + "full_name": {"type": "string"}, + "role": {"type": "string", "enum": ["admin", "user"]}, + "user_role": {"type": "string"} + } +} +``` +Security Rules: +- Only admin users can list, update, or delete other users +- Regular users can only view and update their own user record +- These rules are automatically enforced + +### 2. Event Entity +Description: Core event/order management entity for workforce scheduling. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique event identifier | Auto-generated | +| `event_name`| `string` | Name of the event | Required | +| `is_recurring`| `boolean`| Whether event recurs | Default: false | +| `recurrence_type`| `string`| Type of recurrence | Enum: "single", "date_range", "scatter" | +| `recurrence_start_date`| `date`| Start date for recurring events| Optional | +| `recurrence_end_date`| `date`| End date for recurring events | Optional | +| `scatter_dates`| `array` | Specific dates for scatter recurring| Array of date strings | +| `business_id`| `string` | Associated business ID | Optional | +| `business_name`| `string` | Business name | Optional | +| `vendor_id`| `string` | Vendor ID if created by vendor| Optional | +| `vendor_name`| `string` | Vendor name | Optional | +| `hub` | `string` | Hub location | Optional | +| `contract_type`| `string`| Contract type | Enum: "W2", "1099", "Temp", "Contract" | +| `po_reference`| `string`| Purchase order reference| Optional | +| `status` | `string` | Event status | Enum: "Draft", "Active", "Pending", "Assigned", "Confirmed", "Completed", "Canceled" | +| `date` | `date` | Event date | Optional | +| `shifts` | `array` | Array of shift objects | Optional | +| `addons` | `object` | Additional services/features| Optional | +| `total` | `number` | Total cost | Optional | +| `client_name`| `string` | Client contact name | Optional | +| `client_email`| `string`| Client email | Optional | +| `client_phone`| `string`| Client phone | Optional | +| `notes` | `string` | Additional notes | Optional | +| `requested`| `number` | Total staff requested | Optional | +| `assigned_staff`| `array`| Array of assigned staff | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | +| `created_by`| `string` | Creator email | Auto-populated | + +Shifts Structure: +```json +{ + "shift_name": "string", + "shift_contact": "string", + "location_address": "string", + "roles": [ + { + "role": "string", + "department": "string", + "count": "number", + "start_time": "string", + "end_time": "string", + "hours": "number", + "uniform": "string", + "break_minutes": "number", + "cost_per_hour": "number", + "total_value": "number", + "vendor_name": "string", + "vendor_id": "string" + } + ] +} +``` + +### 3. Staff Entity +Description: Employee/workforce member management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique staff identifier | Auto-generated | +| `employee_name`| `string`| Full name | Required | +| `vendor_id`| `string` | Associated vendor ID | Optional | +| `vendor_name`| `string`| Vendor company name | Optional | +| `manager` | `string` | Manager's name | Optional | +| `contact_number`| `string`| Primary contact number | Optional | +| `phone` | `string` | Additional phone | Optional | +| `email` | `string` | Email address | Email format | +| `department`| `string` | Department | Enum: "Operations", "Sales", "HR", "Finance", "IT", "Marketing", "Customer Service", "Logistics" | +| `hub_location`| `string`| Hub/office location | Optional | +| `event_location`| `string`| Event location | Optional | +| `address` | `string` | Employee address | Optional | +| `city` | `string` | City | Optional | +| `position` | `string` | Primary job position/skill| Optional | +| `position_2`| `string` | Secondary job position/skill| Optional | +| `profile_type`| `string`| Skill profile level | Enum: "Skilled", "Beginner", "Cross-Trained" | +| `employment_type`| `string`| Employment type | Enum: "Full Time", "Part Time", "On call", "Weekends", "Specific Days", "Seasonal", "Medical Leave" | +| `english` | `string` | English proficiency | Enum: "Fluent", "Intermediate", "Basic", "None" | +| `english_required`| `boolean`| English required | Optional | +| `rating` | `number` | Performance rating | Min: 0, Max: 5 | +| `shift_coverage_percentage`| `number`| Shift coverage % | Min: 0, Max: 100 | +| `cancellation_count`| `number`| Number of cancellations | Min: 0 | +| `no_show_count`| `number`| Number of no-shows | Min: 0 | +| `total_shifts`| `number`| Total shifts assigned | Min: 0 | +| `reliability_score`| `number`| Reliability score | Min: 0, Max: 100 | +| `background_check_status`| `string`| Background check status | Enum: "pending", "cleared", "failed", "expired", "not_required" | +| `background_check_date`| `date`| Last background check date| Optional | +| `certifications`| `array`| List of certifications | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | +| `created_by`| `string` | Creator email | Auto-populated | + +### 4. Vendor Entity +Description: Vendor/supplier management and onboarding. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique vendor identifier| Auto-generated | +| `vendor_number`| `string`| Vendor Number (VN-####) | Required, Pattern: `^VN-[0-9]{4}$` | +| `legal_name`| `string` | Legal business name | Required | +| `doing_business_as`| `string`| DBA/Trade name | Optional | +| `region` | `string` | Geographic region | Enum: "National", "Bay Area", "Southern California", "Northern California", "West", "East", "Midwest", "South" | +| `state` | `string` | Primary state | Optional | +| `city` | `string` | Primary city | Optional | +| `service_specialty`| `string`| Service specialty | Optional | +| `workforce_count`| `number`| Total workforce count | Optional | +| `platform_type`| `string`| Technology integration level| Enum: "Full Platform", "Building platform (KROW)", "Partial Tech", "Traditional" | +| `tax_id` | `string` | Federal Tax ID/EIN | Optional | +| `business_type`| `string`| Business entity type | Enum: "Corporation", "LLC", "Partnership", "Sole Proprietorship" | +| `primary_contact_name`| `string`| Primary contact | Optional | +| `primary_contact_email`| `string`| Primary email | Required, Email format | +| `primary_contact_phone`| `string`| Primary phone | Optional | +| `billing_address`| `string`| Billing address | Optional | +| `service_address`| `string`| Service/office address | Optional | +| `coverage_regions`| `array`| Geographic coverage | Array of strings | +| `eligible_roles`| `array`| Roles/positions provided| Array of strings | +| `insurance_certificate`| `string`| URL to insurance cert | Optional | +| `insurance_expiry`| `date`| Insurance expiration | Optional | +| `w9_document`| `string` | URL to W9 form | Optional | +| `coi_document`| `string` | URL to COI | Optional | +| `approval_status`| `string`| Vendor approval status | Enum: "pending", "approved", "suspended", "terminated" | +| `approved_date`| `date` | Approval date | Optional | +| `approved_by`| `string` | Approver | Optional | +| `is_active`| `boolean` | Active status | Default: true | +| `notes` | `string` | Internal notes | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 5. VendorRate Entity +Description: Vendor pricing and rate management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique rate identifier | Auto-generated | +| `vendor_id`| `string` | Vendor ID | Optional | +| `vendor_name`| `string`| Vendor name | Required | +| `category` | `string` | Service category | Enum: "Kitchen and Culinary", "Concessions", "Facilities", "Bartending", "Security", "Event Staff", "Management", "Technical", "Other" | +| `role_name`| `string` | Role/position name | Required | +| `employee_wage`| `number`| Employee base wage/hour | Required, Min: 0 | +| `markup_percentage`| `number`| Markup percentage | Min: 0, Max: 100 | +| `vendor_fee_percentage`| `number`| Vendor fee percentage | Min: 0, Max: 100 | +| `client_rate`| `number` | Final rate to client | Required, Min: 0 | +| `is_active`| `boolean` | Active status | Default: true | +| `minimum_wage_compliance`| `boolean`| Meets minimum wage | Optional | +| `pricing_status`| `string`| Pricing analysis | Enum: "optimal", "underpriced", "overpriced", "competitive" | +| `market_average`| `number`| Market average rate | Optional | +| `notes` | `string` | Additional notes | Optional | +| `available_to_clients`| `array`| Client IDs with access | Array of strings | +| `client_visibility`| `string`| Visibility setting | Enum: "all", "specific", "none" | +| `competitive_status`| `boolean`| Competitive pricing | Default: false | +| `csta_compliant`| `boolean`| CA Staffing Agency compliant| Default: false | +| `compliance_verified`| `boolean`| Compliance verified | Default: false | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 6. Invoice Entity +Description: Invoice and billing management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique invoice identifier| Auto-generated | +| `invoice_number`| `string`| Unique invoice number | Required | +| `manager_name`| `string`| Manager/client name | Optional | +| `hub` | `string` | Hub location | Optional | +| `cost_center`| `string` | Cost center/department | Optional | +| `event_id` | `string` | Related event ID | Optional | +| `event_name`| `string` | Event name | Optional | +| `business_name`| `string`| Client/Business name | Required | +| `vendor_name`| `string`| Vendor name | Optional | +| `amount` | `number` | Invoice amount | Required, Min: 0 | +| `item_count`| `number` | Number of items | Min: 0 | +| `status` | `string` | Invoice status | Enum: "Open", "Disputed", "Resolved", "Verified", "Overdue", "Reconciled", "Paid", "Confirmed", "Pending" | +| `issue_date`| `date` | Invoice issue date | Required | +| `due_date` | `date` | Payment due date | Required | +| `paid_date`| `date` | Payment received date | Optional | +| `payment_method`| `string`| Payment method | Enum: "Credit Card", "ACH", "Wire Transfer", "Check", "Cash" | +| `notes` | `string` | Additional notes | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 7. Business Entity +Description: Client business/company management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique business identifier| Auto-generated | +| `business_name`| `string`| Business/client company name| Required | +| `company_logo`| `string`| URL to company logo | Optional | +| `contact_name`| `string`| Primary contact person | Required | +| `email` | `string` | Business email | Email format | +| `phone` | `string` | Business phone | Optional | +| `hub_building`| `string`| Hub/building name | Optional | +| `address` | `string` | Street address | Optional | +| `city` | `string` | City | Optional | +| `area` | `string` | Geographic area | Enum: "Bay Area", "Southern California", "Northern California", "Central Valley", "Other" | +| `sector` | `string` | Sector/industry | Enum: "Bon Appétit", "Eurest", "Aramark", "Epicurean Group", "Chartwells", "Other" | +| `rate_group`| `string` | Pricing tier | Required, Enum: "Standard", "Premium", "Enterprise", "Custom" | +| `status` | `string` | Business status | Enum: "Active", "Inactive", "Pending" | +| `notes` | `string` | Additional notes | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 8. Certification Entity +Description: Employee certification and compliance tracking. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique certification ID | Auto-generated | +| `employee_id`| `string`| Staff member ID | Optional | +| `employee_name`| `string`| Staff member name | Required | +| `vendor_id`| `string` | Vendor ID | Optional | +| `vendor_name`| `string`| Vendor name | Optional | +| `certification_name`| `string`| Certification name | Required | +| `certification_type`| `string`| Type of certification | Enum: "Legal", "Operational", "Safety", "Training", "License", "Other" | +| `status` | `string` | Current status | Enum: "current", "expiring_soon", "expired", "pending_validation" | +| `issue_date`| `date` | Issue date | Optional | +| `expiry_date`| `date` | Expiration date | Required | +| `issuer` | `string` | Issuing authority | Optional | +| `certificate_number`| `string`| Certificate ID | Optional | +| `document_url`| `string`| Uploaded certificate URL| Optional | +| `validation_status`| `string`| Validation status | Enum: "approved", "pending_expert_review", "rejected", "ai_verified", "ai_flagged", "manual_review_needed" | +| `ai_validation_result`| `object`| AI validation results | Optional | +| `validated_by`| `string`| Validator | Optional | +| `validated_date`| `date`| Validation date | Optional | +| `is_required_for_role`| `boolean`| Required for role | Default: false | +| `days_until_expiry`| `number`| Auto-calculated days | Optional | +| `alert_sent`| `boolean` | Expiry alert sent | Default: false | +| `notes` | `string` | Additional notes | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 9. Team Entity +Description: Team and organization management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique team identifier | Auto-generated | +| `team_name`| `string` | Name of the team | Required | +| `owner_id` | `string` | Team owner user ID | Required | +| `owner_name`| `string` | Team owner name | Required | +| `owner_role`| `string` | Role of team owner | Required, Enum: "admin", "procurement", "operator", "sector", "client", "vendor", "workforce" | +| `company_logo`| `string`| URL to company logo | Optional | +| `full_name`| `string` | Primary contact name | Optional | +| `email` | `string` | Contact email | Email format | +| `phone` | `string` | Contact phone | Optional | +| `address` | `string` | Company address | Optional | +| `city` | `string` | City | Optional | +| `zip_code` | `string` | ZIP code | Optional | +| `vendor_id`| `string` | Vendor ID if applicable | Optional | +| `departments`| `array` | Available departments | Array of strings | +| `total_members`| `number`| Total team members | Default: 0 | +| `active_members`| `number`| Active members | Default: 0 | +| `total_hubs`| `number` | Total hubs | Default: 0 | +| `favorite_staff_count`| `number`| Favorite staff count | Default: 0 | +| `blocked_staff_count`| `number`| Blocked staff count | Default: 0 | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 10. Conversation Entity +Description: Messaging and communication management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique conversation ID | Auto-generated | +| `participants`| `array` | Array of participant objects| Required | +| `conversation_type`| `string`| Type of conversation | Required, Enum: "client-vendor", "staff-client", "staff-admin", "vendor-admin", "client-admin", "group-staff", "group-event-staff" | +| `is_group` | `boolean` | Is group conversation | Default: false | +| `group_name`| `string` | Group name | Optional | +| `related_to`| `string` | Related entity ID | Optional | +| `related_type`| `string`| Related entity type | Enum: "event", "staff", "business", "general" | +| `subject` | `string` | Conversation subject | Optional | +| `last_message`| `string`| Preview of last message | Optional | +| `last_message_at`| `timestamp`| Last message timestamp | Optional | +| `unread_count`| `number`| Unread message count | Default: 0 | +| `status` | `string` | Conversation status | Enum: "active", "archived", "closed" | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 11. Message Entity +Description: Individual messages within conversations. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique message identifier| Auto-generated | +| `conversation_id`| `string`| Conversation ID | Required | +| `sender_id`| `string` | Sender ID | Optional | +| `sender_name`| `string`| Sender name | Required | +| `sender_role`| `string`| Sender role | Enum: "client", "vendor", "staff", "admin" | +| `content` | `string` | Message content | Required | +| `read_by` | `array` | User IDs who read | Array of strings | +| `attachments`| `array` | Attached files | Array of objects | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 12. ActivityLog Entity +Description: Activity and notification tracking. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique activity identifier| Auto-generated | +| `title` | `string` | Notification title | Required | +| `description`| `string`| Detailed description | Required | +| `activity_type`| `string`| Type of activity | Required, Enum: "event_created", "event_updated", "event_rescheduled", "event_canceled", "staff_assigned", "staff_removed", "invoice_paid", "invoice_created", "message_received", "order_created", "order_updated" | +| `related_entity_type`| `string`| Related entity type | Enum: "event", "staff", "invoice", "message", "order", "user" | +| `related_entity_id`| `string`| Related entity ID | Optional | +| `action_link`| `string`| Link to related item | Optional | +| `action_label`| `string`| Action button label | Optional | +| `user_id` | `string` | User this is for | Required | +| `is_read` | `boolean` | Read status | Default: false | +| `icon_type`| `string` | Icon to display | Enum: "calendar", "user", "invoice", "message", "alert", "check" | +| `icon_color`| `string` | Icon color theme | Enum: "blue", "red", "green", "yellow", "purple" | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 13. Enterprise Entity +Description: Enterprise organization management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique enterprise ID | Auto-generated | +| `enterprise_number`| `string`| Enterprise Number (EN-####)| Required, Pattern: `^EN-[0-9]{4}$` | +| `enterprise_name`| `string`| Enterprise name | Required | +| `enterprise_code`| `string`| Short code identifier | Required | +| `brand_family`| `array` | Brands under enterprise | Array of strings | +| `headquarters_address`| `string`| HQ address | Optional | +| `global_policies`| `object`| Global policies | Optional | +| `sector_registry`| `array`| Sector IDs | Array of strings | +| `rate_guardrails`| `object`| Rate limits | Optional | +| `primary_contact_name`| `string`| Contact name | Optional | +| `primary_contact_email`| `string`| Contact email | Email format | +| `is_active`| `boolean` | Active status | Default: true | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 14. Sector Entity +Description: Sector/branch management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique sector identifier| Auto-generated | +| `sector_number`| `string`| Sector Number (SN-####) | Required, Pattern: `^SN-[0-9]{4}$` | +| `sector_name`| `string` | Sector/brand name | Required | +| `sector_code`| `string` | Short code identifier | Required | +| `parent_enterprise_id`| `string`| Parent enterprise ID | Optional | +| `parent_enterprise_name`| `string`| Parent enterprise name | Optional | +| `sector_type`| `string` | Sector business type | Enum: "Food Service", "Facilities", "Healthcare", "Education", "Corporate", "Sports & Entertainment" | +| `client_portfolio`| `array`| Partner/client IDs | Array of strings | +| `sector_policies`| `object`| Sector-specific policies| Optional | +| `approved_vendors`| `array`| Approved vendor IDs | Array of strings | +| `is_active`| `boolean` | Active status | Default: true | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 15. Partner Entity +Description: Partner/client organization management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique partner identifier| Auto-generated | +| `partner_name`| `string`| Partner/client name | Required | +| `partner_number`| `string`| Partner Number (PN-####)| Required, Pattern: `^PN-[0-9]{4}$` | +| `partner_type`| `string`| Partner type | Enum: "Corporate", "Education", "Healthcare", "Sports & Entertainment", "Government" | +| `sector_id`| `string` | Sector ID | Optional | +| `sector_name`| `string`| Sector name | Optional | +| `primary_contact_name`| `string`| Primary contact | Optional | +| `primary_contact_email`| `string`| Primary email | Email format | +| `primary_contact_phone`| `string`| Primary phone | Optional | +| `billing_address`| `string`| Billing address | Optional | +| `sites` | `array` | Partner sites/locations | Array of objects | +| `allowed_vendors`| `array`| Allowed vendor IDs | Array of strings | +| `rate_exceptions`| `array`| Rate exceptions | Array of objects | +| `cost_centers`| `array` | Cost centers/PO numbers | Array of strings | +| `payment_terms`| `string`| Payment terms | Default: "Net 30" | +| `is_active`| `boolean` | Active status | Default: true | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 16. Order Entity +Description: Order management system. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique order identifier | Auto-generated | +| `order_number`| `string`| Order Number (ORD-####) | Required, Pattern: `^ORD-[0-9]{4,6}$` | +| `partner_id`| `string` | Partner/Client ID | Required | +| `partner_name`| `string`| Partner/Client name | Optional | +| `site_id` | `string` | Site/location ID | Optional | +| `site_name`| `string` | Site/location name | Optional | +| `site_address`| `string`| Event/site address | Optional | +| `sector_id`| `string` | Sector ID | Optional | +| `enterprise_id`| `string`| Enterprise ID | Optional | +| `order_type`| `string` | Type of order | Enum: "Standard", "Last Minute", "Emergency", "Recurring" | +| `cost_center`| `string`| Cost center | Optional | +| `po_number`| `string` | Purchase order number | Optional | +| `roles_requested`| `array`| Roles and headcount | Array of objects | +| `tags` | `array` | Order tags/labels | Array of strings | +| `point_of_contact`| `object`| On-site contact | Optional | +| `sla_targets`| `object`| SLA targets | Optional | +| `order_status`| `string`| Order status | Enum: "Draft", "Submitted", "Confirmed", "In Progress", "Completed", "Cancelled" | +| `submitted_date`| `timestamp`| Submission date | Optional | +| `confirmed_date`| `timestamp`| Confirmation date | Optional | +| `special_instructions`| `string`| Special instructions | Optional | +| `total_estimated_cost`| `number`| Estimated total cost | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +### 17. Shift Entity +Description: Shift scheduling and management. + +| Field Name | Type | Description | Validation | +| :--------- | :-------- | :---------------------- | :---------------------------------------------------------------------- | +| `id` | `string` | Unique shift identifier | Auto-generated | +| `event_id` | `string` | Associated event ID | Optional | +| `shift_name`| `string` | Name of the shift | Required | +| `manager_id`| `string` | Manager staff ID | Optional | +| `manager_name`| `string`| Manager name | Optional | +| `location` | `string` | Shift location | Optional | +| `start_date`| `timestamp`| Shift start date/time | Required | +| `end_date` | `timestamp`| Shift end date/time | Optional | +| `unpaid_break`| `number`| Unpaid break in minutes | Optional | +| `count` | `number` | Number of staff needed | Optional | +| `assigned` | `number` | Number of staff assigned| Optional | +| `uniform_type`| `string`| Required uniform type | Optional | +| `price` | `number` | Price per staff member | Optional | +| `amount` | `number` | Total amount for shift | Optional | +| `assigned_staff`| `array`| List of assigned staff | Array of objects | +| `role` | `string` | Role for this shift | Optional | +| `department`| `string` | Department | Optional | +| `created_date`| `timestamp`| Creation date | Auto-generated | +| `updated_date`| `timestamp`| Last update | Auto-updated | + +--- + +## SDK Operations + +### Standard Entity Operations +All entities support the following base operations: + +#### List All Records ```javascript -// Lister tous les enregistrements +// List all records (default limit: 50) const records = await base44.entities.EntityName.list(); -// Lister avec tri (préfixer avec - pour un tri descendant) -const sorted = await base44.entities.EntityName.list('-created_date', 50); +// List with sorting (descending by created_date) +const records = await base44.entities.EntityName.list('-created_date'); -// Filtrer les enregistrements -const filtered = await base44.entities.EntityName.filter({ - status: 'Active', - created_by: user.email -}, '-updated_date', 10); - -// Créer un enregistrement -const newRecord = await base44.entities.EntityName.create({ - field1: "value1", - field2: "value2" -}); - -// Création en masse -const records = await base44.entities.EntityName.bulkCreate([ - { field1: "value1" }, - { field1: "value2" } -]); - -// Mettre à jour un enregistrement -await base44.entities.EntityName.update(recordId, { - field1: "updated_value" -}); - -// Supprimer un enregistrement -await base44.entities.EntityName.delete(recordId); - -// Obtenir le schéma de l'entité -const schema = await base44.entities.EntityName.schema(); -// Retourne le schéma JSON sans les champs intégrés +// List with sorting and limit +const records = await base44.entities.EntityName.list('-created_date', 20); ``` -### Référence des Entités +#### Filter Records +```javascript +// Filter by single field +const records = await base44.entities.EntityName.filter({ + status: 'Active' +}); -#### 1. Event (Gestion des Commandes) -**Objectif :** Gérer les commandes de main-d'œuvre avec prise en charge des commandes ponctuelles, récurrentes, rapides et permanentes. +// Filter with multiple conditions +const records = await base44.entities.EntityName.filter({ + status: 'Active', + created_by: user.email +}); -**Champs Clés :** -* `event_name` (string, optionnel) -* `order_type` (enum: `rapid`, `one_time`, `recurring`, `permanent`) -* `business_id` / `business_name` (référence client) -* `vendor_id` / `vendor_name` (référence fournisseur) -* `status` (enum: `Draft`, `Active`, `Pending`, `Assigned`, `Confirmed`, `Completed`, `Canceled`) -* `shifts` (tableau d'objets de quarts de travail avec des rôles) +// Filter with sorting and limit +const records = await base44.entities.EntityName.filter( + { status: 'Active' }, + '-created_date', + 10 +); -#### 2. Staff (Gestion de la Main-d'œuvre) -**Objectif :** Gérer les membres individuels du personnel avec suivi des performances et de la conformité. +// Filter with operators +const records = await base44.entities.EntityName.filter({ + rating: { $gte: 4.5 }, + total: { $lte: 1000 } +}); +``` -**Champs Clés :** -* `employee_name` (string, requis) -* `vendor_id` / `vendor_name` (fournisseur propriétaire) -* `rating` (nombre, 0-5 étoiles) -* `shift_coverage_percentage` (nombre, 0-100) -* `background_check_status` (enum: `pending`, `cleared`, `failed`, `expired`) +#### Create Record +```javascript +// Create single record +const newRecord = await base44.entities.EntityName.create({ + field1: 'value1', + field2: 'value2' +}); -#### 3. Vendor -**Objectif :** Gérer les partenaires fournisseurs de services de main-d'œuvre. +// Returns created record with id +``` -**Champs Clés :** -* `vendor_number` (string, format: `VN-####`) -* `legal_name` (string, requis) -* `approval_status` (enum: `pending`, `approved`, `suspended`, `terminated`) -* `is_active` (boolean) +#### Bulk Create Records +```javascript +// Create multiple records +const newRecords = await base44.entities.EntityName.bulkCreate([ + { field1: 'value1' }, + { field1: 'value2' }, + { field1: 'value3' } +]); -#### 4. VendorRate -**Objectif :** Définir la tarification des services des fournisseurs avec suivi de la conformité. +// Returns array of created records +``` -**Champs Clés :** -* `vendor_id` / `vendor_name` (référence fournisseur) -* `role_name` (string, nom du poste) -* `employee_wage` (nombre) -* `client_rate` (nombre, taux horaire final) -* `pricing_status` (enum: `optimal`, `underpriced`, `overpriced`, `competitive`) +#### Update Record +```javascript +// Update by ID +const updatedRecord = await base44.entities.EntityName.update(recordId, { + field1: 'new value' +}); -... et ainsi de suite pour les autres entités (`Business`, `Certification`, `Enterprise`, `Sector`, `Partner`, `Order`, `Invoice`, `Team`, `ActivityLog`). +// Returns updated record +``` + +#### Delete Record +```javascript +// Delete by ID +await base44.entities.EntityName.delete(recordId); +``` + +#### Get Entity Schema +```javascript +// Get JSON schema (without built-in fields) +const schema = await base44.entities.EntityName.schema(); + +// Useful for dynamic form generation +``` + +### Entity-Specific Examples + +#### Event Operations +```javascript +// List recent events +const events = await base44.entities.Event.list('-date', 50); + +// Filter vendor's events +const myEvents = await base44.entities.Event.filter({ + vendor_id: user.id, + status: 'Active' +}, '-date', 20); + +// Create new event +const newEvent = await base44.entities.Event.create({ + event_name: 'Corporate Luncheon', + business_name: 'Acme Corp', + date: '2025-12-01', + status: 'Draft', + requested: 15 +}); + +// Update event status +await base44.entities.Event.update(eventId, { + status: 'Confirmed' +}); +``` + +#### Staff Operations +```javascript +// List all active staff +const staff = await base44.entities.Staff.list('-created_date'); + +// Filter by vendor +const vendorStaff = await base44.entities.Staff.filter({ + vendor_id: vendorId +}); + +// Filter by rating +const topStaff = await base44.entities.Staff.filter({ + rating: { $gte: 4.5 } +}, '-rating', 10); + +// Create staff member +const newStaff = await base44.entities.Staff.create({ + employee_name: 'John Doe', + vendor_name: 'ABC Staffing', + position: 'Server', + employment_type: 'Part Time' +}); + +// Update staff rating +await base44.entities.Staff.update(staffId, { + rating: 4.8, + reliability_score: 95 +}); +``` + +#### Invoice Operations +```javascript +// List unpaid invoices +const unpaid = await base44.entities.Invoice.filter({ + status: 'Open' +}, '-due_date'); + +// Get client's invoices +const clientInvoices = await base44.entities.Invoice.filter({ + business_name: clientName +}); + +// Create invoice +const invoice = await base44.entities.Invoice.create({ + invoice_number: 'INV-2025-001', + business_name: 'Client Corp', + amount: 5000, + status: 'Open', + issue_date: '2025-01-01', + due_date: '2025-01-31' +}); + +// Mark as paid +await base44.entities.Invoice.update(invoiceId, { + status: 'Paid', + paid_date: new Date().toISOString() +}); +``` + +#### Conversation & Message Operations +```javascript +// List active conversations +const conversations = await base44.entities.Conversation.filter({ + status: 'active', + participants: { $contains: userId } +}, '-last_message_at'); + +// Create conversation +const conversation = await base44.entities.Conversation.create({ + participants: [ + { id: user1Id, name: user1Name, role: 'client' }, + { id: user2Id, name: user2Name, role: 'vendor' } + ], + conversation_type: 'client-vendor', + subject: 'Event #123 Discussion', + status: 'active' +}); + +// Send message +const message = await base44.entities.Message.create({ + conversation_id: conversationId, + sender_id: userId, + sender_name: userName, + sender_role: 'client', + content: 'Hello, can we discuss the event details?' +}); + +// Mark as read +await base44.entities.Message.update(messageId, { + read_by: [...existingReadBy, userId] +}); +``` --- -## API des Intégrations +## Core Integrations -### Intégrations Principales -Toutes les intégrations sont accessibles via `base44.integrations.Core.*` : +### Integration: InvokeLLM +Description: Generate responses from an LLM with optional web context or file attachments. -1. **InvokeLLM** : Générer des réponses IA avec un contexte web optionnel et une sortie JSON. -2. **SendEmail** : Envoyer des e-mails aux utilisateurs. -3. **UploadFile** : Télécharger des fichiers sur un stockage public. -4. **GenerateImage** : Génération d'images par IA. -5. **ExtractDataFromUploadedFile** : Extraire des données structurées de documents. -6. **Gestion de Fichiers Privés** : Pour un stockage de fichiers sécurisé. +| Parameter | Type | Required | Description | +| :------------------------ | :-------- | :------- | :----------------------------------------------------- | +| `prompt` | `string` | Yes | The prompt to send to the LLM | +| `add_context_from_internet`| `boolean` | No | Fetch context from Google Search, Maps, News (default: false) | +| `response_json_schema` | `object` | No | JSON schema for structured output | +| `file_urls` | `string[]`| No | Array of file URLs for additional context | + +Returns: +- If `response_json_schema` specified: `object` (parsed JSON) +- Otherwise: `string` + +Examples: +```javascript +// Simple text response +const response = await base44.integrations.Core.InvokeLLM({ + prompt: "Summarize the top 3 benefits of workforce automation" +}); + +// Structured JSON response +const data = await base44.integrations.Core.InvokeLLM({ + prompt: "Extract key information about Apple Inc.", + add_context_from_internet: true, + response_json_schema: { + type: "object", + properties: { + stock_price: { type: "number" }, + ceo: { type: "string" }, + headquarters: { type: "string" }, + recent_news: { + type: "array", + items: { type: "string" } + } + } + } +}); + +// With file context +const analysis = await base44.integrations.Core.InvokeLLM({ + prompt: "Analyze this invoice and extract line items", + file_urls: [invoiceFileUrl], + response_json_schema: { + type: "object", + properties: { + line_items: { + type: "array", + items: { + type: "object", + properties: { + description: { type: "string" }, + quantity: { type: "number" }, + rate: { type: "number" }, + amount: { type: "number" } + } + } + }, + total: { type: "number" } + } + } +}); +``` + +### Integration: SendEmail +Description: Send an email to a user. + +| Parameter | Type | Required | Description | +| :-------- | :-------- | :------- | :----------------------------------------------------- | +| `to` | `string` | Yes | Recipient email address | +| `subject` | `string` | Yes | Email subject line | +| `body` | `string` | Yes | Email body (supports HTML) | +| `from_name`| `string` | No | Sender name (defaults to app name) | + +Returns: `void` + +Example: +```javascript +await base44.integrations.Core.SendEmail({ + to: 'client@example.com', + subject: 'Your Event Has Been Confirmed', + body: ` +

Event Confirmation

+

Hello ${clientName},

+

Your event "${eventName}" has been confirmed for ${eventDate}.

+

Staff assigned: ${staffCount}

+

Thank you for using KROW Workforce!

+ `, + from_name: 'KROW Workforce Team' +}); +``` + +### Integration: UploadFile +Description: Upload a file to public storage. + +| Parameter | Type | Required | Description | +| :-------- | :----- | :------- | :---------------------- | +| `file` | `File` | Yes | File object to upload | + +Returns: +```json +{ + "file_url": "string" // Public URL to the uploaded file +} +``` + +Example: +```javascript +// From file input +const fileInput = document.querySelector('input[type="file"]'); +const file = fileInput.files[0]; + +const { file_url } = await base44.integrations.Core.UploadFile({ + file: file +}); + +// Use the URL +await base44.entities.Staff.update(staffId, { + profile_picture: file_url +}); +``` + +### Integration: UploadPrivateFile +Description: Upload a file to private storage (requires signed URL for access). + +| Parameter | Type | Required | Description | +| :-------- | :----- | :------- | :---------------------- | +| `file` | `File` | Yes | File object to upload | + +Returns: +```json +{ + "file_uri": "string" // Private file URI (not directly accessible) +} +``` + +Example: +```javascript +// Upload private document +const { file_uri } = await base44.integrations.Core.UploadPrivateFile({ + file: sensitiveDocument +}); + +// Store the URI +await base44.entities.Vendor.update(vendorId, { + w9_document: file_uri +}); + +// Later, create signed URL for access +const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({ + file_uri: file_uri, + expires_in: 3600 // 1 hour +}); +``` + +### Integration: CreateFileSignedUrl +Description: Create a temporary signed URL for accessing a private file. + +| Parameter | Type | Required | Description | +| :--------- | :-------- | :------- | :----------------------------------------------------- | +| `file_uri` | `string` | Yes | Private file URI | +| `expires_in`| `number` | No | Expiration time in seconds (default: 300) | + +Returns: +```json +{ + "signed_url": "string" // Temporary URL for file access +} +``` + +Example: +```javascript +// Create 1-hour signed URL +const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({ + file_uri: vendor.w9_document, + expires_in: 3600 +}); + +// Use signed URL +window.open(signed_url, '_blank'); +``` + +### Integration: ExtractDataFromUploadedFile +Description: Extract structured data from uploaded files (CSV, PDF, images). + +| Parameter | Type | Required | Description | +| :---------- | :-------- | :------- | :----------------------------------------------------- | +| `file_url` | `string` | Yes | URL to uploaded file | +| `json_schema`| `object` | Yes | JSON schema defining expected data structure | + +Returns: +```json +{ + "status": ""success" | "error"", + "details": "string | null", // Error details if status is error + "output": "object[] | object | null" // Extracted data if successful +} +``` + +Example: +```javascript +// Upload CSV of staff members +const { file_url } = await base44.integrations.Core.UploadFile({ + file: csvFile +}); + +// Extract data +const result = await base44.integrations.Core.ExtractDataFromUploadedFile({ + file_url: file_url, + json_schema: { + type: "array", + items: { + type: "object", + properties: { + employee_name: { type: "string" }, + email: { type: "string" }, + position: { type: "string" }, + department: { type: "string" }, + phone: { type: "string" } + } + } + } +}); + +if (result.status === "success") { + // Bulk create staff from extracted data + await base44.entities.Staff.bulkCreate(result.output); +} +``` + +### Integration: GenerateImage +Description: Generate an AI image from a text prompt. + +| Parameter | Type | Required | Description | +| :-------- | :-------- | :------- | :----------------------------------------------------- | +| `prompt` | `string` | Yes | Detailed image description | + +Returns: +```json +{ + "url": "string" // URL to generated image +} +``` + +Example: +```javascript +// Generate event banner +const { url } = await base44.integrations.Core.GenerateImage({ + prompt: "Professional corporate event banner with elegant food service theme, blue and white color scheme, modern minimalist design" +}); + +// Use the generated image +await base44.entities.Event.update(eventId, { + banner_image: url +}); +``` --- -## Meilleures Pratiques +## Data Models Reference -1. **Utiliser React Query pour la récupération de données** : Pour la mise en cache, la refraîchissement en arrière-plan et la gestion de l'état du serveur. -2. **Gérer le formatage des dates en toute sécurité** : Éviter les erreurs avec des dates non valides. -3. **Filtrer par rôle d'utilisateur** : Appliquer une logique de filtrage côté client en fonction du rôle de l'utilisateur. -4. **Opérations par lots** : Utiliser `bulkCreate` au lieu de plusieurs appels `create`. -5. **Gestion des erreurs avec des Toasts** : Fournir un retour d'information clair à l'utilisateur en cas de succès ou d'échec. +### Complete Event Object Example +```json +{ + "id": "evt_1234567890", + "event_name": "Google Campus Lunch Service", + "is_recurring": true, + "recurrence_type": "date_range", + "recurrence_start_date": "2025-01-01", + "recurrence_end_date": "2025-12-31", + "business_id": "bus_0987654321", + "business_name": "Google", + "vendor_id": "vnd_1122334455", + "vendor_name": "Elite Staffing Solutions", + "hub": "Mountain View Campus", + "contract_type": "W2", + "po_reference": "PO-2025-001", + "status": "Active", + "date": "2025-01-15", + "shifts": [ + { + "shift_name": "Lunch Shift", + "shift_contact": "John Manager", + "location_address": "1600 Amphitheatre Parkway", + "roles": [ + { + "role": "Server", + "department": "Food Service", + "count": 10, + "start_time": "11:00", + "end_time": "15:00", + "hours": 4, + "uniform": "White shirt, black pants", + "break_minutes": 30, + "cost_per_hour": 25, + "total_value": 1000, + "vendor_name": "Elite Staffing Solutions", + "vendor_id": "vnd_1122334455" + }, + { + "role": "Cook", + "department": "Kitchen", + "count": 5, + "start_time": "10:00", + "end_time": "16:00", + "hours": 6, + "uniform": "Chef whites", + "break_minutes": 30, + "cost_per_hour": 30, + "total_value": 900, + "vendor_name": "Elite Staffing Solutions", + "vendor_id": "vnd_1122334455" + } + ] + } + ], + "addons": { + "goal": { + "enabled": true, + "text": "Maintain 95% customer satisfaction" + }, + "portal_access": true, + "meal_provided": true, + "travel_time": false, + "tips": { + "enabled": true, + "amount": "pooled" + } + }, + "total": 1900, + "requested": 15, + "assigned_staff": [ + { + "staff_id": "stf_111", + "staff_name": "Maria Garcia", + "role": "Server", + "confirmed": true + }, + { + "staff_id": "stf_222", + "staff_name": "John Smith", + "role": "Cook", + "confirmed": true + } + ], + "client_name": "Sarah Johnson", + "client_email": "sarah.johnson@google.com", + "client_phone": "(650) 555-0123", + "notes": "Ensure all staff arrive 15 minutes early", + "created_date": "2025-01-01T10:00:00Z", + "updated_date": "2025-01-10T14:30:00Z", + "created_by": "admin@krow.com" +} +``` + +### Complete Staff Object Example +```json +{ + "id": "stf_9876543210", + "employee_name": "Maria Garcia", + "vendor_id": "vnd_1122334455", + "vendor_name": "Elite Staffing Solutions", + "manager": "Fernando Lopez", + "contact_number": "(415) 555-0199", + "phone": "(415) 555-0200", + "email": "maria.garcia@email.com", + "department": "Operations", + "hub_location": "San Francisco Bay Area", + "event_location": "Various", + "address": "123 Main St, Apt 4B", + "city": "San Francisco", + "position": "Server", + "position_2": "Bartender", + "initial": "MG", + "profile_type": "Skilled", + "employment_type": "Part Time", + "english": "Fluent", + "english_required": true, + "check_in": "2025-01-15", + "rating": 4.8, + "shift_coverage_percentage": 95, + "cancellation_count": 2, + "no_show_count": 0, + "total_shifts": 47, + "reliability_score": 96, + "background_check_status": "cleared", + "background_check_date": "2024-06-15", + "certifications": [ + { + "name": "Food Handler Certificate", + "issued_date": "2024-06-01", + "expiry_date": "2026-06-01", + "issuer": "ServSafe" + }, + { + "name": "Alcohol Service Permit", + "issued_date": "2024-07-01", + "expiry_date": "2025-07-01", + "issuer": "CA ABC" + } + ], + "notes": "Excellent customer service skills. Prefers weekend shifts.", + "created_date": "2024-01-10T09:00:00Z", + "updated_date": "2025-01-15T16:45:00Z", + "created_by": "vendor@elitestaffing.com" +} +``` + +### Complete Vendor Object Example +```json +{ + "id": "vnd_1122334455", + "vendor_number": "VN-0042", + "legal_name": "Elite Staffing Solutions Inc.", + "doing_business_as": "Elite Staffing", + "region": "Bay Area", + "state": "California", + "city": "San Francisco", + "service_specialty": "Event Staffing & Hospitality Services", + "workforce_count": 250, + "platform_type": "Full Platform", + "tax_id": "12-3456789", + "business_type": "Corporation", + "primary_contact_name": "Robert Chen", + "primary_contact_email": "robert.chen@elitestaffing.com", + "primary_contact_phone": "(415) 555-0100", + "billing_address": "456 Business Plaza, Suite 200, San Francisco, CA 94102", + "service_address": "456 Business Plaza, Suite 200, San Francisco, CA 94102", + "coverage_regions": [ + "San Francisco", + "Oakland", + "San Jose", + "Peninsula", + "East Bay" + ], + "eligible_roles": [ + "Server", + "Bartender", + "Cook", + "Dishwasher", + "Event Manager", + "Catering Staff" + ], + "insurance_certificate": "https://storage.example.com/certs/elite-insurance.pdf", + "insurance_expiry": "2025-12-31", + "w9_document": "https://storage.example.com/docs/elite-w9.pdf", + "coi_document": "https://storage.example.com/docs/elite-coi.pdf", + "approval_status": "approved", + "approved_date": "2024-01-15", + "approved_by": "admin@krow.com", + "is_active": true, + "notes": "Preferred vendor for tech company events. Excellent track record.", + "created_date": "2024-01-10T10:00:00Z", + "updated_date": "2025-01-05T11:20:00Z" +} +``` --- -## Gestion des Erreurs +## Code Examples -### Modèles d'Erreurs Courants +### Example 1: Create Event with Staff Assignment +```javascript +import { base44 } from "@/api/base44Client"; -* **Entité non trouvée** : Gérer les cas où un `filter` ne retourne aucun résultat. -* **Erreurs de validation** : Capturer et afficher les erreurs de validation du backend (par exemple, salaire inférieur au minimum). -* **Erreurs d'authentification** : Rediriger vers la page de connexion lorsque la session de l'utilisateur a expiré. +async function createEventAndAssignStaff() { + // Get current user + const user = await base44.auth.me(); + + // Create new event + const event = await base44.entities.Event.create({ + event_name: "Corporate Holiday Party", + business_name: "Acme Corporation", + date: "2025-12-20", + hub: "Downtown Office", + status: "Draft", + requested: 20, + shifts: [ + { + shift_name: "Evening Service", + location_address: "123 Corporate Plaza", + roles: [ + { + role: "Server", + department: "Food Service", + count: 15, + start_time: "18:00", + end_time: "23:00", + hours: 5, + cost_per_hour: 28, + total_value: 2100 + }, + { + role: "Bartender", + department: "Bar Service", + count: 5, + start_time: "17:30", + end_time: "23:30", + hours: 6, + cost_per_hour: 32, + total_value: 960 + } + ] + } + ], + total: 3060, + client_name: user.full_name, + client_email: user.email + }); + + // Find available staff + const availableStaff = await base44.entities.Staff.filter({ + position: "Server", + rating: { $gte: 4.5 }, + employment_type: { $in: ["Part Time", "Full Time"] } + }, '-rating', 15); + + // Assign staff to event + const assignedStaff = availableStaff.map(staff => ({ + staff_id: staff.id, + staff_name: staff.employee_name, + role: "Server", + confirmed: false + })); + + await base44.entities.Event.update(event.id, { + assigned_staff: assignedStaff, + status: "Pending" + }); + + // Create activity log + await base44.entities.ActivityLog.create({ + title: "Event Created", + description: `New event "${event.event_name}" created and staff assigned`, + activity_type: "event_created", + related_entity_type: "event", + related_entity_id: event.id, + user_id: user.id, + is_read: false, + icon_type: "calendar", + icon_color: "blue" + }); + + return event; +} +``` + +### Example 2: Send Invoice Reminder Emails +```javascript +import { base44 } from "@/api/base44Client"; + +async function sendInvoiceReminders() { + // Get overdue invoices + const today = new Date(); + const overdueInvoices = await base44.entities.Invoice.filter({ + status: { $in: ["Open", "Overdue"] }, + due_date: { $lt: today.toISOString().split('T')[0] } + }); + + // Send reminder for each + for (const invoice of overdueInvoices) { + // Update status + await base44.entities.Invoice.update(invoice.id, { + status: "Overdue" + }); + + // Get business contact + const business = await base44.entities.Business.filter({ + business_name: invoice.business_name + }); + + if (business.length > 0) { + const contact = business[0]; + + // Send email + await base44.integrations.Core.SendEmail({ + to: contact.email, + subject: `Payment Reminder: Invoice ${invoice.invoice_number}`, + body: ` +

Payment Reminder

+

Dear ${contact.contact_name},

+

This is a friendly reminder that invoice ${invoice.invoice_number} + for $${invoice.amount.toLocaleString()} is now overdue.

+

Due Date: ${invoice.due_date}

+

Amount: $${invoice.amount.toLocaleString()}

+

Please process payment at your earliest convenience.

+

Thank you,
KROW Workforce Team

+ `, + from_name: "KROW Accounts Receivable" + }); + + // Log activity + await base44.entities.ActivityLog.create({ + title: "Invoice Reminder Sent", + description: `Reminder sent for invoice ${invoice.invoice_number}`, + activity_type: "invoice_created", + related_entity_type: "invoice", + related_entity_id: invoice.id, + user_id: contact.id || "system", + icon_type: "invoice", + icon_color: "yellow" + }); + } + } + + return overdueInvoices.length; +} +``` + +### Example 3: AI-Powered Staff Recommendation +```javascript +import { base44 } from "@/api/base44Client"; + +async function getStaffRecommendations(eventId) { + // Get event details + const events = await base44.entities.Event.filter({ id: eventId }); + const event = events[0]; + + // Get all available staff + const allStaff = await base44.entities.Staff.list(); + + // Use AI to analyze and recommend + const recommendations = await base44.integrations.Core.InvokeLLM({ + prompt: ` + Analyze this event and recommend the best staff members. + + Event Details: + - Name: ${event.event_name} + - Date: ${event.date} + - Location: ${event.hub} + - Roles Needed: ${JSON.stringify(event.shifts)} + + Available Staff: + ${JSON.stringify(allStaff.map(s => ({ + id: s.id, + name: s.employee_name, + position: s.position, + rating: s.rating, + reliability: s.reliability_score, + experience: s.total_shifts + })))} + + Recommend the top staff for each role based on: + 1. Position match + 2. Rating and reliability + 3. Experience level + 4. Availability patterns + + Provide reasoning for each recommendation. + `, + response_json_schema: { + type: "object", + properties: { + recommendations: { + type: "array", + items: { + type: "object", + properties: { + staff_id: { type: "string" }, + staff_name: { type: "string" }, + role: { type: "string" }, + score: { type: "number" }, + reasoning: { type: "string" } + } + } + }, + overall_analysis: { type: "string" } + } + } + }); + + return recommendations; +} +``` + +### Example 4: Bulk Import Staff from CSV +```javascript +import { base44 } from "@/api/base44Client"; + +async function importStaffFromCSV(file) { + // Upload file + const { file_url } = await base44.integrations.Core.UploadFile({ + file: file + }); + + // Extract data + const result = await base44.integrations.Core.ExtractDataFromUploadedFile({ + file_url: file_url, + json_schema: { + type: "array", + items: { + type: "object", + properties: { + employee_name: { type: "string" }, + email: { type: "string" }, + phone: { type: "string" }, + position: { type: "string" }, + department: { type: "string" }, + employment_type: { type: "string" }, + vendor_name: { type: "string" } + }, + required: ["employee_name"] + } + } + }); + + if (result.status === "error") { + throw new Error(result.details); + } + + // Bulk create staff + const createdStaff = await base44.entities.Staff.bulkCreate( + result.output.map(staff => ({ + ...staff, + rating: 0, + reliability_score: 0, + total_shifts: 0, + background_check_status: "pending" + })) + ); + + // Create activity logs + await base44.entities.ActivityLog.create({ + title: "Bulk Staff Import", + description: `${createdStaff.length} staff members imported from CSV`, + activity_type: "staff_assigned", + user_id: (await base44.auth.me()).id, + icon_type: "user", + icon_color: "green" + }); + + return createdStaff; +} +``` + +### Example 5: Generate Performance Report +```javascript +import { base44 } from "@/api/base44Client"; + +async function generateVendorPerformanceReport(vendorId) { + // Get vendor details + const vendors = await base44.entities.Vendor.filter({ id: vendorId }); + const vendor = vendors[0]; + + // Get vendor's staff + const staff = await base44.entities.Staff.filter({ + vendor_id: vendorId + }); + + // Get vendor's events + const events = await base44.entities.Event.filter({ + vendor_id: vendorId, + status: "Completed" + }); + + // Calculate metrics + const totalStaff = staff.length; + const avgRating = staff.reduce((sum, s) => sum + (s.rating || 0), 0) / totalStaff; + const avgReliability = staff.reduce((sum, s) => sum + (s.reliability_score || 0), 0) / totalStaff; + const totalEvents = events.length; + const totalRevenue = events.reduce((sum, e) => sum + (e.total || 0), 0); + + // Use AI to generate insights + const report = await base44.integrations.Core.InvokeLLM({ + prompt: ` + Generate a comprehensive performance report for this vendor: + + Vendor: ${vendor.legal_name} + Workforce Size: ${totalStaff} + Average Staff Rating: ${avgRating.toFixed(2)}/5.0 + Average Reliability: ${avgReliability.toFixed(1)}% + Events Completed: ${totalEvents} + Total Revenue: $${totalRevenue.toLocaleString()} + + Staff Performance Distribution: + ${JSON.stringify(staff.map(s => ({ + name: s.employee_name, + rating: s.rating, + reliability: s.reliability_score, + shifts: s.total_shifts + })))} + + Provide: + 1. Overall performance summary + 2. Key strengths + 3. Areas for improvement + 4. Specific recommendations + 5. Comparison to industry benchmarks + `, + response_json_schema: { + type: "object", + properties: { + summary: { type: "string" }, + grade: { type: "string" }, + strengths: { + type: "array", + items: { type: "string" } + }, + improvements: { + type: "array", + items: { type: "string" } + }, + recommendations: { + type: "array", + items: { type: "string" } + }, + benchmark_comparison: { type: "string" } + } + } + }); + + return { + vendor, + metrics: { + totalStaff, + avgRating, + avgReliability, + totalEvents, + totalRevenue + }, + analysis: report + }; +} +``` --- -## Exemples +## Best Practices -### Flux de Commande Complet +### 1. Error Handling +```javascript +try { + const event = await base44.entities.Event.create(eventData); + // Success handling +} catch (error) { + console.error("Failed to create event:", error); + // Show user-friendly error message + toast({ + title: "❌ Error", + description: "Failed to create event. Please try again.", + variant: "destructive" + }); +} +``` -1. **Créer un événement** en utilisant `base44.entities.Event.create`. -2. **Assigner du personnel** en filtrant le personnel disponible et en mettant à jour l'événement. -3. **Envoyer des notifications** aux membres du personnel assignés via `ActivityLog` et `SendEmail`. -4. **Créer une facture** pour l'événement complété. +### 2. Query Optimization +```javascript +// ❌ Bad: Fetch all then filter in memory +const allEvents = await base44.entities.Event.list(); +const vendorEvents = allEvents.filter(e => e.vendor_id === vendorId); -### Surveillance de la Conformité +// ✅ Good: Filter at database level +const vendorEvents = await base44.entities.Event.filter({ + vendor_id: vendorId +}); +``` -* Surveiller les **certifications expirant bientôt** et notifier les employés. -* Vérifier la **conformité des salaires** par rapport au salaire minimum. +### 3. Pagination +```javascript +// Fetch in batches +const pageSize = 50; +let page = 0; +let allRecords = []; -### Tableau de Bord Analytique +while (true) { + const batch = await base44.entities.Event.list( + '-created_date', + pageSize, + page * pageSize + ); + + if (batch.length === 0) break; + + allRecords = [...allRecords, ...batch]; + page++; +} +``` -* Calculer des **statistiques sur les événements** (total, actifs, revenus). -* Identifier les **meilleurs performers** parmi le personnel en fonction de l'évaluation et de la couverture des quarts. -* Suivre la **performance des fournisseurs** actifs et approuvés. +### 4. Caching with React Query +```javascript +import { useQuery } from "@tanstack/react-query"; + +function useEvents() { + return useQuery({ + queryKey: ['events'], + queryFn: () => base44.entities.Event.list('-date'), + initialData: [], + staleTime: 5 * 60 * 1000, // 5 minutes + cacheTime: 10 * 60 * 1000 // 10 minutes + }); +} +``` + +### 5. Batch Operations +```javascript +// ❌ Bad: Multiple sequential creates +for (const staff of staffList) { + await base44.entities.Staff.create(staff); +} + +// ✅ Good: Single bulk create +await base44.entities.Staff.bulkCreate(staffList); +``` --- -## Limites de Taux & Performance +## Security Considerations -* Pas de limites de taux explicites sur la plateforme Base44. -* Utiliser la **pagination** pour les grands ensembles de données. -* Privilégier les **opérations par lots**. -* Utiliser le **filtrage côté serveur** (`filter()`) au lieu de la récupération complète. +### 1. User Entity Access Control +- Only admin users can access other users' data +- Regular users can only view/update their own records +- Built-in security rules are automatically enforced + +### 2. Private Files +- Use `UploadPrivateFile` for sensitive documents +- Always use signed URLs with appropriate expiration +- Never expose private file URIs directly + +### 3. Email Validation +- Always validate email formats before sending +- Use proper HTML escaping in email bodies +- Consider rate limiting for bulk emails + +### 4. Data Validation +- Validate all input data before entity operations +- Use enum constraints where applicable +- Implement client-side validation before API calls --- -## Support & Ressources +## Rate Limits & Quotas -* **Documentation de la plateforme :** [Documentation Base44](https://example.com) -* **Signalement de problèmes :** Utiliser le bouton de feedback dans l'application. -* **Demandes de fonctionnalités :** Contacter l'équipe Base44. -* **Support d'urgence :** [Informations de contact] +### Standard Limits +- Entity Operations: 1000 requests/minute +- LLM Invocations: 100 requests/minute +- File Uploads: 100 MB per file +- Email Sending: 1000 emails/day + +### Best Practices for Limits +- Implement exponential backoff for retries +- Cache frequently accessed data +- Use bulk operations when possible +- Monitor usage via activity logs --- -## Journal des Modifications +## Changelog -**Version 1.0.0 (Décembre 2024)** -* Documentation initiale de l'API. -* Documentation de toutes les entités principales. -* Documentation des points de terminaison d'intégration. -* Ajout d'exemples et de meilleures pratiques. \ No newline at end of file +### Version 2.0 (2025-01-11) +- Complete entity schema documentation +- Added 17 entity schemas with full field specifications +- Comprehensive SDK operation examples +- Core integration specifications +- Advanced code examples +- Best practices and security guidelines + +### Version 1.0 (2024-12-01) +- Initial API documentation +- Basic entity schemas +- Core integration endpoints + +--- + +## Support & Resources + +- **Documentation** + - Platform Docs: `https://docs.base44.com` + - API Reference: `https://api.base44.com/docs` + - Community Forum: `https://community.base44.com` +- **Contact** + - Technical Support: `support@krow.com` + - Sales Inquiries: `sales@krow.com` + - General Questions: `info@krow.com` + +© 2025 KROW Workforce. All rights reserved. \ No newline at end of file diff --git a/docs/MAINTENANCE_GUIDE.md b/docs/MAINTENANCE_GUIDE.md new file mode 100644 index 00000000..de26c1c2 --- /dev/null +++ b/docs/MAINTENANCE_GUIDE.md @@ -0,0 +1,55 @@ +# 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" + ``` + +--- diff --git a/docs/api_specification.md b/docs/api_specification.md index 36c036a0..d88e5dcd 100644 --- a/docs/api_specification.md +++ b/docs/api_specification.md @@ -1,8 +1,8 @@ # Spécification de l'API KROW Workforce (Migration GCP) -**Version :** 1.0 -**Date :** 10/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 fournie par Base44 et une analyse exhaustive de l'utilisation de son SDK dans le code source du frontend. +**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. --- @@ -24,218 +24,215 @@ 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` +### 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 (`admin`, `procurement`, `client`...) | -| `company_name` | `string` | Nom de l'entreprise associée | -| `profile_picture` | `string` | URL de l'image de profil | +| `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é. -- **Utilisation observée :** `base44.auth.me()` (utilisé dans presque toutes les pages). -- **Réponse (200 OK) :** - ```json - { - "id": "firebase-user-id-123", - "email": "dev@example.com", - "full_name": "Dev User", - "user_role": "admin", - "company_name": "KROW Corp", - "profile_picture": "https://..." - } - ``` +- **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. -- **Utilisation observée :** `base44.auth.updateMe(data)` (dans `WorkforceProfile.jsx`, `RoleSwitcher.jsx`). -- **Corps de la requête :** - ```json - { - "full_name": "John Doe", - "profile_picture": "https://..." - } - ``` +- **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 (CRUD) +## 2. Entités (Endpoints CRUD) -### 2.1. Event +Pour chaque entité ci-dessous, les endpoints standards suivants sont à implémenter. -**Description :** Gère les commandes de main-d'œuvre. +- `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. -#### Schéma `Event` +### 2.1. Event (`/events`) -| Champ | Type | Description | -| ------------- | -------- | ------------------------------------------------------------------------ | -| `event_name` | `string` | Nom de l'événement/commande | -| `order_type` | `string` | Enum: `rapid`, `one_time`, `recurring`, `permanent` | -| `business_id` | `string` | ID de l'entité `Business` (client) | -| `vendor_id` | `string` | ID de l'entité `Vendor` (fournisseur) | -| `status` | `string` | Enum: `Draft`, `Active`, `Pending`, `Assigned`, `Confirmed`, `Completed`, `Canceled` | -| `shifts` | `array` | Tableau d'objets `Shift` (défini comme une sous-entité ou un type JSON) | -| `date` | `string` | ISO 8601 Timestamp, date de début de l'événement | +**Description :** Gère les événements et les commandes de main-d'œuvre. -#### Endpoints +| 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é | -- **`POST /events`** - - **SDK :** `base44.entities.Event.create(eventData)` - - **Utilisation :** `CreateEvent.jsx`, `QuickReorderModal.jsx` - - **Body :** Objet `Event` sans les champs communs. - - **Réponse :** Le nouvel objet `Event` créé. - -- **`GET /events`** - - **SDK :** `base44.entities.Event.list(sort, limit)` et `.filter(query, sort, limit)` - - **Utilisation :** `Events.jsx`, `Dashboard.jsx`, `WorkforceShifts.jsx`, etc. - - **Paramètres de requête :** - - `sort` (ex: `-date` pour trier par date décroissante) - - `limit` (ex: `50`) - - Autres champs de l'entité pour le filtrage (ex: `status=Active`) - - **Réponse :** Tableau d'objets `Event`. - -- **`PUT /events/{id}`** - - **SDK :** `base44.entities.Event.update(id, data)` - - **Utilisation :** `EditEvent.jsx`, `QuickAssignPopover.jsx` - - **Body :** Un objet avec les champs de `Event` à mettre à jour. - - **Réponse :** L'objet `Event` mis à jour. - -### 2.2. Staff +### 2.2. Staff (`/staff`) **Description :** Gère les membres du personnel. -#### Schéma `Staff` +| 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 | -| Champ | Type | Description | -| ------------------------- | -------- | ----------------------------------------- | -| `employee_name` | `string` | Requis. Nom de l'employé. | -| `vendor_id` | `string` | Fournisseur auquel l'employé est rattaché. | -| `rating` | `number` | Note de 0 à 5. | -| `shift_coverage_percentage` | `number` | Pourcentage de shifts couverts. | -| `background_check_status` | `string` | Enum: `pending`, `cleared`, `failed`, `expired` | +### 2.3. Vendor (`/vendors`) -#### Endpoints +**Description :** Gère les fournisseurs et leur onboarding. -- **`POST /staff`** - - **SDK :** `base44.entities.Staff.create(staffData)` - - **Utilisation :** `AddStaff.jsx` - - **Body :** Objet `Staff` sans les champs communs. - - **Réponse :** Le nouvel objet `Staff` créé. +| 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 | -- **`GET /staff`** - - **SDK :** `base44.entities.Staff.list(sort, limit)` - - **Utilisation :** `StaffDirectory.jsx`, `Dashboard.jsx`, `Reports.jsx`, etc. - - **Paramètres de requête :** `sort`, `limit`, et autres champs pour le filtrage. - - **Réponse :** Tableau d'objets `Staff`. +### 2.4. VendorRate (`/vendor-rates`) -- **`PUT /staff/{id}`** - - **SDK :** `base44.entities.Staff.update(id, data)` - - **Utilisation :** `EditStaff.jsx` - - **Body :** Un objet avec les champs de `Staff` à mettre à jour. - - **Réponse :** L'objet `Staff` mis à jour. +**Description :** Gère les grilles tarifaires des fournisseurs. -### 2.3. Vendor +| 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é | -**Description :** Gère les fournisseurs de services. +### 2.5. Invoice (`/invoices`) -#### Schéma `Vendor` +**Description :** Gère les factures. -| Champ | Type | Description | -| --------------- | --------- | ----------------------------------------- | -| `vendor_number` | `string` | Format: `VN-####` | -| `legal_name` | `string` | Requis. Nom légal. | -| `approval_status` | `string` | Enum: `pending`, `approved`, `suspended`, `terminated` | -| `is_active` | `boolean` | Statut d'activité. | +| 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) | -#### Endpoints +### 2.6. Business (`/businesses`) -- **`POST /vendors`** - - **SDK :** `base44.entities.Vendor.create(data)` - - **Utilisation :** `VendorOnboarding.jsx`, `SmartVendorOnboarding.jsx` - - **Body :** Objet `Vendor`. - - **Réponse :** Le nouvel objet `Vendor` créé. +**Description :** Gère les entreprises clientes. -- **`GET /vendors`** - - **SDK :** `base44.entities.Vendor.list()` et `.filter()` - - **Utilisation :** `VendorManagement.jsx` - - **Paramètres de requête :** `sort`, `limit`, `approval_status`, etc. - - **Réponse :** Tableau d'objets `Vendor`. - -- **`PUT /vendors/{id}`** - - **SDK :** `base44.entities.Vendor.update(id, data)` - - **Utilisation :** `EditVendor.jsx`, `VendorManagement.jsx` - - **Body :** Champs de `Vendor` à mettre à jour. - - **Réponse :** L'objet `Vendor` mis à jour. +| 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` | --- -### 2.4. Autres Entités Majeures (Structure Similaire) - -La même structure d'endpoints (POST, GET, PUT) doit être créée pour les entités suivantes, en se basant sur les schémas à obtenir et l'utilisation observée dans le code : - -- **`VendorRate`**: Gère les tarifs des fournisseurs. -- **`Business`**: Gère les clients. -- **`Invoice`**: Gère les factures. -- **`Team`, `TeamMember`, `TeamMemberInvite`**: Gère les équipes et les invitations. -- **`ActivityLog`**: Gère les notifications et les journaux d'activité. -- **`Certification`**: Gère les certifications du personnel. -- **`Enterprise`, `Sector`, `Partner`**: Gèrent la hiérarchie organisationnelle. -- **`Conversation`, `Message`**: Gèrent la messagerie interne. -- ... et toutes les autres entités listées dans `api/entities.js`. +*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 -Ces endpoints ne sont pas des CRUDs mais des appels à des services spécifiques. +### `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 :** `base44.integrations.Core.SendEmail(params)` -- **Utilisation :** `InviteVendor.jsx`, `TeamDetails.jsx`, etc. -- **Body :** - ```json - { - "to": "recipient@example.com", - "subject": "Sujet de l'email", - "body": "

Contenu HTML

" - } - ``` +- **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 vers Google Cloud Storage. -- **SDK :** `base44.integrations.Core.UploadFile({ file })` -- **Utilisation :** `WorkforceProfile.jsx`, `VendorOnboarding.jsx`, etc. -- **Requête :** Doit être une requête `multipart/form-data`. -- **Réponse (200 OK) :** - ```json - { - "file_url": "https://storage.googleapis.com/..." - } - ``` +- **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/invoke-llm` -- **Description :** Fait appel à un modèle de langage (Vertex AI). -- **SDK :** `base44.integrations.Core.InvokeLLM({ prompt })` -- **Utilisation :** `SmartVendorOnboarding.jsx`, `VendorCompliance.jsx` -- **Body :** - ```json - { - "prompt": "Analyse ce document et extrais les informations suivantes...", - "context": "..." // Contexte additionnel - } - ``` -- **Réponse (200 OK) :** - ```json - { - "result": "Texte ou JSON généré par le LLM" - } - ``` +### `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://..." }` \ No newline at end of file diff --git a/docs/base44_prompts.md b/docs/base44_prompts.md new file mode 100644 index 00000000..5cf446fb --- /dev/null +++ b/docs/base44_prompts.md @@ -0,0 +1,55 @@ +# Prompts pour l'IA de Base44 + +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. + +## 1. Prompt Principal : Demande de Documentation Complète (Version Discrète et Itérative) + +*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.* + +--- + +```text +Hello! + +I am the lead developer for the "KROW Workforce" project. We are looking to deeply integrate the Base44 platform into our wider ecosystem by building several custom tools and automations. + +Previously, you generated an `API_documentation.md` file that was incredibly helpful for our team. To ensure our new integration projects are built using the most current project state, could you please refresh and exhaustively update this `API_documentation.md` file? + +Please conduct a full review of our project and ensure the updated documentation includes the following for **all current entities** (Events, Staff, Vendors, Invoices, Users, Teams, etc.): + +1. **Entity Data Schemas**: For each entity, a detailed breakdown of its fields in a table or JSON Schema format, including: + * `Field Name` + * `Data Type` (e.g., `string`, `number`, `timestamp`) + * `Description` of the field's purpose. + * `Validation Rules` (e.g., `required`, `unique`, `enum` values). + +2. **SDK Operations**: A complete list of all available SDK methods for each entity (e.g., `.list()`, `.filter()`, `.create()`, `.update()`). + +3. **Integrations API**: The full specification for all services under `base44.integrations.Core` (`SendEmail`, `InvokeLLM`, etc.), including their input parameters and output structure. + +After you have updated the file, please output the **entire, updated content** of `API_documentation.md` in your response. This will serve as the single source of truth for our development team. + +**IMPORTANT: Please ensure you output the ENTIRE, updated content of `API_documentation.md` directly in your response, not just a summary.** + +Thank you! +``` + +--- + +## 2. Prompt Secondaire : Demande de Schéma pour une Entité Spécifique + +*Utilisez ce prompt si vous avez besoin de vérifier rapidement la structure d'une seule entité sans demander la documentation complète.* + +--- + +```text +Hello! + +For the "KROW Workforce" project, could you please provide the detailed data schema for the **[ENTITY_NAME]** entity? + +Please format the response as a JSON Schema or a Markdown table, including the field names, data types, a description of each field, and any validation rules (like `required` fields or `enum` values). + +For example, for an entity named `Event`. +``` + +---