Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/JoseOlivares19/Proyecto-PC3-JavaScript-Avanzado/llms.txt

Use this file to discover all available pages before exploring further.

SmartStock360 is organized as a classic three-tier web application where each tier has a single, well-scoped responsibility: the React frontend handles all user interaction and visualization, the Spring Boot middleware owns the REST contract, business data persistence, and cross-tier orchestration, and the Python FastAPI service owns all machine-learning inference. No tier reaches past its immediate neighbor — React never calls Python directly, and Python never touches the MySQL database. This separation makes each tier independently deployable, testable, and replaceable.

Architecture Diagram

The diagram below shows the full call path from a user action in the browser to an AI prediction and back. Port assignments, protocol boundaries, and the five model endpoints are all reflected here.
┌─────────────────────────────────────────────────────────────────────┐
│                  TIER 1 · React Frontend · port 5173                │
│                                                                     │
│   src/services/api.ts                                               │
│   ├── obtenerProductos()  →  GET  /api/productos                    │
│   └── predecirDemanda()   →  POST /api/productos/predict            │
└──────────────────────────────┬──────────────────────────────────────┘
                               │ HTTP (Axios)

┌─────────────────────────────────────────────────────────────────────┐
│              TIER 2 · Spring Boot Middleware · port 8080            │
│                                                                     │
│   REST API  (@CrossOrigin(origins = "*"))                           │
│   ├── GET  /api/productos          ←── JPA → MySQL (smartstock)     │
│   └── POST /api/productos/predict  ──► proxy to Python :8001        │
└──────────────────────────────┬──────────────────────────────────────┘
                               │ HTTP (RestTemplate)

┌─────────────────────────────────────────────────────────────────────┐
│              TIER 3 · Python FastAPI AI Service · port 8001         │
│                                                                     │
│   Prediction endpoints (all POST)                                   │
│   ├── /predict/smart-stock      → SmartStock360 demand model        │
│   ├── /predict/fraud-shield     → FraudShield transaction model     │
│   ├── /predict/cyber-sentinel   → CyberSentinel security model      │
│   ├── /predict/utp-risk         → UTP Risk AI academic model        │
│   └── /predict/talent-match     → TalentMatch AI profile model      │
│                                                                     │
│   Support endpoints                                                 │
│   ├── GET /health               → status + list of loaded models    │
│   ├── GET /metadata             → features + labels per model       │
│   └── GET /docs                 → Swagger UI (OpenAPI 3.x)          │
│                                                                     │
│   All five RandomForestClassifier models trained in-memory          │
│   at startup (n_estimators=180, max_depth=7)                        │
└─────────────────────────────────────────────────────────────────────┘


                    MySQL · database: smartstock
                    (product catalog, persisted via JPA)

Tier 1: React Frontend

The frontend is a Vite-bundled React 19 single-page application written in TypeScript. It runs on port 5173 (Vite’s default dev server) and has no direct connection to either the MySQL database or the Python AI service — all communication is mediated by Spring Boot. The entire API surface consumed by the frontend is defined in src/services/api.ts:
import axios from 'axios';

const API_URL = 'https://swifttask.tech/universidad/api/productos';

export const predecirDemanda = async (datosProducto: any) => {
    const response = await axios.post(`${API_URL}/predict`, datosProducto);
    return response.data;
};

export const obtenerProductos = async () => {
    const response = await axios.get(API_URL);
    return response.data;
};
  • obtenerProductos() — issues GET /api/productos to retrieve the product catalog from MySQL via Spring Boot.
  • predecirDemanda(datosProducto) — issues POST /api/productos/predict with a product payload; Spring Boot proxies this to the Python AI service and returns the prediction.
The API_URL in api.ts points to the production deployment at https://swifttask.tech/universidad/api/productos. For local development, change this value to http://localhost:8080/api/productos to route requests to your local Spring Boot instance.
Key frontend dependencies (from package.json):
PackageVersionRole
react^19.2.7UI framework
react-dom^19.2.7DOM renderer
axios^1.18.1HTTP client
vite^8.1.1Dev server & bundler
typescript~6.0.2Type safety

Tier 2: Spring Boot Middleware

Spring Boot acts as the sole gateway between the browser and all back-end resources. It runs on port 8080, exposes the REST API that the React frontend consumes, persists and retrieves product data through JPA, and proxies AI prediction requests to the Python service. Maven coordinates (pom.xml):
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.0</version>
</parent>
<properties>
    <java.version>21</java.version>
</properties>
Core dependencies:
DependencyRole
spring-boot-starter-data-jpaORM and repository abstraction over MySQL
spring-boot-starter-webmvcREST controllers and HTTP layer
mysql-connector-jJDBC driver for MySQL
lombokBoilerplate reduction for entity and DTO classes
Database configuration (application.properties):
spring.datasource.url=jdbc:mysql://localhost:3306/smartstock
spring.datasource.username=root
spring.datasource.password=<your-password>
spring.jpa.hibernate.ddl-auto=update
With ddl-auto=update, Hibernate automatically creates or alters tables on startup to match the current JPA entity definitions — no manual SQL schema migration is required for local development. REST endpoints exposed by Spring Boot:
MethodPathDescription
GET/api/productosReturns the full product catalog from MySQL
POST/api/productos/predictAccepts a product payload, proxies to Python /predict/smart-stock, returns the AI prediction
The ProductoController is annotated with @CrossOrigin(origins = "*"), allowing requests from any origin — including the React dev server on port 5173 and the production frontend deployment. The proxy target for prediction requests is http://127.0.0.1:8001/predict/smart-stock — the Smart Stock 360 demand classification model running on the Python AI service. Spring Boot uses RestTemplate to forward the request and relay the response.
Spring Boot proxies only to /predict/smart-stock. The other four Python model endpoints (/predict/fraud-shield, /predict/cyber-sentinel, /predict/utp-risk, /predict/talent-match) are available directly on the Python service at port 8001 and are not exposed through the Spring Boot gateway. Spring Boot does not include Swagger — interactive API documentation is provided only by the Python FastAPI service at http://localhost:8001/docs.

