Cambios en backend:
- Actualizado ClassResponseDTO con campos de tenant y timestamps
- Agregados métodos estáticos en servicio (get_all, get_by_id, create, update, delete)
- Reemplazados endpoints de rutas con inicialización de TenantCRUDRoutes
- Corregida ruta de importación del modelo Company en security.py
- Actualizados nombres de campos en DTO para coincidir con modelo (description_es/en)
- Agregada validación para constraint de foreign key de material_key
- Agregada validación de class_code duplicado en método create
- Agregado TimestampMixin al modelo Class
- Creada migración de Alembic para agregar columnas timestamp a tabla classes
- Corregido orden de parámetros en firma del método update
Cambios en frontend:
- Actualizados componentes de UI para módulo de clases
- Cambiar de heredoc (<<EOF) a formato -c para ejecutar comandos SQL
- Agregar cast explícito 'SHARED'::tenanttype para el campo type del tenant
- Arreglar inserción de company para que se ejecute correctamente
- Arreglar inserción de relación usuario-tenant en table user_tenants
- Mejora en ejecución de comandos PostgreSQL dentro de docker exec
El problema era que los heredocs no interpolaban correctamente las variables
en el contexto de docker exec. Usar -c con sentencias SQL en una línea resuelve
el problema y asegura que los INSERTs se ejecuten correctamente.
- Added a data table for displaying customs brokers with columns for key, name, type, license, RFC, email, phone, city, and actions.
- Created a dialog for adding new customs brokers with a form for inputting necessary details.
- Implemented actions for viewing details and deleting customs brokers with confirmation dialogs.
- Integrated search functionality to find customs brokers by their key.
- Established server-side loading for the customs brokers page to handle authentication and data retrieval.
- Added data table component for displaying clients and providers with infinite scroll functionality.
- Created dropdown actions for each client/provider including copy ID, copy RFC, view details, edit, toggle status, and delete.
- Implemented dialogs for creating, editing, viewing details, and deleting clients/providers.
- Integrated API calls for fetching, creating, editing, deleting, and toggling status of clients/providers.
- Enhanced error handling and loading states for better user experience.
- Updated server-side logic to handle pagination and company selection for client/provider data retrieval.
- Centralized API URL configuration and token management in $lib/server/api.ts.
- Replaced direct token access with a centralized method for retrieving tokens.
- Updated all dashboard reference data routes to use authenticatedFetch for API calls, improving token refresh handling.
- Simplified login route by utilizing centralized token management functions.
- Added a new layout file for the dashboard to pass user and company data to the client.
- Updated SealService to support tenant and company filtering with pagination and enhanced CRUD methods.
- Refactored TrailerService to include tenant and company support, added filtering capabilities, and improved CRUD methods.
- Introduced TenantCRUDRoutes for Trailer and Transporter routes to streamline API endpoint creation and management.
- Enhanced TransporterService with tenant and company filtering, pagination, and improved CRUD operations.
- Added Customs Broker module with DTOs, models, services, and routes for managing customs broker data.
- Implemented CRUD operations for Customs Broker, including personnel and VU management.
- Improved data validation and descriptions in DTOs for better API documentation.
- Rearranged imports in multiple files for consistency and clarity.
- Updated logging middleware to exclude specific paths from logging.
- Enhanced security module by cleaning up token handling and improving tenant validation.
- Added tenant and company scoped mixins for better database model management.
- Implemented generic CRUD routes for tenant-scoped resources.
- Improved error handling and response management in API routes.
- Cleaned up login and logout processes to ensure proper session management.
- Introduced mechanisms to clear local storage and cookies on tenant change.
- Enhanced company store to detect tenant changes and clear data accordingly.
- Added new DTO mixins for currency and value affect flags.
- Enhanced TenantMiddleware to validate tenant information from JWT tokens.
- Added LicenseValidationMiddleware to check tenant licenses before processing requests.
- Updated security utilities to extract tenant information from tokens and validate company access.
- Introduced CompanyStore to manage active company state and handle company switching in the frontend.
- Modified API routes to include company_id in requests for better resource management.
- Improved logging and error handling throughout the middleware and API layers.
- Updated frontend components to reflect changes in company management and selection.
- Added new API route for fetching user's companies with proper authentication handling.
- Updated all route files to replace tenant_id with company_id.
- Introduced validate_company_access function to check user access to the specified company.
- Modified service methods to accept company_id as a parameter.
- Adjusted query parameters in route definitions to include company_id.
- Ensured all CRUD operations in pedimento routes validate access based on company_id.
- Added a script to automate the update process for route files.
- Updated PermissionRuleOct model to include company_id and modified unique constraint.
- Updated Seal model to include company_id and modified unique constraint.
- Added TYPE_CHECKING imports in reference data models for better type hinting.
- Created new models for QClasses and SClasses in the a24 module.
- Enhanced init_first_time.sh script for comprehensive system initialization, including Keycloak and PostgreSQL setup.
- Updated documentation to reflect changes in API endpoints and database relationships.
- Updated GBultoService to use models.Package instead of models.GBulto.
- Refactored Part model to use SQLAlchemy 2.0 style with Mapped and mapped_column.
- Added timestamps (created_at, updated_at, deleted_at) to various pedimento models.
- Improved relationships and foreign key constraints in pedimento models.
- Updated PermissionRuleOct and Seal models to use Mapped and mapped_column.
- Changed DTO configuration from orm_mode to from_attributes for better compatibility.
- Removed obsolete models (models.py and models_ped.py) from the repository.
- Updated `PedimentoDates`, `PedimentoPayments`, `PedimentoTransportMeans`, and `PedimentoValidation` interfaces to include new fields and rename existing ones for consistency.
- Modified forms in Svelte components to reflect the updated interfaces, including new input fields for various dates and payment details.
- Enhanced status handling in the dashboard to accommodate new status options and improve user feedback.
- Implemented token validation on the server-side to ensure secure access to the dashboard.
- Cleaned up login logic to prevent redirection loops when tokens are present but potentially expired.
- Implemented PaymentsTabForm component for managing payment information.
- Implemented TransportTabForm component for managing transport details.
- Implemented ValidationTabForm component for managing validation documents.
- Enhanced the main edit page to include new tabs and handle data saving for each section.
- Added alert components for success and error messages during save operations.
- Updated server-side logic to handle fetching and saving of pedimento data.
- Creación y traducción de módulos:
- gpaisreglaoct -> country_rule_oct
- gpermisoreglaoct -> permission_rule_oct
- gprecintos -> seal
- gtipocambio -> exchange_rate
- gfracroctava -> fraction_rule_octave
- gbultos -> package
- Traducción de nombres de campos, clases y métodos al inglés.
- Renombrados los nombres de las tablas (__tablename__) en los modelos.
- Actualización de las importaciones en el archivo router.py para reflejar los nuevos nombres de módulos.
- Asegurada la consistencia en los nombres de clases, métodos y rutas.
- Agregado el campo tenant_id a los modelos que no lo incluían.
- Added service layer for handling client and provider operations including creation, retrieval, updating, and deletion.
- Introduced DTOs for data transfer and validation.
- Implemented filtering and pagination for client/provider listing.
- Added logging for better traceability of operations.
feat: Create parts management module
- Developed a complete module for managing parts/components including creation, retrieval, updating, and deletion.
- Introduced DTOs for parts with detailed attributes and validation.
- Implemented search and filtering capabilities for parts based on various criteria.
- Added endpoints for regulatory information retrieval and parts statistics.
- Integrated logging for error handling and operational insights.
- Added create-edit-dialog component for creating and editing pedimentos.
- Integrated dialog with data table actions for editing existing pedimentos.
- Implemented infinite scroll functionality in the data table for loading more pedimentos.
- Enhanced server-side loading of pedimentos with authentication checks.
- Added filtering options for pedimentos based on status, client ID, and year.
- Improved error handling and user feedback for actions like creating, editing, and deleting pedimentos.
- Implemented service classes for PedimentoConfigParameters, PedimentoConfigSurcharges, PedimentoConfigUpdateRectification, PedimentoConfigUpdates, PedimentoCustomsOffices, PedimentoDates, PedimentoDecrementables, PedimentoIncrementables, PedimentoIndexes, PedimentoPayments, PedimentoRectificationDestination, PedimentoRectificationOrigin, PedimentoTransportMeans, and PedimentoValidation.
- Each service class includes methods for CRUD operations: create, read, update, and delete.
- Added a main router for the API v1, integrating various modules including authentication, tenants, licenses, and pedimentos.
- Created models for PedimentoValidation with appropriate constraints and relationships.
## Cambios Realizados
### 1. **Modelos**
- Se actualizaron los modelos para incluir el esquema en las tablas:
-
-
-
-
- Ajustes en relaciones y claves foráneas para garantizar consistencia con el esquema .
- Se añadieron anotaciones de tipo y mejoras en la documentación de los modelos.
### 2. **Servicios**
- Implementación de lógica de negocio en para el módulo :
- Creación, actualización, eliminación y búsqueda de partes.
- Métodos para estadísticas y manejo de estados habilitado/deshabilitado.
### 3. **Migraciones**
- Creación de nuevas migraciones de Alembic para las tablas:
-
-
-
-
- Tablas relacionadas con direcciones y programas de clientes/proveedores.
### 4. **Documentación**
- Actualización de :
- Detalles de las nuevas funcionalidades implementadas.
- Endpoints REST API agregados para los módulos.
- Relaciones principales entre tablas.
- Actualización de :
- Cambios realizados en los modelos para usar el esquema .
- Beneficios de la separación de esquemas.
- Próximos pasos para completar la integración.
## Próximos Pasos
1. Verificar las migraciones generadas y aplicarlas en el entorno de desarrollo.
2. Implementar pruebas unitarias para los nuevos servicios y modelos.
---
*Documento generado automáticamente el 5 de noviembre de 2025.*
✨ New Features:
- Company module: Single company management with comprehensive business info
- Client & Provider module: Manages clients/providers with address/program relationships
- GParts module: Parts/components management for SCAII, SCAF, and WINSAAI systems
- GClass module: Class classifications for SCAII and SCAF with tariff information
🔗 Database Relationships:
- GPart ↔ GClass: Composite key relationship (client_key, part_class ↔ class_code)
- GPart → Country: Foreign key to public.countries (country_of_origin)
- GPart → CurrencyType: Foreign key to public.currency_types (currency_key)
- GClass → MaterialType: Foreign key to public.material_types (material_key)
📊 API Endpoints Added:
Company Module (/company):
- POST / - Create company
- GET / - Get single company
Client & Provider Module (/clients-providers):
- POST / - Create client/provider
- GET / - List all with pagination
- GET /clients - List only clients
- GET /providers - List only providers
- GET /search/rfc/{rfc} - Search by RFC
- GET /{client_id} - Get by ID
- PUT /{client_id} - Update client/provider
- DELETE /{client_id} - Delete client/provider
- PATCH /{client_id}/toggle-status - Toggle status
- GET /{client_id}/address - Get address info
- GET /{client_id}/programs - Get programs info
- GET /{client_id}/basic - Get basic info
GParts Module (/parts):
- POST / - Create part
- GET / - List all with pagination and filters
- GET /client/{client_key} - Get parts by client
- GET /search/fraction/{fraction} - Search by tariff fraction
- GET /search/supplier/{supplier} - Search by supplier
- GET /search/country/{country_code} - Search by country
- GET /statistics - Get parts statistics
- GET /{client_key}/{part_number} - Get specific part
- PUT /{client_key}/{part_number} - Update part
- DELETE /{client_key}/{part_number} - Delete part
- PATCH /{client_key}/{part_number}/toggle-status - Toggle status
- GET /{client_key}/{part_number}/basic - Get basic info
- GET /{client_key}/{part_number}/regulatory - Get regulatory info
GClass Module (/classes):
- POST / - Create class
- GET / - List all with pagination and filters
- GET /client/{client_key} - Get classes by client
- GET /search/fraction/{fraction} - Search by tariff fraction
- GET /search/material/{material_key} - Search by material
- GET /search/unit-measure/{unit_of_measure} - Search by unit of measure
- GET /search/physical-review/{physical_review} - Search by physical review status
- GET /statistics - Get class statistics
- GET /{client_key}/{class_code} - Get specific class
- PUT /{client_key}/{class_code} - Update class
- DELETE /{client_key}/{class_code} - Delete class
- GET /{client_key}/{class_code}/basic - Get basic info
- GET /{client_key}/{class_code}/tariff - Get tariff information
🏗️ Architecture:
- Modular design with models, DTOs, services, and routes for each entity
- English field names with composite primary keys where applicable
- Comprehensive CRUD operations with specialized search endpoints
- SQLAlchemy relationships with proper foreign key constraints
- Type-safe DTOs with Pydantic validation
📝 Documentation:
- RELATIONSHIPS.md: Complete documentation of database relationships
- Detailed type hints and comprehensive service methods
- Consistent patterns across all modules for maintainability
- Updated sidebar navigation titles and URLs to use new reference data keys for consistency.
- Added additional items to the general catalogs section in the sidebar.
- Changed the user avatar fallback text from "CN" to "AS" for better representation.
- Added server-side loading logic for states, transport modes, transport types, and valuation methods with pagination support.
- Created Svelte components for displaying and managing states, transport modes, transport types, and valuation methods.
- Implemented infinite scroll functionality for loading more data as the user scrolls.
- Added error handling and user feedback for API interactions.
- Included dialogs for creating and editing entries in each reference data category.
feat(translations): update English and Spanish message files with new keys
refactor(layout): simplify layout component by removing loading state logic
refactor(page.server): adjust authentication flow to return public page for unauthenticated users
refactor(dashboard): create dynamic columns for CodePedimentoRegimen with onSuccess callback
feat(dashboard): implement create, edit, and delete dialogs for CodePedimentoRegimen
feat(dialogs): add reusable dialog components for confirmation and details display
style(alert-dialog): improve styling and structure for alert dialog components
style(dialog): enhance styling and structure for dialog components