### Pyparsing Import and Namespace Setup Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Demonstrates the recommended way to import pyparsing and set up namespaces for common modules like `pyparsing.common` and `pyparsing.unicode`. This ensures consistent access to library features. ```python import pyparsing as pp # For pyparsing.common ppc = pp.common # For pyparsing.unicode ppu = pp.unicode ``` -------------------------------- ### Defining Keyword Constants with Using Each Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Shows a concise way to define multiple keyword constants using `using_each` with a list of keywords, avoiding repetitive individual assignments. ```python import pyparsing as pp # Define multiple keywords efficiently IF, THEN, ELSE = pp.Keyword.using_each(["if", "then", "else"]) # Example usage parser = IF + THEN + ELSE result = parser.parse_string("if then else") print(result) ``` -------------------------------- ### Ensuring Full Input Consumption Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Explains how to use the `parse_all=True` argument with `parse_string` to ensure that the entire input string is consumed by the grammar. ```python import pyparsing as pp parser = pp.Word(pp.alphanums) # This will raise an exception if there's unparsed input result = parser.parse_string("hello world", parse_all=True) ``` -------------------------------- ### Parsing Delimited Lists with Optional Handling Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Demonstrates the use of `pp.DelimitedList` for parsing comma-separated sequences and `pp.Optional` to handle cases where the list might be empty. ```python import pyparsing as pp # Parse a delimited list, optionally empty items = pp.Optional(pp.DelimitedList(pp.Word(pp.alphanums)))('') result_empty = items.parse_string("") print(result_empty) result_data = items.parse_string("apple,banana,cherry") print(result_data) ``` -------------------------------- ### Handling Comments with Ignore Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Demonstrates how to handle comments within the grammar using the `ignore()` method, recommending built-in comment parsers like `pp.cpp_style_comment` and `pp.python_style_comment`. ```python import pyparsing as pp # Define grammar elements content = pp.Word(pp.alphanums) # Ignore C++ style comments parser = content.copy().ignore(pp.cpp_style_comment) result = parser.parse_string("some_data // this is a comment") print(result[0]) # Output: some_data ``` -------------------------------- ### Using Operator Forms for Grammar Elements Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Demonstrates the preference for using operator forms like `+`, `|`, `^`, `~` over explicit pyparsing classes (e.g., `And`, `MatchFirst`, `Or`, `Not`) for improved readability in grammar definitions. ```python import pyparsing as pp # Example using operator forms parser = pp.Word(pp.alphas) + pp.Optional(pp.Word(pp.nums)) | pp.Keyword("special") ``` -------------------------------- ### Using Each for Order-Independent Elements Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Explains the use of `pp.Each()` to define elements that can appear in any order within the grammar. The '&' operator is presented as a more readable alternative. ```python import pyparsing as pp # Using Each operator parser_each = pp.Each([ pp.Keyword("first"), pp.Keyword("second") ]) # Using '&' operator (more readable) parser_amp = pp.Keyword("first") & pp.Keyword("second") result = parser_amp.parse_string("second first") print(result) ``` -------------------------------- ### Organizing Sub-expressions with Group Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Highlights the use of `pp.Group` for organizing related sub-expressions and preserving results names, especially when used within `OneOrMore` or `ZeroOrMore`. ```python import pyparsing as pp # Grouping related elements coordinates = pp.Group( pp.Word(pp.nums)("x") + pp.Word(pp.nums)("y") ) result = coordinates.parse_string("10 20") print(result.x) # Output: 10 print(result.y) # Output: 20 ``` -------------------------------- ### GET /api/customers Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint to list all customers along with their total stock value. ```APIDOC ## GET /api/customers ### Description Endpoints for exploring inventory by customer, obtaining a list of items with their values, and calculating historical averages in specific date ranges. ### Method GET ### Endpoint /api/customers ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "http://localhost:8000/api/customers" ``` ### Response #### Success Response (200) - **customers** (array of objects) - A list of customers and their associated total stock value. - **Cliente** (string) - The name of the customer. - **Valor_Total** (float) - The total stock value for the customer. #### Response Example ```json { "customers": [ {"Cliente": "FORD ESPAÑA", "Valor_Total": 2500000.50}, {"Cliente": "SEAT S.A.", "Valor_Total": 1850000.25} ] } ``` ``` -------------------------------- ### FastAPI Server Configuration (Python) Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/docs/architecture/RPK_NEXUS_ARCHITECTURE.md This snippet illustrates the backend server setup using FastAPI, highlighting its use for routing API data and static files. It also mentions intelligent routing and security practices like 'Zero-Trust'. ```python # backend/server_nexus.py # Utiliza el framework FastAPI por su alto rendimiento y tipado estático (Pydantic). # - Enrutamiento Inteligente: Gestiona tanto la API de datos como el servicio de archivos estáticos. # - Redirecciones Relativas: Implementa lógica para forzar barras al final. # - Seguridad: Sigue el patrón "Zero-Trust" validando cada entrada de datos. ``` -------------------------------- ### Handling Whitespace and Line Endings Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Provides guidance on configuring pyparsing to handle whitespace and significant newlines. It shows how to set default whitespace characters and explicitly define line endings for line-oriented grammars. ```python import pyparsing as pp # Set default whitespace to only spaces and tabs pp.ParserElement.set_default_whitespace_chars(" \t") # Define a suppressor for line endings NL = pp.LineEnd().suppress() ``` -------------------------------- ### Enabling Packrat Parsing for Recursive Grammars Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Shows how to enable packrat parsing immediately after importing pyparsing to optimize performance for grammars with recursive elements, such as those using `Forward()` or `infix_notation()`. ```python import pyparsing as pp # Enable packrat parsing for performance pp.ParserElement.enable_packrat() ``` -------------------------------- ### Applying Parse Actions for Data Conversion Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Illustrates how to use parse actions to convert parsed string data into Python data types. It covers common types, unquoting strings, replacing keywords with Python constants, and using `aslist`/`asdict` for native containers. ```python import pyparsing as pp # Parse integer using pyparsing.common integer_parser = pp.common.integer result_int = integer_parser.parse_string("123") print(type(result_int[0])) # Output: # Unquote and parse double-quoted string dbl_quoted = pp.dbl_quoted_string().set_parse_action(pp.remove_quotes) result_str = dbl_quoted.parse_string('"hello world"') print(result_str[0]) # Output: hello world # Replace keyword 'true' with Python True boolean_true = pp.Keyword("true").set_parse_action(pp.replace_with(True)) result_bool = boolean_true.parse_string("true") print(result_bool[0]) # Output: True # Parse into native Python list list_parser = pp.Group(pp.Word(pp.nums) + pp.Word(pp.alphanums), aslist=True) result_list = list_parser.parse_string("10 abc") print(result_list) # Output: [['10', 'abc']] # Parse into native Python dict dict_parser = pp.Dict(pp.Word(pp.alphas)("key") + pp.Word(pp.nums)("value"), asdict=True) result_dict = dict_parser.parse_string("name 42") print(result_dict) # Output: [{'key': 'name', 'value': '42'}] ``` -------------------------------- ### API: Listar Escenarios Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Realiza una solicitud GET a la ruta /api/scenarios para obtener una lista de todos los escenarios guardados en el sistema. No requiere parámetros de entrada. ```bash curl -X GET "http://localhost:8000/api/scenarios" ``` -------------------------------- ### API: Ejecutar Simulación Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Ejecuta una simulación para un escenario específico utilizando una solicitud GET a /api/simulate/{id}. Permite especificar días laborales y horas de turno como parámetros de consulta. ```bash curl -X GET "http://localhost:8000/api/simulate/1?dias_laborales=240&horas_turno=24" ``` -------------------------------- ### API: Obtener Historial de Cambios Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Recupera el historial de cambios de un escenario particular a través de una solicitud GET a /api/scenarios/{id}/history. ```bash curl -X GET "http://localhost:8000/api/scenarios/1/history" ``` -------------------------------- ### Using Keyword for Reserved Words Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Recommends using `pp.Keyword` over `pp.Literal` for matching reserved words to prevent partial matches. `pp.CaselessKeyword` is available for case-insensitive matching. ```python import pyparsing as pp # Using Keyword to match reserved words precisely for_keyword = pp.Keyword("for") # Using CaselessKeyword for case-insensitive matching if_keyword = pp.CaselessKeyword("if") ``` -------------------------------- ### Choosing Appropriate Parsing Methods Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Compares and contrasts the different parsing methods available in pyparsing: `parse_string` for full parsing, `search_string` for finding matches anywhere, `scan_string` for yielding all matches with positions, and `transform_string` for batch transformations. ```python import pyparsing as pp parser = pp.Word("abc") text = "abc xyz abc" # parse_string: Parses from the start, requires parse_all=True for full consumption result_parse = parser.parse_string(text, parse_all=True) print(f"parse_string: {result_parse}") # search_string: Searches anywhere in the text result_search = parser.search_string(text) print(f"search_string: {list(result_search)}") # scan_string: Yields all matches with positions result_scan = parser.scan_string(text) print(f"scan_string: {list(result_scan)}") # transform_string: Batch transforms or conversions def upper_transform(s): return s[0].upper() transformed_text = parser.transform_string(text, upper_transform) print(f"transform_string: {transformed_text}") ``` -------------------------------- ### Defining Recursive Grammar Elements with Forward Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Illustrates the use of `pp.Forward()` to define placeholders for recursive grammar elements, which are later assigned using the `<<=` operator. Assigning meaningful names with `set_name()` is crucial for error reporting. ```python import pyparsing as pp # Define a forward declaration for a recursive element recursive_element = pp.Forward().set_name("recursive_element") # Later, assign the actual grammar to the forward recursive_element <<= pp.Word(pp.alphanums) | pp.Group(recursive_element + recursive_element) ``` -------------------------------- ### Creating Masked Arrays with Old and New NumPy Versions Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/numpy/ma/README.rst Demonstrates the creation of masked arrays using both the older numpy.core.ma and the newer maskedarray packages. It shows how the representation and comparison of these arrays differ, particularly in how masked values are displayed and how masks are handled. ```python >>> import numpy.core.ma as old_ma >>> import maskedarray as new_ma >>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0]) >>> x array(data = [ 1 2 999999 4 5], mask = [False False True False False], fill_value=999999) >>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0]) >>> y array(data = [1 2 -- 4 5], mask = [False False True False False], fill_value=999999) ``` -------------------------------- ### Comparing Masked Arrays from Old and New NumPy Versions Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/numpy/ma/README.rst Illustrates the comparison between masked arrays created with the old numpy.core.ma and the new maskedarray packages. It highlights how the equality comparison results in a masked array and how the masks themselves are extracted and compared. ```python >>> x==y array(data = [True True True True True], mask = [False False True False False], fill_value=?) >>> old_ma.getmask(x) == new_ma.getmask(x) array([True, True, True, True, True]) >>> old_ma.getmask(y) == new_ma.getmask(y) array([True, True, False, True, True]) >>> old_ma.getmask(y) False ``` -------------------------------- ### GET /api/summary Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Unified endpoint that returns KPIs, temporal evolution, and rankings according to the requesting module. It automatically detects if the request comes from the stock or times module based on the referer header. ```APIDOC ## GET /api/summary ### Description Unified endpoint that returns KPIs, temporal evolution, and rankings according to the requesting module. It automatically detects if the request comes from the stock or times module based on the referer header. ### Method GET ### Endpoint /api/summary ### Parameters #### Query Parameters - **fecha_inicio** (string) - Optional - The start date for the data range (YYYY-MM-DD). - **fecha_fin** (string) - Optional - The end date for the data range (YYYY-MM-DD). #### Request Body None ### Request Example (Load Times) ```bash curl -X GET "http://localhost:8000/api/summary?fecha_inicio=2026-01-01&fecha_fin=2026-02-18" ``` ### Response (Load Times) #### Success Response (200) - **kpis** (object) - Key performance indicators for load times. - **total_carga** (float) - Total load. - **media_carga** (float) - Average load. - **num_centros** (integer) - Number of work centers. - **num_dias** (integer) - Number of days in the period. - **evolucion_total** (object) - Temporal evolution of total load. - **fechas** (array of strings) - Dates in the period. - **cargas** (array of floats) - Load values corresponding to the dates. - **evolucion_centros** (object) - Temporal evolution of load per work center. - **[centro_id]** (object) - Data for a specific work center. - **fechas** (array of strings) - Dates. - **cargas** (array of floats) - Load values. - **rankings** (array of objects) - Rankings of work centers. - **Centro** (string) - Work center identifier. - **Carga_Total** (float) - Total load for the center. - **Media_Diaria** (float) - Daily average load for the center. - **ultima_fecha** (string) - The last date for which data is available. #### Response Example (Load Times) ```json { "kpis": { "total_carga": 45620.5, "media_carga": 1520.68, "num_centros": 45, "num_dias": 30 }, "evolucion_total": { "fechas": ["2026-01-01", "2026-01-02", "..."], "cargas": [1450.2, 1523.8, "..."] }, "evolucion_centros": { "782": {"fechas": ["..."], "cargas": ["..."]}, "640": {"fechas": ["..."], "cargas": ["..."]} }, "rankings": [ {"Centro": "782", "Carga_Total": 4520.5, "Media_Diaria": 150.68}, {"Centro": "640", "Carga_Total": 3890.2, "Media_Diaria": 129.67} ], "ultima_fecha": "2026-02-18" } ``` ### Response (Stock) #### Success Response (200) - **kpis** (object) - Key performance indicators for stock. - **evolucion_total** (object) - Temporal evolution of total stock. - **top_customers** (array of objects) - Top customers by stock value. - **top_items** (array of objects) - Top items by stock value. #### Response Example (Stock) ```json { "kpis": { ... }, "evolucion_total": { ... }, "top_customers": [ ... ], "top_items": [ ... ] } ``` ``` -------------------------------- ### Get Work Center Article Breakdown by Month (REST API) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Provides a detailed breakdown of articles processed in a specific work center for a given month. The output includes article details, associated production orders, hours, days, and percentage contribution. ```bash curl -X GET "http://localhost:8000/api/centro/782/articulos/mes/2026-02" ``` -------------------------------- ### Get Pending Sales Order Articles (REST API) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Fetches a list of articles with pending sales orders for a specific date. The response includes article details, customer reference, quantity, and amount. ```bash curl -X GET "http://localhost:8000/api/pedidos/articulos?fecha=2026-02-18" ``` -------------------------------- ### Get Base Simulation (REST API) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Retrieves the base simulation results for production capacity without any modifications. It includes detailed article-level data and a summary of center-level metrics, based on specified working days and shift hours. ```bash curl -X GET "http://localhost:8000/api/simulate/base?dias_laborales=238&horas_turno=16" ``` -------------------------------- ### API: Previsualizar Simulación Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Realiza una solicitud POST a /api/simulate/preview para obtener una vista previa de una simulación sin guardarla. Requiere un cuerpo JSON con detalles de configuración y posibles anulaciones. ```bash curl -X POST "http://localhost:8000/api/simulate/preview" \ -H "Content-Type: application/json" \ -d '{ "dias_laborales": 240, "horas_turno": 16, "center_configs": {"782": {"shifts": 24}}, "overrides": [ {"articulo": "123456", "centro": "782", "oee_override": 0.92} ] }' ``` -------------------------------- ### API: Actualizar Escenario Completo Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Actualiza un escenario existente de forma completa mediante una solicitud PUT a /api/scenarios/{id}/full. El cuerpo de la solicitud debe contener todos los campos del escenario a actualizar. ```bash curl -X PUT "http://localhost:8000/api/scenarios/1/full" \ -H "Content-Type: application/json" \ -d '{ "name": "Escenario Q3 2026 - Rev2", "description": "Revisión con nuevos datos de demanda", "dias_laborales": 242, "horas_turno_global": 16, "center_configs": {}, "overrides": [] }' ``` -------------------------------- ### Resumen de Tiempos de Carga API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint unificado que retorna KPIs, evolución temporal y rankings para el módulo de tiempos de carga. Requiere filtros de fecha y detecta automáticamente el módulo solicitante por el header 'referer'. ```bash # Resumen de Tiempos de Carga (con filtros de fecha) curl -X GET "http://localhost:8000/api/summary?fecha_inicio=2026-01-01&fecha_fin=2026-02-18" # Respuesta esperada (Tiempos): { "kpis": { "total_carga": 45620.5, "media_carga": 1520.68, "num_centros": 45, "num_dias": 30 }, "evolucion_total": { "fechas": ["2026-01-01", "2026-01-02", "..."], "cargas": [1450.2, 1523.8, "..."] }, "evolucion_centros": { "782": {"fechas": ["..."], "cargas": ["..."]}, "640": {"fechas": ["..."], "cargas": ["..."]} }, "rankings": [ {"Centro": "782", "Carga_Total": 4520.5, "Media_Diaria": 150.68}, {"Centro": "640", "Carga_Total": 3890.2, "Media_Diaria": 129.67} ], "ultima_fecha": "2026-02-18" } # Resumen de Stock (llamado desde módulo /mod/stock) # Respuesta incluye: kpis, evolucion_total, top_customers, top_items ``` -------------------------------- ### Modelos SQLAlchemy: Inicialización de Base de Datos Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Inicializa las tablas necesarias para el sistema de escenarios de simulación utilizando la función init_sim_db() y crea una sesión de base de datos con SessionLocal(). ```python from backend.db.models_sim import init_sim_db, SessionLocal # Inicializar tablas del simulador init_sim_db() # Crear sesión de base de datos db = SessionLocal() ``` -------------------------------- ### Suppressing Punctuation Tokens Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Shows a pattern for suppressing punctuation tokens to keep parse results clean, using `pp.Suppress.using_each()` for common punctuation characters. ```python import pyparsing as pp # Suppress common punctuation LBRACK, RBRACK, LBRACE, RBRACE, COLON = pp.Suppress.using_each("[]{}:") # Example usage parser = LBRACK + pp.Word(pp.alphanums) + RBRACK result = parser.parse_string("[data]") print(result) ``` -------------------------------- ### Frontend JavaScript: Inicialización y Comunicación con API REST Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Este snippet muestra la configuración base de la API, el estado global de la aplicación, y funciones asíncronas para inicializar el sistema, renderizar el dashboard, mostrar desglose de centros, y actualizar gráficos de comparación. Utiliza `fetch` para interactuar con endpoints REST y `Promise.all` para peticiones concurrentes. ```javascript // Configuración base de la API const API_BASE = '/api'; // Estado global de la aplicación const state = { currentTab: 'dashboard', fechas: [], centros: [], selectedCentros: [], charts: {}, filters: { from: '', to: '' } }; // Inicialización del sistema async function initializeSystem() { const [fechasRes, centrosRes, statusRes] = await Promise.all([ fetch(`${API_BASE}/fechas`), fetch(`${API_BASE}/centros`), fetch(`${API_BASE}/status`) ]); const fechasData = await fechasRes.json(); const centrosData = await centrosRes.json(); state.fechas = fechasData.fechas || []; state.centros = centrosData.centros || []; } // Renderizar dashboard principal async function renderDashboard() { const params = new URLSearchParams({ fecha_inicio: state.filters.from, fecha_fin: state.filters.to }); const res = await fetch(`${API_BASE}/summary?${params}`); const data = await res.json(); // Actualizar KPIs document.getElementById('kpi-total-carga').innerText = data.kpis.total_carga.toLocaleString(); document.getElementById('kpi-media-carga').innerText = data.kpis.media_carga.toLocaleString(); document.getElementById('kpi-centros').innerText = data.kpis.num_centros; } // Mostrar desglose (drilldown) de un centro async function showDrilldown(centro) { const mes = state.filters.to.substring(0, 7); // YYYY-MM const res = await fetch(`${API_BASE}/centro/${centro}/articulos/mes/${mes}`); const data = await res.json(); // Renderizar tabla de artículos con horas, días y porcentaje de carga data.articulos.forEach(art => { console.log(`${art.articulo}: ${art.horas}h (${art.porcentaje}%)`); }); } // Comparar evolución de múltiples centros async function updateComparisonChart() { const params = new URLSearchParams({ fecha_inicio: state.filters.from, fecha_fin: state.filters.to }); const centrosIds = state.selectedCentros.join(','); const res = await fetch(`${API_BASE}/centro/${centrosIds}?${params}`); const data = await res.json(); // data.fechas: Array de fechas // data.centros: { "782": { cargas: [...] }, "640": { cargas: [...] } } } ``` -------------------------------- ### Listar Clientes con Valor de Stock API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint para explorar el inventario por cliente. Retorna un listado de todos los clientes junto con el valor total de stock asociado a cada uno de ellos. ```bash # Listar todos los clientes con su valor de stock curl -X GET "http://localhost:8000/api/customers" # Respuesta: { "customers": [ {"Cliente": "FORD ESPAÑA", "Valor_Total": 2500000.50}, {"Cliente": "SEAT S.A.", "Valor_Total": 1850000.25} ] } ``` -------------------------------- ### GET /api/customer/{cliente_nombre}/items Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint to retrieve a specific customer's items, including their values within a specified date range. ```APIDOC ## GET /api/customer/{cliente_nombre}/items ### Description Endpoint to retrieve a specific customer's items, including their values within a specified date range. ### Method GET ### Endpoint /api/customer/{cliente_nombre}/items ### Parameters #### Path Parameters - **cliente_nombre** (string) - Required - The name of the customer. URL-encoded if it contains spaces or special characters. #### Query Parameters - **fecha_inicio** (string) - Optional - The start date for filtering items (YYYY-MM-DD). - **fecha_fin** (string) - Optional - The end date for filtering items (YYYY-MM-DD). #### Request Body None ### Request Example ```bash curl -X GET "http://localhost:8000/api/customer/FORD%20ESPAÑA/items?fecha_inicio=2026-01-01&fecha_fin=2026-02-18" ``` ### Response #### Success Response (200) - **items** (array of objects) - A list of items associated with the customer. - **Articulo** (string) - The item identifier. - **Cantidad** (integer) - The quantity of the item. - **Valor_Unitario** (float) - The unit value of the item. - **Valor_Total** (float) - The total value of the item (Cantidad * Valor_Unitario). - **Fecha** (string) - The date the item data pertains to. #### Response Example ```json { "items": [ {"Articulo": "ITEM001", "Cantidad": 100, "Valor_Unitario": 25.00, "Valor_Total": 2500.00, "Fecha": "2026-01-15"}, {"Articulo": "ITEM002", "Cantidad": 50, "Valor_Unitario": 37.00, "Valor_Total": 1850.00, "Fecha": "2026-01-15"} ] } ``` ``` -------------------------------- ### GET /api/v1/status Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint to verify the connectivity and general status of the NEXUS database. It returns information about the connection and record counts in the main tables. ```APIDOC ## GET /api/v1/status ### Description Endpoint to verify the connectivity and general status of the NEXUS database. Returns information about the connection and record counts in the main tables. ### Method GET ### Endpoint /api/v1/status ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "http://localhost:8000/api/v1/status" ``` ### Response #### Success Response (200) - **status** (string) - The current status of the system (e.g., "online"). - **db_path** (string) - The absolute path to the SQLite database file. - **records** (object) - An object containing the count of records in key tables. - **stock** (integer) - Number of records in the stock table. - **tiempos** (integer) - Number of records in the times/load table. - **database** (string) - The name of the database file. #### Response Example ```json { "status": "online", "db_path": "/path/to/rpk_industrial.db", "records": { "stock": 15420, "tiempos": 8750 }, "database": "rpk_industrial.db" } ``` ``` -------------------------------- ### Consultar Datos con Lenguaje Natural API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Permite realizar consultas en lenguaje natural sobre los datos de producción. Utiliza un motor de traducción a SQL para interpretar preguntas sobre stock, saturación y carga de trabajo. Soporta diversas consultas predefinidas. ```bash # Consultar datos mediante lenguaje natural curl -X POST "http://localhost:8000/api/v1/chat" \ -H "Content-Type: application/json" \ -d '{"text": "¿Cuál es el stock total?"}' # Respuesta esperada: { "response": "He consultado la base de datos NEXUS.\n\nLos datos que he encontrado son:\n- **Total_Stock**: 2500000\n- **Valor_Total**: 15750000.50" } # Otras consultas soportadas: curl -X POST "http://localhost:8000/api/v1/chat" \ -H "Content-Type: application/json" \ -d '{"text": "stock por cliente"}' curl -X POST "http://localhost:8000/api/v1/chat" \ -H "Content-Type: application/json" \ -d '{"text": "saturacion critica"}' curl -X POST "http://localhost:8000/api/v1/chat" \ -H "Content-Type: application/json" \ -d '{"text": "top 10 articulos"}' ``` -------------------------------- ### Configure Matplotlib to Use Maskedarray Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/numpy/ma/README.rst Demonstrates how to configure Matplotlib to use the external maskedarray module instead of numpy.ma. This can be done by modifying the matplotlibrc file or using a command-line option. ```text # In matplotlibrc file: #maskedarray : False # True to use external maskedarray module # instead of numpy.ma; this is a temporary # # setting for testing maskedarray. # Command-line option: # python simple_plot.py --maskedarray ``` -------------------------------- ### Grouping Sub-expressions with Results Names Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Details the requirement to use `pp.Group` when adding a results name to an expression containing sub-expressions that also have results names. This preserves the results names of the nested elements. ```python import pyparsing as pp # Grouping is necessary when sub-expressions have results names address = pp.Group( pp.Word(pp.alphanums)("street") + pp.Word(pp.alphanums)("city") )("location") result = address.parse_string("123 Main Anytown") print(result.location[0].street) # Output: 123 print(result.location[0].city) # Output: Main ``` -------------------------------- ### Obtener Artículos de un Cliente Específico API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint para explorar el inventario por cliente. Permite obtener el listado de artículos para un cliente específico dentro de un rango de fechas determinado. ```bash # Obtener artículos de un cliente específico curl -X GET "http://localhost:8000/api/customer/FORD%20ESPAÑA/items?fecha_inicio=2026-01-01&fecha_fin=2026-02-18" ``` -------------------------------- ### Apply Date Filters Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/frontend/modules/stock/index.html Applies date filters to the data by calling the loadData function with start and end dates obtained from input elements with IDs 'date-start' and 'date-end'. ```javascript function applyFilters() { loadData(document.getElementById('date-start').value, document.getElementById('date-end').value); } ``` -------------------------------- ### Fetch and Update Ranking Section (JavaScript) Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/frontend/modules/stock/index.html Fetches customer data from the API based on selected start and end dates and then updates the ranking table. This function is asynchronous. ```javascript async function updateRankingSection() { const start = document.getElementById('date-ranking-start').value; const end = document.getElementById('date-ranking-end').value; const res = await fetch(`/api/customers?fecha_inicio=${start}&fecha_fin=${end}`); const data = await res.json(); updateRankingTable(data.customers); } ``` -------------------------------- ### Modelos SQLAlchemy: Creación de Escenario Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Crea un nuevo escenario de simulación programáticamente utilizando los modelos SQLAlchemy definidos. Permite especificar detalles como nombre, descripción, días laborales, horas de turno y configuraciones de centro. ```python from backend.db.models_sim import Scenario, SessionLocal db = SessionLocal() # Crear un nuevo escenario programáticamente nuevo_escenario = Scenario( name="Plan Expansión 2027", description="Evaluación de nueva línea de producción", dias_laborales=245, horas_turno_global=24, center_configs_json='{"782": {"shifts": 24, "personnel_ratio": 1.5}}' ) db.add(nuevo_escenario) db.commit() ``` -------------------------------- ### GET /api/v1/hub_stats Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Endpoint that provides the main KPIs for the central dashboard: total stock, average saturation of work centers, and theoretical coverage days calculated through data cross-analysis. ```APIDOC ## GET /api/v1/hub_stats ### Description Endpoint that provides the main KPIs for the central dashboard: total stock, average saturation of work centers, and theoretical coverage days calculated through data cross-analysis. ### Method GET ### Endpoint /api/v1/hub_stats ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "http://localhost:8000/api/v1/hub_stats" ``` ### Response #### Success Response (200) - **stock** (object) - Information about the total stock. - **total** (integer) - The total value or quantity of stock. - **items** (integer) - The number of distinct stock items. - **saturation** (float) - The average saturation percentage of work centers. - **cobertura** (float) - The theoretical coverage in days. #### Response Example ```json { "stock": { "total": 2500000, "items": 1847 }, "saturation": 74.5, "cobertura": 12.4 } ``` ``` -------------------------------- ### Get TT Table Class by Tag Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/fontTools/ttLib/tables/table_API_readme.txt Demonstrates how to obtain the converter class for a given TT table tag using `ttLib.getTableClass`. This function is useful for instantiating the correct table converter class. ```python from fontTools import ttLib print(ttLib.getTableClass('glyf')) ``` -------------------------------- ### Obtener Estadísticas Principales del Hub API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Proporciona los KPIs principales para el dashboard central, incluyendo stock total, saturación media de centros de trabajo y días de cobertura teórica. Estos datos se calculan mediante análisis cruzado de la información disponible. ```bash # Obtener estadísticas principales del Hub curl -X GET "http://localhost:8000/api/v1/hub_stats" # Respuesta esperada: { "stock": { "total": 2500000, "items": 1847 }, "saturation": 74.5, "cobertura": 12.4 } ``` -------------------------------- ### Project Structure Overview (Text) Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/docs/architecture/RPK_NEXUS_ARCHITECTURE.md This snippet displays the physical layout of the RPK NEXUS project, following the RPK Agentic Standard. It outlines the main directories and their purposes, including agent rules, Python runtime, backend logic, frontend modules, scripts, and documentation. ```text Plan Maestro RPK NEXUS/ ├── .agent/ # 🤖 Reglas y workflows del Agente AI ├── _SISTEMA/ # 🚀 Entorno Python Portable (runtime_python) ├── backend/ # 🧠 Lógica de Negocio y Servidor │ ├── core/ # Motores de simulación y analítica │ ├── db/ # Capa de datos (SQLite + Esquemas) │ ├── api/ # Endpoints especializados (Futuros) │ └── server_nexus.py # Servidor Central FastAPI (El Corazón) ├── frontend/ # 🎨 Interfaz de Usuario │ ├── modules/ # Micro-Frontends (Dashboard Paneles) │ │ ├── pedidos/ # Panel de Gestión de Pedidos de Venta │ │ ├── simulador/ # Simulador de Producción / Escenarios │ │ ├── stock/ # Dashboard de Existencias y Valoración │ │ └── tiempos/ # Planificación de Cargas y Saturation │ ├── ui/ # Portal Hub Central (Portal de Usuario) │ └── assets/ # Recursos globales (Logos, CSS base) ├── scripts/ # ⚙️ Utilidades de Operaciones (Ops) │ ├── qa_scanner.py # Auditoría de sintaxis y patrones RPK │ ├── ops_sync.py # Sincronización Golden con GitHub │ └── sync_nexus.py # Motor ETL de ingesta diaria ├── docs/ # 📄 Documentación y Logs │ ├── architecture/ # [NUEVO] Este documento y diagramas │ └── logs/ # Historial de cambios y actualizaciones ├── INICIAR_NEXUS.bat # ⚡ Lanzador Maestro Único └── README.md # Guía rápida del proyecto ``` -------------------------------- ### Masked Array Division - Default Behavior Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/numpy/ma/README.rst Illustrates the default behavior of masked array division in NumPy, where input arrays are filled, the operation is performed, and then the mask is set for the result. This can lead to divisions by zero. ```python import numpy import maskedarray as ma from numpy import logical_or x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float_) y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float_) d1 = x.filled(0) # d1 = array([0., 2., 3., 4.]) d2 = y.filled(1) # array([-1., 0., 1., 1.]) m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m = array([True,False,False,True]) dm = ma.divide.domain(d1,d2) # array([False, True, False, False]) result = (d1/d2).view(ma.MaskedArray) # masked_array([-0. inf, 3., 4.]) result._mask = logical_or(m, dm) ``` -------------------------------- ### Consultor Lenguaje Natural: Traducción a SQL Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Traduce preguntas formuladas en lenguaje natural a consultas SQL utilizando la función traducir_a_sql(). Está diseñado para una futura integración con Google Gemini API. ```python from backend.db.consultor import traducir_a_sql, ejecutar_consulta # Traducir pregunta a SQL sql = traducir_a_sql("¿Cuál es el stock total?") print(sql) # Salida: "SELECT SUM(cantidad) as Total_Stock, SUM(valor_total) as Valor_Total FROM stock_snapshot" ``` -------------------------------- ### Verificar Estado del Sistema API (Bash) Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Verifica la conectividad y el estado general de la base de datos NEXUS. Retorna información sobre la conexión, la ruta de la base de datos y el conteo de registros en tablas clave. ```bash # Verificar estado del sistema curl -X GET "http://localhost:8000/api/v1/status" # Respuesta esperada: { "status": "online", "db_path": "/path/to/rpk_industrial.db", "records": { "stock": 15420, "tiempos": 8750 }, "database": "rpk_industrial.db" } ``` -------------------------------- ### Assigning Results Names for Parsed Data Access Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/pyparsing/ai/best_practices.md Explains how to use results names for accessing parsed data fields, enabling attribute-style access on `ParseResults`. Results names should be valid Python identifiers and replace numeric indexing. ```python import pyparsing as pp # Assigning results names using call format full_name = pp.Word(pp.alphas)("first_name") + pp.Word(pp.alphas)("last_name") # Example usage result = full_name.parse_string("John Doe") print(result.first_name) # Output: John print(result.last_name) # Output: Doe ``` -------------------------------- ### Initialize Application Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/frontend/modules/stock/index.html Calls the initialization function for the application. ```javascript init(); ``` -------------------------------- ### Masked Array Division - Without Filling Arrays Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/numpy/ma/README.rst Demonstrates masked array division without filling the arrays first. This method is faster but may result in floating-point exceptions like 'inf' if divisions by zero occur. ```python import numpy import maskedarray as ma from numpy import logical_or x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float_) y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float_) d1 = x._data # d1 = array([1., 2., 3., 4.]) d2 = y._data # array([-1., 0., 1., 2.]) dm = ma.divide.domain(d1,d2) # array([False, True, False, False]) m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m = array([True,False,False,True]) result = (d1/d2).view(ma.MaskedArray) # masked_array([-1. inf, 3., 2.]) result._mask = logical_or(m, dm) ``` -------------------------------- ### Consultor Lenguaje Natural: Ejecución de Consultas Source: https://context7.com/keepertrading90/rpk-nexus-plan-maestro/llms.txt Ejecuta una consulta SQL generada por traducir_a_sql() y devuelve los resultados y los nombres de las columnas. La función ejecutar_consulta() permite interactuar con la base de datos. ```python from backend.db.consultor import ejecutar_consulta # Ejecutar consulta y obtener resultados resultados, columnas = ejecutar_consulta(sql) print(columnas) # ['Total_Stock', 'Valor_Total'] print(resultados) # [(2500000.0, 15750000.50)] ``` -------------------------------- ### Get TT Table Module by Tag Source: https://github.com/keepertrading90/rpk-nexus-plan-maestro/blob/main/_SISTEMA/runtime_python/Lib/site-packages/fontTools/ttLib/tables/table_API_readme.txt Shows how to retrieve the Python module corresponding to a specific TT table tag using `ttLib.getTableModule`. This function helps in accessing the converter module dynamically based on the table tag. ```python from fontTools import ttLib print(ttLib.getTableModule('glyf')) ```