Commit Graph

123 Commits

Author SHA1 Message Date
Urtzi Alfaro
a030bd14c8 demo seed change 2 2025-12-14 11:58:14 +01:00
Urtzi Alfaro
ff830a3415 demo seed change 2025-12-13 23:57:54 +01:00
Urtzi Alfaro
10c779858a Fix enum mismatch: Update Python enums and seed data to match database uppercase values
- Fixed ProductType enum values from lowercase to uppercase (INGREDIENT, FINISHED_PRODUCT)
- Fixed UnitOfMeasure enum values from lowercase/abbreviated to uppercase (KILOGRAMS, LITERS, etc.)
- Fixed IngredientCategory enum values from lowercase to uppercase (FLOUR, YEAST, etc.)
- Fixed ProductCategory enum values from lowercase to uppercase (BREAD, CROISSANTS, etc.)
- Updated seed data files to use correct uppercase enum values
- Fixed hardcoded enum references throughout the codebase
- This resolves the InvalidTextRepresentationError when inserting inventory data

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2025-12-13 16:49:04 +01:00
Urtzi Alfaro
508f4569b9 Fix and UI imporvements 2025-12-09 10:21:41 +01:00
Urtzi Alfaro
667e6e0404 New alert service 2025-12-05 20:07:01 +01:00
Urtzi Alfaro
0da0470786 New enterprise feature2 2025-11-30 16:29:38 +01:00
Urtzi Alfaro
972db02f6d New enterprise feature 2025-11-30 09:12:40 +01:00
Urtzi Alfaro
e902419b6e New alert system and panel de control page 2025-11-27 15:52:40 +01:00
Urtzi Alfaro
1a2f4602f3 revert(demo): Restore BASE_REFERENCE_DATE to November 25, 2025
The date adjustment logic was correct. The BASE_REFERENCE_DATE is used
by adjust_date_for_demo() to calculate offsets relative to demo session
creation time, not to filter for "today's" data.

Production batches showing "Sin Plan" must have a different root cause.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 11:04:21 +01:00
Urtzi Alfaro
b545d05d23 fix(dashboard): Fix production plans and reasoning modal issues
1. **Fix "Sin Plan" (No Production Planned)**:
   - Updated BASE_REFERENCE_DATE from Nov 25 to Nov 27 to match current date
   - Production batches were being filtered out because they were dated for Nov 25
   - The get_todays_batches() method filters for batches scheduled TODAY

2. **Fix "Ver razonamiento" Button Not Opening Modal**:
   - Changed handleOpenReasoning() to always emit 'reasoning:show' event
   - Previous logic tried to navigate to PO/batch detail pages instead
   - Now keeps user on dashboard and shows reasoning modal inline
   - Passes all metadata (action_id, po_id, batch_id, reasoning) in event

This ensures production progress shows correctly and users can view
AI reasoning without leaving the dashboard.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 11:02:59 +01:00
Urtzi Alfaro
8bce5ee594 fix(demo): Update BASE_REFERENCE_DATE to November 2025
Update BASE_REFERENCE_DATE from January 15, 2025 to November 25, 2025
to ensure demo data appears recent and relevant.

This fixes the "11 meses" (11 months) display issue in GlanceableHealthHero
where lastOrchestrationRun was showing an 11-month-old timestamp.

The BASE_REFERENCE_DATE is used by all demo seeding scripts to calculate
relative dates. With the updated reference date, the most recent
orchestration runs will show as "hace 2 días" or similar instead of
"hace 11 meses".

Impact:
- All demo seed data timestamps will be relative to Nov 25, 2025
- Dashboard will show "Last run: 2 days ago" instead of "11 months ago"
- Expiration dates, delivery dates, and other temporal data remain
  properly offset from the new reference

Fixes: Issue #6 - "11 meses" data bug

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 07:43:31 +01:00
Urtzi Alfaro
3242c8d837 Improve te panel de control logic 2025-11-21 16:15:09 +01:00
Urtzi Alfaro
29e6ddcea9 Improve frontend 3 2025-11-19 22:12:51 +01:00
Urtzi Alfaro
938df0866e Implement subscription tier redesign and component consolidation
This comprehensive update includes two major improvements:

## 1. Subscription Tier Redesign (Conversion-Optimized)