Tier 3: Python FastAPI AI Service

The Python service is the intelligence layer of the platform. It runs on port 8001, exposes five prediction endpoints and two support endpoints, and requires no external model registry or file-based model loading. All five classifiers are trained from scratch every time the service starts. Python dependencies (requirements.txt):
fastapi==0.115.0
uvicorn[standard]==0.30.6
scikit-learn==1.5.2
numpy==2.1.1
pydantic==2.9.2

In-Memory Model Training

All five models share the same training pipeline. The train_pack function generates synthetic training data, fits a RandomForestClassifier, and registers the resulting ModelPack in the MODELS dictionary during the FastAPI startup event:
def train_pack(features: List[str], X: np.ndarray, y: np.ndarray) -> ModelPack:
    encoder = LabelEncoder()
    y_enc = encoder.fit_transform(y)
    model = RandomForestClassifier(
        n_estimators=180,
        max_depth=7,
        random_state=42,
        class_weight="balanced_subsample"
    )
    model.fit(X, y_enc)
    return ModelPack(features, list(encoder.classes_), model, encoder)

Prediction Endpoints

All prediction routes accept a POST request with a JSON body validated by a Pydantic model, run the corresponding classifier, and return a structured response:
# Example response shape (all five endpoints return the same envelope)
{
  "caso": "SmartStock360",
  "prediccion": "DEMANDA_ALTA_REABASTECER",
  "confianza": 0.9124,
  "ranking": [
    {"clase": "DEMANDA_ALTA_REABASTECER", "probabilidad": 0.9124},
    {"clase": "DEMANDA_MEDIA_MONITOREAR", "probabilidad": 0.0721},
    {"clase": "DEMANDA_BAJA_OPTIMIZAR",   "probabilidad": 0.0155}
  ],
  "recomendaciones": [
    "Reabastecer en las próximas 48 horas.",
    "Mantener promoción si el margen lo permite.",
    "Mostrar alerta roja en el dashboard."
  ],
  "entrada": { "precio": 120.0, "stock_actual": 30, "ventas_7d": 950, ... }
}
EndpointModel KeyTraining SamplesOutput Classes
POST /predict/smart-stocksmart-stock300DEMANDA_ALTA_REABASTECER, DEMANDA_MEDIA_MONITOREAR, DEMANDA_BAJA_OPTIMIZAR
POST /predict/fraud-shieldfraud-shield320FRAUDE_PROBABLE, REVISION_MANUAL, TRANSACCION_SEGURA
POST /predict/cyber-sentinelcyber-sentinel300CRITICO, ALTO, MEDIO, BAJO
POST /predict/utp-riskutp-risk260RIESGO_ALTO, RIESGO_MEDIO, RIESGO_BAJO
POST /predict/talent-matchtalent-match320FRONTEND_REACT, BACKEND_SPRING, DATA_ANALYST_JUNIOR, FULLSTACK_JUNIOR

Support Endpoints

GET /health
# → {"status": "ok", "modelos_cargados": ["utp-risk", "fraud-shield", "cyber-sentinel", "smart-stock", "talent-match"]}

GET /metadata
# → {key: {"features": [...], "labels": [...]}, ...} for each registered model
Interactive API documentation is served by FastAPI’s built-in Swagger UI at http://localhost:8001/docs — no additional tooling required.

Request Lifecycle: Demand Prediction

The following steps trace the complete path of a single demand prediction request from user gesture to rendered result.
1

User triggers prediction in React

The user views a product in the React dashboard and clicks “Ejecutar Predicción IA”. The predecirDemanda(datosProducto) function in src/services/api.ts fires an Axios POST to /api/productos/predict on the Spring Boot server at port 8080.
2

Spring Boot receives the request

The ProductoController (annotated @CrossOrigin(origins = "*")) accepts the incoming JSON payload and passes it to ProductoService.predecirStock(), which forwards it directly to the Python AI service.
3

Spring Boot proxies to Python FastAPI

ProductoService uses RestTemplate to issue an HTTP POST to http://127.0.0.1:8001/predict/smart-stock, passing the product data as a JSON body. The Python service receives the request and deserializes it into a StockRequest Pydantic model.
4

Random Forest inference

The Python service builds a feature vector from the seven StockRequest fields — precio, stock_actual, ventas_7d, descuento_pct, temporada, dias_sin_reabastecer, rating_producto — and runs RandomForestClassifier.predict() and predict_proba() to obtain the class label, confidence score, and full probability ranking.
5

Structured response is assembled

The Python endpoint constructs the response envelope: caso, prediccion, confianza, ranking, recomendaciones (three actionable strings), and the original entrada for auditability. This JSON is returned to Spring Boot.
6

Spring Boot relays the response to React

Spring Boot returns the Python response body as the HTTP response to the original Axios call. The React component receives the structured JSON and renders the prediction label, confidence percentage, probability ranking, and recommendations list in the dashboard.

Explore Further

Backend (Spring Boot)

JPA entities, REST controllers, proxy configuration, and MySQL schema details.

Frontend (React)

Component structure, Axios service layer, and dashboard UX patterns.

AI Models

Input features, label definitions, recommendation logic, and response schemas for all five models.

Quickstart

Get all three tiers running locally with step-by-step setup instructions.

Build docs developers (and LLMs) love