Frontend enhancements:
- Add PlanComparisonTable component for side-by-side tier comparison
- Add UsageMetricCard with predictive analytics and trend visualization
- Add ROICalculator for real-time savings calculation
- Add PricingComparisonModal for detailed plan comparisons
- Enhance SubscriptionPricingCards with behavioral economics (Professional tier prominence)
- Integrate useSubscription hook for real-time usage forecast data
- Update SubscriptionPage with enhanced metrics, warnings, and CTAs
- Add subscriptionAnalytics utility with 20+ conversion tracking events

Backend APIs:
- Add usage forecast endpoint with linear regression predictions
- Add daily usage tracking for trend analysis (usage_forecast.py)
- Enhance subscription error responses for conversion optimization
- Update tenant operations for usage data collection

Infrastructure:
- Add usage tracker CronJob for daily snapshot collection
- Add track_daily_usage.py script for automated usage tracking

Internationalization:
- Add 109 translation keys across EN/ES/EU for subscription features
- Translate ROI calculator, plan comparison, and usage metrics
- Update landing page translations with subscription messaging

Documentation:
- Add comprehensive deployment checklist
- Add integration guide with code examples
- Add technical implementation details (710 lines)
- Add quick reference guide for common tasks
- Add final integration summary

Expected impact: +40% Professional tier conversions, +25% average contract value

## 2. Component Consolidation and Cleanup

Purchase Order components:
- Create UnifiedPurchaseOrderModal to replace redundant modals
- Consolidate PurchaseOrderDetailsModal functionality into unified component
- Update DashboardPage to use UnifiedPurchaseOrderModal
- Update ProcurementPage to use unified approach
- Add 27 new translation keys for purchase order workflows

Production components:
- Replace CompactProcessStageTracker with ProcessStageTracker
- Update ProductionPage with enhanced stage tracking
- Improve production workflow visibility

UI improvements:
- Enhance EditViewModal with better field handling
- Improve modal reusability across domain components
- Add support for approval workflows in unified modals

Code cleanup:
- Remove obsolete PurchaseOrderDetailsModal (620 lines)
- Remove obsolete CompactProcessStageTracker (303 lines)
- Net reduction: 720 lines of code while adding features
- Improve maintainability with single source of truth

Build verified: All changes compile successfully
Total changes: 29 files, 1,183 additions, 1,903 deletions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-19 21:01:06 +01:00
Urtzi Alfaro
5c45164c8e Improve backend 2025-11-18 07:17:17 +01:00
Urtzi Alfaro
843cd2bf5c Improve the UI and training 2025-11-15 15:20:10 +01:00
Urtzi Alfaro
c349b845a6 Bug fixes of training 2025-11-14 20:27:39 +01:00
Urtzi Alfaro
a8d8828935 imporve features 2025-11-14 07:23:56 +01:00
Urtzi Alfaro
9bc048d360 Add whatsapp feature 2025-11-13 16:01:08 +01:00
Urtzi Alfaro
5783c7ed05 Add POI feature and imporve the overall backend implementation 2025-11-12 15:34:10 +01:00
Claude
413f652bbc fix: Align dashboard API calls with actual procurement and production service endpoints
CRITICAL FIX: Dashboard was calling non-existent API endpoints

The Problem:
------------
The orchestrator dashboard service was calling API endpoints that don't exist:
1. Procurement: Expected dict {items: [...]} but API returns array [...]
2. Production: Called /production/production-batches/today - doesn't exist
3. Production: Called /production/production-batches - doesn't exist

Root Cause:
-----------
Created client methods without verifying actual backend API structure.
Made assumptions about response formats that didn't match reality.

The Fix:
--------
**1. Procurement Client (shared/clients/procurement_client.py)**
- Fixed get_pending_purchase_orders return type: Dict → List
- Procurement API returns: List[PurchaseOrderResponse] directly
- Changed: "Dict with {items: [...], total: n}" → "List of purchase order dicts"

**2. Production Client (shared/clients/production_client.py)**
- Fixed get_todays_batches endpoint:
  OLD: "/production/production-batches/today" (doesn't exist)
  NEW: "/production/batches?start_date=today&end_date=today"

- Fixed get_production_batches_by_status endpoint:
  OLD: "/production/production-batches?status=X"
  NEW: "/production/batches?status=X"

- Updated return type docs: {"items": [...]} → {"batches": [...], "total_count": n}
- Response structure: ProductionBatchListResponse (batches, total_count, page, page_size)

**3. Orchestrator Dashboard API (services/orchestrator/app/api/dashboard.py)**
- Fixed all po_data access patterns:
  OLD: po_data.get("items", [])
  NEW: direct list access or po_data if isinstance(po_data, list)

- Fixed production batch access:
  OLD: prod_data.get("items", [])
  NEW: prod_data.get("batches", [])

- Updated 6 locations:
  * Line 206: health-status pending POs count
  * Line 216: health-status production delays count
  * Line 274-281: orchestration-summary PO summaries
  * Line 328-329: action-queue pending POs
  * Line 472-487: insights deliveries calculation
  * Line 499-519: insights savings calculation

Verified Against:
-----------------
Frontend successfully calls these exact APIs:
- /tenants/{id}/procurement/purchase-orders (ProcurementPage.tsx)
- /tenants/{id}/production/batches (production hooks)

Both return arrays/objects as documented in their respective API files:
- services/procurement/app/api/purchase_orders.py: returns List[PurchaseOrderResponse]
- services/production/app/api/production_batches.py: returns ProductionBatchListResponse

Now dashboard calls match actual backend APIs! 
2025-11-08 06:56:30 +00:00
Claude
bc97fc0d1a refactor: Extract alerts functionality to dedicated AlertsServiceClient
Moved alert-related methods from ProcurementServiceClient to a new
dedicated AlertsServiceClient for better separation of concerns.

Changes:
- Created shared/clients/alerts_client.py:
  * get_alerts_summary() - Alert counts by severity/status
  * get_critical_alerts() - Filtered list of urgent alerts
  * get_alerts_by_severity() - Filter by any severity level
  * get_alert_by_id() - Get specific alert details
  * Includes severity mapping (critical → urgent)

- Updated shared/clients/__init__.py:
  * Added AlertsServiceClient import/export
  * Added get_alerts_client() factory function

- Updated procurement_client.py:
  * Removed get_critical_alerts() method
  * Removed get_alerts_summary() method
  * Kept only procurement-specific methods

- Updated dashboard.py:
  * Import and initialize alerts_client
  * Use alerts_client for alert operations
  * Use procurement_client only for procurement operations

Benefits:
- Better separation of concerns
- Alerts logically grouped with alert_processor service
- Cleaner, more maintainable service client architecture
- Each client maps to its domain service
2025-11-07 22:19:24 +00:00
Claude
41d292913a feat: Add alert endpoints to alert_processor service for dashboard
Implemented missing alert endpoints that the dashboard requires for
health status and action queue functionality.

Alert Processor Service Changes:
- Created alerts_repository.py:
  * get_alerts() - Filter alerts by severity/status/resolved with pagination
  * get_alerts_summary() - Count alerts by severity and status
  * get_alert_by_id() - Get specific alert

- Created alerts.py API endpoints:
  * GET /api/v1/tenants/{tenant_id}/alerts/summary - Alert counts
  * GET /api/v1/tenants/{tenant_id}/alerts - Filtered alert list
  * GET /api/v1/tenants/{tenant_id}/alerts/{alert_id} - Single alert

- Severity mapping: "critical" (dashboard) maps to "urgent" (alert_processor)
- Status enum: active, resolved, acknowledged, ignored
- Severity enum: low, medium, high, urgent

API Server Changes:
- Registered alerts_router in api_server.py
- Exported alerts_router in __init__.py

Procurement Client Changes:
- Updated get_critical_alerts() to use /alerts path
- Updated get_alerts_summary() to use /alerts/summary path
- Added severity mapping (critical → urgent)
- Added documentation about gateway routing

This fixes the 404 errors for alert endpoints in the dashboard.
2025-11-07 22:16:16 +00:00
Claude
6cd4ef0f56 feat: Add dedicated dashboard methods to service clients
Created typed, domain-specific methods in service clients instead of
using generic .get() calls with paths. This improves type safety,
discoverability, and maintainability.

Service Client Changes:
- ProcurementServiceClient:
  * get_pending_purchase_orders() - POs awaiting approval
  * get_critical_alerts() - Critical severity alerts
  * get_alerts_summary() - Alert counts by severity

- ProductionServiceClient:
  * get_todays_batches() - Today's production timeline
  * get_production_batches_by_status() - Filter by status

- InventoryServiceClient:
  * get_stock_status() - Dashboard stock metrics
  * get_sustainability_widget() - Sustainability data

Dashboard API Changes:
- Updated all endpoints to use new dedicated methods
- Cleaner, more maintainable code
- Better error handling and logging
- Fixed inventory data type handling (list vs dict)

Note: Alert endpoints return 404 - alert_processor service needs
endpoints: /alerts/summary and /alerts (filtered by severity).
2025-11-07 22:12:21 +00:00
Claude
b85e8d760b feat: Add remaining production batch reasoning helper functions
Added missing helper functions for all production batch reasoning types:
- create_batch_reasoning_stock_replenishment: Inventory replenishment
- create_batch_reasoning_seasonal_preparation: Seasonal demand prep
- create_batch_reasoning_promotion_event: Promotional events
- create_batch_reasoning_urgent_order: Urgent customer orders

This completes the full set of reasoning helper functions for both
purchase orders and production batches, preventing future import errors
in demo seed scripts and other services.

All helpers now provide structured reasoning_data for i18n translation.
2025-11-07 19:47:12 +00:00
Claude
0a2982d22f feat: Add complete set of PO reasoning helper functions
Added missing helper functions for all purchase order reasoning types:
- create_po_reasoning_supplier_contract: Contract-based orders
- create_po_reasoning_safety_stock: Safety stock replenishment
- create_po_reasoning_seasonal_demand: Seasonal preparation
- create_po_reasoning_production_requirement: Production needs
- create_po_reasoning_manual_request: Manual orders

These functions generate structured reasoning_data for i18n translation
and provide consistent reasoning structure across all PO types.

Fixes ImportError in demo-seed-purchase-orders pod.
2025-11-07 19:46:27 +00:00
Claude
0fb519f0c4 fix: Add missing create_batch_reasoning_regular_schedule helper function
Demo seed script was failing with ImportError because the
create_batch_reasoning_regular_schedule function was referenced
but not implemented in reasoning_types.py.

Added the missing helper function to support REGULAR_SCHEDULE
batch reasoning type for regular scheduled production batches.

Fixes container restart loop in demo-seed-production-batches pod.
2025-11-07 19:35:51 +00:00
Claude
9d284cae46 refactor: Convert internal services to structured JSON reasoning
Convert pipe-separated reasoning codes to structured JSON format for:
- Safety stock calculator (statistical calculations, errors)
- Price forecaster (procurement recommendations, volatility)
- Order optimization (EOQ, tier pricing)

This enables i18n translation of internal calculation reasoning
and provides structured data for frontend AI insights display.

Benefits:
- Consistent with PO/Batch reasoning_data format
- Frontend can translate using same i18n infrastructure
- Structured parameters enable rich UI visualization
- No legacy string parsing needed

Changes:
- safety_stock_calculator.py: Replace reasoning str with reasoning_data dict
- price_forecaster.py: Convert recommendation reasoning to structured format
- optimization.py: Update EOQ and tier pricing to use reasoning_data

Part of complete i18n implementation for AI insights.
2025-11-07 19:22:02 +00:00
Claude
be8cb20b18 fix: Replace all remaining hardcoded English reasoning with structured codes
This commit removes the last hardcoded English text from reasoning fields
across all backend services, completing the i18n implementation.

Changes by service:

Safety Stock Calculator (safety_stock_calculator.py):
- CALC:STATISTICAL_Z_SCORE - Statistical calculation with Z-score
- CALC:ADVANCED_VARIABILITY - Advanced formula with demand and lead time variability
- CALC:FIXED_PERCENTAGE - Fixed percentage of lead time demand
- All calculation methods now use structured codes with pipe-separated parameters

Price Forecaster (price_forecaster.py):
- PRICE_FORECAST:DECREASE_EXPECTED - Price expected to decrease
- PRICE_FORECAST:INCREASE_EXPECTED - Price expected to increase
- PRICE_FORECAST:HIGH_VOLATILITY - High price volatility detected
- PRICE_FORECAST:BELOW_AVERAGE - Current price below average (buy opportunity)
- PRICE_FORECAST:STABLE - Price stable, normal schedule
- All forecasts include relevant parameters (change_pct, days, etc.)

Optimization Utils (shared/utils/optimization.py):
- EOQ:BASE - Economic Order Quantity base calculation
- EOQ:MOQ_APPLIED - Minimum order quantity constraint applied
- EOQ:MAX_APPLIED - Maximum order quantity constraint applied
- TIER_PRICING:CURRENT_TIER - Current tier pricing
- TIER_PRICING:UPGRADED - Upgraded to higher tier for savings
- All optimizations include calculation parameters

Format: All codes use pattern "CATEGORY:TYPE|param1=value|param2=value"
This allows frontend to parse and translate with parameters while maintaining
technical accuracy for logging and debugging.

Frontend can now translate ALL reasoning codes across the entire system.
2025-11-07 19:00:00 +00:00
Claude
ddc4928d78 feat: Implement structured reasoning_data generation for i18n support
Implemented proper reasoning data generation for purchase orders and
production batches to enable multilingual dashboard support.

Backend Strategy:
- Generate structured JSON with type codes and parameters
- Store only reasoning_data (JSONB), not hardcoded text
- Frontend will translate using i18n libraries

Changes:
1. Created shared/schemas/reasoning_types.py
   - Defined reasoning types for POs and batches
   - Created helper functions for common reasoning patterns
   - Supports multiple reasoning types (low_stock, forecast_demand, etc.)

2. Production Service (services/production/app/services/production_service.py)
   - Generate reasoning_data when creating batches from forecast
   - Include parameters: product_name, predicted_demand, current_stock, etc.
   - Structure supports frontend i18n interpolation

3. Procurement Service (services/procurement/app/services/procurement_service.py)
   - Implemented actual PO creation (was placeholder before!)
   - Groups requirements by supplier
   - Generates reasoning_data based on context (low_stock vs forecast)
   - Creates PO items automatically

Example reasoning_data:
{
  "type": "low_stock_detection",
  "parameters": {
    "supplier_name": "Harinas del Norte",
    "product_names": ["Flour Type 55", "Flour Type 45"],
    "days_until_stockout": 3,
    "current_stock": 45.5,
    "required_stock": 200
  },
  "consequence": {
    "type": "stockout_risk",
    "severity": "high",
    "impact_days": 3
  }
}

Frontend will translate:
- EN: "Low stock detected for Harinas del Norte. Stock runs out in 3 days."
- ES: "Stock bajo detectado para Harinas del Norte. Se agota en 3 días."
- CA: "Estoc baix detectat per Harinas del Norte. S'esgota en 3 dies."

Next steps:
- Remove TEXT fields (reasoning, consequence) from models
- Update dashboard service to use reasoning_data
- Create frontend i18n translation keys
- Update dashboard components to translate dynamically
2025-11-07 18:16:44 +00:00
Urtzi Alfaro
3ad093d38b Fix orchestrator issues 2025-11-05 22:54:14 +01:00
Urtzi Alfaro
394ad3aea4 Improve AI logic 2025-11-05 13:34:56 +01:00
Urtzi Alfaro
5adb0e39c0 Improve the frontend 5 2025-11-02 20:24:44 +01:00
Urtzi Alfaro
269d3b5032 Add user delete process 2025-10-31 11:54:19 +01:00
Urtzi Alfaro
63f5c6d512 Improve the frontend 3 2025-10-30 21:08:07 +01:00
Urtzi Alfaro
36217a2729 Improve the frontend 2 2025-10-29 06:58:05 +01:00
Urtzi Alfaro
858d985c92 Improve the frontend modals 2025-10-27 16:33:26 +01:00
Urtzi Alfaro
61376b7a9f Improve the frontend and fix TODOs 2025-10-24 13:05:04 +02:00
Urtzi Alfaro
07c33fa578 Improve the frontend and repository layer 2025-10-23 07:44:54 +02:00
Urtzi Alfaro
8d30172483 Improve the frontend 2025-10-21 19:50:07 +02:00
Urtzi Alfaro
05da20357d Improve teh securty of teh DB 2025-10-19 19:22:37 +02:00
Urtzi Alfaro
312e36c893 Update requirements and insfra versions 2025-10-17 23:09:40 +02:00
Urtzi Alfaro
7e089b80cf Improve public pages 2025-10-17 18:14:28 +02:00
Urtzi Alfaro
d4060962e4 Improve demo seed 2025-10-17 07:31:14 +02:00
Urtzi Alfaro
dbb48d8e2c Improve the sales import 2025-10-15 21:09:42 +02:00
Urtzi Alfaro
8f9e9a7edc Add role-based filtering and imporve code 2025-10-15 16:12:49 +02:00
Urtzi Alfaro
96ad5c6692 Refactor datetime and timezone utils 2025-10-12 23:16:04 +02:00
Urtzi Alfaro
7556a00db7 Improve the demo feature of the project 2025-10-12 18:47:33 +02:00
Urtzi Alfaro
b420af32c5 REFACTOR production scheduler 2025-10-09 18:01:24 +02:00
Urtzi Alfaro
3c689b4f98 REFACTOR external service and improve websocket training 2025-10-09 14:11:02 +02:00