diff --git a/.env.example b/.env.example index c66ef877..8e04d045 100644 --- a/.env.example +++ b/.env.example @@ -21,14 +21,12 @@ KEYCLOAK_FRONTEND_CLIENT_ID=anexo76-frontend # ----- Backend ----- DEBUG=True ENVIRONMENT=development - CORE_DB_HOST=postgres-a76 CORE_DB_PORT=5432 CORE_DB_NAME=anexo76_core CORE_DB_USER=postgres CORE_DB_PASSWORD=postgres - # ----- Frontend ----- NODE_ENV=development VITE_API_URL=http://localhost:8000/api @@ -36,3 +34,8 @@ INTERNAL_API_URL=http://backend:8000/api VITE_KEYCLOAK_REALM=master VITE_KEYCLOAK_URL=http://localhost:8080 VITE_KEYCLOAK_CLIENT_ID=anexo76-frontend + +# ----- Sitar API ----- +SITAR_API_URL=http://api.sitar.aduanasoft.com +SITAR_API_USER=your_sitar_user +SITAR_API_PASSWORD=your_sitar_password diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml new file mode 100644 index 00000000..760f8edd --- /dev/null +++ b/.gitea/workflows/build.yml @@ -0,0 +1,55 @@ +name: Build Producción & Push a Harbor + +on: + push: + branches: + - main + +jobs: + build: + runs-on: self-hosted + + steps: + - name: Checkout código + uses: actions/checkout@v4 + + - name: Login a Harbor + run: | + echo '${{ secrets.HARBOR_PASSWORD }}' | docker login \ + dev.aduanasoft.com \ + -u '${{ secrets.HARBOR_USERNAME }}' \ + --password-stdin + + # ------------------------ + # Backend + # ------------------------ + - name: Build backend + run: | + docker build \ + -t dev.aduanasoft.com/anexo76/backend:latest \ + -f ./backend/Dockerfile \ + ./backend + + # ------------------------ + # Frontend + # ------------------------ + - name: Build frontend + run: | + docker build \ + --build-arg VITE_API_URL=https://anexo76-dev.aduanasoft.com/api/ \ + --build-arg VITE_KEYCLOAK_URL=https://anexo76-dev.aduanasoft.com/kcauth/ \ + --build-arg INTERNAL_API_URL=http://backend:3467/api/ \ + -t dev.aduanasoft.com/anexo76/frontend:latest \ + -f ./frontend/Dockerfile.prod \ + ./frontend + + # ------------------------ + # Push imágenes + # ------------------------ + - name: Push backend + run: | + docker push dev.aduanasoft.com/anexo76/backend:latest + + - name: Push frontend + run: | + docker push dev.aduanasoft.com/anexo76/frontend:latest diff --git a/backend/alembic/versions/7937209f9718_seed_initial_data.py b/backend/alembic/versions/7937209f9718_seed_initial_data.py index f4e2a5de..6e1e2359 100644 --- a/backend/alembic/versions/7937209f9718_seed_initial_data.py +++ b/backend/alembic/versions/7937209f9718_seed_initial_data.py @@ -69,6 +69,9 @@ from api.v1.modules.a76.general_catalogs.units_of_measure.seed_ame import ( from api.v1.modules.a76.general_catalogs.units_of_measure.seed_adua import ( seed as adua_seed, ) +from api.v1.modules.a76.general_catalogs.tariff_fractions.seed import ( + seed as tariff_fractions_seed, +) from api.v1.modules.core.permissions.seed import ( seed_invoices, seed_user, @@ -462,6 +465,22 @@ def upgrade() -> None: """ ) + # --- SEEDS A76 (Tariff Fractions - Fracciones Arancelarias Mexicanas) --- + values_tariff_fractions = ", ".join( + [ + f"({format_value(code)}, {format_value(fraction)}, {format_value(description)}, " + f"{format_value(nico)}, {format_value(umt)}, {format_value(adv_impo)}, {format_value(adv_expo)})" + for code, fraction, description, nico, umt, adv_impo, adv_expo in tariff_fractions_seed + ] + ) + op.execute( + f""" + INSERT INTO a76.tariff_fractions (code, fraction, description, nico, umt, adv_impo, adv_expo) + VALUES {values_tariff_fractions} + ON CONFLICT (code) DO NOTHING; + """ + ) + def downgrade() -> None: """Downgrade schema.""" diff --git a/backend/api/v1/modules/a76/clients_and_providers/routes.py b/backend/api/v1/modules/a76/clients_and_providers/routes.py index b96c7442..6b31d570 100644 --- a/backend/api/v1/modules/a76/clients_and_providers/routes.py +++ b/backend/api/v1/modules/a76/clients_and_providers/routes.py @@ -49,7 +49,14 @@ async def get_clients_and_providers( ) if type is not None: - query = query.filter(ClientProvider.client_or_provider == type) + # Include 'both' type when filtering by client or provider + from sqlalchemy import or_ + query = query.filter( + or_( + ClientProvider.client_or_provider == type, + ClientProvider.client_or_provider == ClientOrProviderEnum.BOTH + ) + ) if active is not None: query = query.filter(ClientProvider.is_active == active) diff --git a/backend/api/v1/modules/a76/clients_and_providers/service.py b/backend/api/v1/modules/a76/clients_and_providers/service.py index 5a329673..417228ee 100644 --- a/backend/api/v1/modules/a76/clients_and_providers/service.py +++ b/backend/api/v1/modules/a76/clients_and_providers/service.py @@ -9,6 +9,7 @@ from fastapi import HTTPException from sqlalchemy import or_ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, joinedload +from .models import ClientOrProviderEnum from .dto import ( ClientProviderBasicDTO, @@ -56,8 +57,12 @@ class ClientProviderService: ) ) if filters.get("client_or_provider"): + query = query.filter( - ClientProvider.client_or_provider == filters["client_or_provider"] + or_( + ClientProvider.client_or_provider == filters["client_or_provider"], + ClientProvider.client_or_provider == ClientOrProviderEnum.BOTH + ) ) if filters.get("status"): enabled = 1 if filters["status"] == "enabled" else 0 @@ -346,7 +351,10 @@ class ClientProviderService: if client_or_provider: query = query.filter( - ClientProvider.client_or_provider == client_or_provider + or_( + ClientProvider.client_or_provider == client_or_provider, + ClientProvider.client_or_provider == ClientOrProviderEnum.BOTH + ) ) if enabled_only: diff --git a/backend/api/v1/modules/a76/general_catalogs/company/models.py b/backend/api/v1/modules/a76/general_catalogs/company/models.py index 7b6860d8..61ccc8a6 100644 --- a/backend/api/v1/modules/a76/general_catalogs/company/models.py +++ b/backend/api/v1/modules/a76/general_catalogs/company/models.py @@ -1,6 +1,7 @@ """ Modelo principal de Company """ + from typing import Optional, TYPE_CHECKING from sqlalchemy import Integer, String, SmallInteger, ForeignKey, Boolean from sqlalchemy.orm import Mapped, mapped_column, relationship @@ -19,39 +20,37 @@ if TYPE_CHECKING: class Company(Base, TimestampMixin): """Información principal de la empresa""" - + __tablename__ = "company" __table_args__ = {"schema": "a76", "extend_existing": True} - + # Primary key id: Mapped[int] = mapped_column(Integer, primary_key=True) tenant_id: Mapped[int] = mapped_column( - ForeignKey("core.tenants.id"), - nullable=False, - index=True + ForeignKey("core.tenants.id"), nullable=False, index=True ) - + # Información básica name: Mapped[Optional[str]] = mapped_column(String(256)) rfc: Mapped[Optional[str]] = mapped_column(String(30)) curp: Mapped[Optional[str]] = mapped_column(String(19)) main_activity: Mapped[Optional[str]] = mapped_column(String(80)) - + # Programa program: Mapped[Optional[str]] = mapped_column(String(7)) program_number: Mapped[Optional[str]] = mapped_column(String(40)) prosec: Mapped[Optional[int]] = mapped_column(SmallInteger) prosec_authorization: Mapped[Optional[str]] = mapped_column(String(20)) - + # Sectores sector1: Mapped[Optional[str]] = mapped_column(String(150)) sector2: Mapped[Optional[str]] = mapped_column(String(150)) sector3: Mapped[Optional[str]] = mapped_column(String(5)) - + # Identificadores manufacturer_id: Mapped[Optional[str]] = mapped_column(String(25)) broker_company: Mapped[Optional[str]] = mapped_column(String(6)) - + # Responsable responsible: Mapped[Optional[str]] = mapped_column(String(80)) responsible_name: Mapped[Optional[str]] = mapped_column(String(20)) @@ -59,15 +58,15 @@ class Company(Base, TimestampMixin): responsible_mother_last_name: Mapped[Optional[str]] = mapped_column(String(20)) responsible_rfc: Mapped[Optional[str]] = mapped_column(String(30)) position: Mapped[Optional[str]] = mapped_column(String(30)) - + # Configuración básica logo: Mapped[Optional[str]] = mapped_column(String(255)) - has_express_line: Mapped[Optional[str]] = mapped_column(String(2)) + has_express_line: Mapped[Optional[str]] = mapped_column(String(2), default="N") order_format_type: Mapped[Optional[str]] = mapped_column(String(19)) is_service_company: Mapped[Optional[bool]] = mapped_column(Boolean, default=False) client_name: Mapped[Optional[str]] = mapped_column(String(300)) subassembly_mode: Mapped[Optional[str]] = mapped_column(String(7)) - + # Configuraciones técnicas (flags) previous_code: Mapped[Optional[int]] = mapped_column(SmallInteger) active_labels: Mapped[Optional[int]] = mapped_column(SmallInteger) @@ -79,8 +78,9 @@ class Company(Base, TimestampMixin): parts_replacement: Mapped[Optional[int]] = mapped_column(SmallInteger) activate_facmexame: Mapped[Optional[int]] = mapped_column(SmallInteger) part_reference: Mapped[Optional[int]] = mapped_column(SmallInteger) + part_reference: Mapped[Optional[int]] = mapped_column(SmallInteger) international_firm: Mapped[Optional[int]] = mapped_column(SmallInteger) - + # Configuraciones simples ftp_key: Mapped[Optional[str]] = mapped_column(String(10)) sifra_path: Mapped[Optional[str]] = mapped_column(String(255)) @@ -88,59 +88,59 @@ class Company(Base, TimestampMixin): sql_language: Mapped[Optional[str]] = mapped_column(String(19)) balance_operation_mode: Mapped[Optional[str]] = mapped_column(String(50)) inter_db_name: Mapped[Optional[str]] = mapped_column(String(100)) - + # ==================== RELACIONES CON SUBTABLAS ==================== - + addresses: Mapped[list["CompanyAddress"]] = relationship( "CompanyAddress", back_populates="company", cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + certification: Mapped[Optional["CompanyCertification"]] = relationship( "CompanyCertification", back_populates="company", uselist=False, cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + digital_certificates: Mapped[list["CompanyDigitalCertificate"]] = relationship( "CompanyDigitalCertificate", back_populates="company", cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + ventanilla_unica: Mapped[Optional["CompanyVU"]] = relationship( "CompanyVU", back_populates="company", uselist=False, cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + electronic_agent: Mapped[Optional["CompanyElectronicAgent"]] = relationship( "CompanyElectronicAgent", back_populates="company", uselist=False, cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + prevalidator: Mapped[Optional["CompanyPrevalidator"]] = relationship( "CompanyPrevalidator", back_populates="company", uselist=False, cascade="all, delete-orphan", - lazy="selectin" + lazy="selectin", ) - + cfdi: Mapped[Optional["CompanyCFDI"]] = relationship( "CompanyCFDI", back_populates="company", uselist=False, cascade="all, delete-orphan", - lazy="selectin" - ) \ No newline at end of file + lazy="selectin", + ) diff --git a/backend/api/v1/modules/a76/general_catalogs/company/routes.py b/backend/api/v1/modules/a76/general_catalogs/company/routes.py index cc59a1bc..e6d4bc52 100644 --- a/backend/api/v1/modules/a76/general_catalogs/company/routes.py +++ b/backend/api/v1/modules/a76/general_catalogs/company/routes.py @@ -50,7 +50,8 @@ async def create_company( ) service = CompanyService(db) - return service.create_company_manually(data, tenant_id=tenant_id) + new_company = service.create_company_manually(data, tenant_id=tenant_id) + return CompanyResponseDTO.model_validate(service.flatten_company_dto(new_company)) @router.get( @@ -94,7 +95,10 @@ async def list_companies( total_pages = (total + page_size - 1) // page_size return { - "items": [CompanyResponseDTO.model_validate(item) for item in items], + "items": [ + CompanyResponseDTO.model_validate(service.flatten_company_dto(item)) + for item in items + ], "total": total, "page": page, "page_size": page_size, @@ -122,135 +126,12 @@ async def get_my_companies( service = CompanyService(db) companies = service.get_companies_by_tenant(tenant_id) - return [CompanyResponseDTO.model_validate(company) for company in companies] - - -@router.get( - "/status/exists", - response_model=dict, - summary="Check if company exists for tenant", -) -async def check_company_exists( - db: Session = Depends(get_core_db), - current_user: dict = Depends(get_current_user), -): - """Check if a company exists for the current tenant""" - tenant_id = current_user.get("tenant_id") - if not tenant_id: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Tenant ID not found in user data", - ) - - service = CompanyService(db) - exists = service.exists_company(tenant_id) - - return {"exists": exists} - - -@router.get( - "/info/basic/{company_id}", - response_model=dict, - summary="Get basic company info", -) -async def get_basic_info( - company_id: int, - db: Session = Depends(get_core_db), - current_user: dict = Depends(get_current_user), -): - """Get basic information about a company""" - tenant_id = current_user.get("tenant_id") - company_id_from_user = current_user.get("company_id") - - # Validate access - validate_access_to_resource( - db, tenant_id, company_id_from_user, Company, company_id, "id" - ) - - company = CompanyService.get_by_id(db, company_id, tenant_id, company_id_from_user) - if not company: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Company not found", - ) - - return { - "id": company.id, - "name": company.name, - "rfc": company.rfc, - "program": company.program, - } - - -@router.get( - "/info/responsible/{company_id}", - response_model=dict, - summary="Get responsible person info", -) -async def get_responsible_info( - company_id: int, - db: Session = Depends(get_core_db), - current_user: dict = Depends(get_current_user), -): - """Get responsible person information for a company""" - tenant_id = current_user.get("tenant_id") - company_id_from_user = current_user.get("company_id") - - # Validate access - validate_access_to_resource( - db, tenant_id, company_id_from_user, Company, company_id, "id" - ) - - company = CompanyService.get_by_id(db, company_id, tenant_id, company_id_from_user) - if not company: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Company not found", - ) - - return { - "responsible": company.responsible, - "responsible_name": company.responsible_name, - "responsible_last_name": company.responsible_last_name, - "responsible_mother_last_name": company.responsible_mother_last_name, - "responsible_rfc": company.responsible_rfc, - "position": company.position, - } - - -@router.get( - "/info/program/{company_id}", - response_model=dict, - summary="Get program information", -) -async def get_program_info( - company_id: int, - db: Session = Depends(get_core_db), - current_user: dict = Depends(get_current_user), -): - """Get program information for a company""" - tenant_id = current_user.get("tenant_id") - company_id_from_user = current_user.get("company_id") - - # Validate access - validate_access_to_resource( - db, tenant_id, company_id_from_user, Company, company_id, "id" - ) - - company = CompanyService.get_by_id(db, company_id, tenant_id, company_id_from_user) - if not company: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Company not found", - ) - - return { - "program": company.program, - "program_number": company.program_number, - "prosec": company.prosec, - "prosec_authorization": company.prosec_authorization, - } + return [ + CompanyResponseDTO.model_validate(service.flatten_company_dto(company)) + for company in companies + ] +# ... existing code ... @router.get( "/{company_id}", @@ -270,6 +151,7 @@ async def get_company( detail="Tenant ID not found in user data", ) + service = CompanyService(db) company = CompanyService.get_by_id(db, company_id, tenant_id, 0) if not company: raise HTTPException( @@ -277,7 +159,7 @@ async def get_company( detail="Company not found", ) - return CompanyResponseDTO.model_validate(company) + return CompanyResponseDTO.model_validate(service.flatten_company_dto(company)) @router.put( @@ -299,81 +181,28 @@ async def update_company( detail="Tenant ID not found in user data", ) - updated_company = CompanyService.update(db, company_id, tenant_id, 0, data) + service = CompanyService(db) + updated_company = service.update(db, company_id, tenant_id, 0, data) if not updated_company: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Company not found", ) - return CompanyResponseDTO.model_validate(updated_company) + return CompanyResponseDTO.model_validate(service.flatten_company_dto(updated_company)) - return CompanyResponseDTO.model_validate(updated_company) -@router.post( - "/{company_id}/upload-logo", - response_model=dict, - summary="Upload company logo", -) -async def upload_company_logo( - company_id: int, - file: UploadFile = File(...), - db: Session = Depends(get_core_db), - current_user: dict = Depends(get_current_user), -): - """Upload logo for a company""" - tenant_id = current_user.get("tenant_id") - if not tenant_id: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Tenant ID not found in user data", - ) - # 1. Verify company exists - company = CompanyService.get_by_id(db, company_id, tenant_id, 0) - if not company: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Company not found", - ) - # 2. Define upload path - # Use a persistent path: 'app_data/logos/{company_id}' - upload_dir = Path(f"app_data/logos/{company_id}") - upload_dir.mkdir(parents=True, exist_ok=True) - - # 3. Save file - # Preserve original filename - filename = file.filename or "logo.png" - file_path = upload_dir / filename - - try: - # Check if file exists and remove it to avoid accumulation if needed, - # or just overwrite (shutil.copyfileobj overwrites) - with open(file_path, "wb") as buffer: - shutil.copyfileobj(file.file, buffer) - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Could not save file: {e}", - ) - - # 4. Returns the absolute path keys - abs_path = str(file_path.absolute()) - - return {"path": abs_path} @router.get( "/{company_id}/logo/image", summary="Get company logo image", ) -@router.get( - "/{company_id}/logo/image", - summary="Get company logo image", -) + async def get_company_logo_image( company_id: int, db: Session = Depends(get_core_db), @@ -401,6 +230,13 @@ async def get_company_logo_image( raise HTTPException(status_code=404, detail="Logo file not found on server") return FileResponse(file_path) + + +@router.delete( + "/{company_id}", + status_code=status.HTTP_204_NO_CONTENT, + summary="Delete a company", +) async def delete_company( company_id: int, db: Session = Depends(get_core_db), @@ -497,7 +333,8 @@ async def upload_company_logo( # Actualizar la empresa con la ruta del logo update_data = CompanyUpdateDTO(logo=file_path) - updated_company = CompanyService.update(db, company_id, tenant_id, 0, update_data) + service = CompanyService(db) + updated_company = service.update(db, company_id, tenant_id, 0, update_data) return { "message": "Logo uploaded successfully", diff --git a/backend/api/v1/modules/a76/general_catalogs/company/service.py b/backend/api/v1/modules/a76/general_catalogs/company/service.py index 63835cd1..90460e79 100644 --- a/backend/api/v1/modules/a76/general_catalogs/company/service.py +++ b/backend/api/v1/modules/a76/general_catalogs/company/service.py @@ -97,8 +97,139 @@ class CompanyService: logger.error(f"Error creating company: {str(e)}") raise HTTPException(status_code=500, detail="Error creating company") - @staticmethod + + # ==================== HELPERS FOR FIELD MAPPING ==================== + def _extract_company_fields(self, data: Dict[str, Any]) -> Dict[str, Any]: + """Extrae campos que pertenecen a la tabla Company principal""" + company_fields = [ + "name", "rfc", "curp", "main_activity", "program", "program_number", + "prosec", "prosec_authorization", "sector1", "sector2", "sector3", + "manufacturer_id", "broker_company", "responsible", "responsible_name", + "responsible_last_name", "responsible_mother_last_name", "responsible_rfc", + "position", "logo", "has_express_line", "order_format_type", + "is_service_company", "client_name", "subassembly_mode", "previous_code", + "active_labels", "active_fractions", "activate_caat", "trans_interface", + "american_costs", "scaf_readonly", "parts_replacement", "activate_facmexame", + "part_reference", "international_firm", "ftp_key", "sifra_path", + "version_type", "sql_language", "balance_operation_mode", "inter_db_name" + ] + return {k: v for k, v in data.items() if k in company_fields} + + def _extract_certification_fields(self, data: Dict[str, Any]) -> Dict[str, Any]: + """Extrae campos que pertenecen a CompanyCertification""" + cert_fields = [ + "is_certified_company", "certified_company_registration", + "certified_company_start_date", "certified_company_end_date", + "annex31_certification_date", "annex31_certification_number", + "annex31_modality", "annex31_company_type", "annex31_renewal_date", + "annex31_final_certification_date", "is_oea_company", "ctpat_svi", + "trusted_exporter_number", "neec_company" + ] + return {k: v for k, v in data.items() if k in cert_fields} + + def _extract_prevalidator_fields(self, data: Dict[str, Any]) -> Dict[str, Any]: + """Extrae campos que pertenecen a CompanyPrevalidator""" + # Note: 'prevalidator_key' in DTO maps to 'key' in model + fields = {} + if "prevalidator_key" in data: + fields["key"] = data["prevalidator_key"] + + # Add other fields if present in DTO in the future + return fields + + def flatten_company_dto(self, company: Company) -> Dict[str, Any]: + """Flattens Company and its submodels into a single dict for DTO validation""" + # 1. Base Company fields + result = { + k: getattr(company, k) + for k in company.__mapper__.c.keys() + } + # Explicitly ensure logo is present (defensive programming) + if hasattr(company, 'logo'): + result['logo'] = company.logo + + # Convert has_express_line from String "S"/"N" to Boolean + if hasattr(company, 'has_express_line'): + val = getattr(company, 'has_express_line', "N") + result['has_express_line'] = (val == "S") + + # 2. Certification fields + if company.certification: + cert_fields = [ + "is_certified_company", "certified_company_registration", + "certified_company_start_date", "certified_company_end_date", + "annex31_certification_date", "annex31_certification_number", + "annex31_modality", "annex31_company_type", "annex31_renewal_date", + "annex31_final_certification_date", "is_oea_company", "ctpat_svi", + "trusted_exporter_number", "neec_company" + ] + for field in cert_fields: + val = getattr(company.certification, field, None) + if val is not None: + result[field] = val + + # 3. Prevalidator fields + if company.prevalidator: + if company.prevalidator.key: + result["prevalidator_key"] = company.prevalidator.key + + return result + + # ==================== CRUD METHODS ==================== + + def create_company_manually(self, data: CompanyCreateDTO, tenant_id: int) -> Company: + from .submodels.certification import CompanyCertification + from .submodels.prevalidator import CompanyPrevalidator + + try: + # 1. Preparar datos + obj_data = data.model_dump(exclude_unset=True) + + # Handle boolean flags for Company (Hybrid Approach) + # has_express_line is String(2), is_service_company is Boolean + if "has_express_line" in obj_data and isinstance(obj_data["has_express_line"], bool): + obj_data["has_express_line"] = "S" if obj_data["has_express_line"] else "N" + + # 2. Extract fields for each model + company_data = self._extract_company_fields(obj_data) + cert_data = self._extract_certification_fields(obj_data) + preval_data = self._extract_prevalidator_fields(obj_data) + + # 3. Create Company + db_company = Company(**company_data, tenant_id=tenant_id) + self.db.add(db_company) + self.db.flush() # Generate ID + + # 4. Create Certification if data exists + if cert_data: + cert = CompanyCertification(**cert_data, company_id=db_company.id) + self.db.add(cert) + + # 5. Create Prevalidator if data exists + if preval_data: + preval = CompanyPrevalidator(**preval_data, company_id=db_company.id) + self.db.add(preval) + + # 6. Commit + self.db.commit() + self.db.refresh(db_company) + + return db_company + + except IntegrityError as e: + self.db.rollback() + logger.error(f"IntegrityError creating company manually: {str(e)}") + raise HTTPException( + status_code=400, + detail="Error de integridad: Es posible que esta empresa ya exista.", + ) + except Exception as e: + self.db.rollback() + logger.error(f"Error creating company manually: {str(e)}") + raise HTTPException(status_code=500, detail=f"Error creando empresa: {str(e)}") + def update( + self, # Changed to instance method to use self helper methods db: Session, company_id: int, tenant_id: int, @@ -106,23 +237,57 @@ class CompanyService: company_data: CompanyUpdateDTO, ) -> Optional[Company]: """Update a company""" - company = CompanyService.get_by_id(db, company_id, tenant_id, company_id_unused) + from .submodels.certification import CompanyCertification + from .submodels.prevalidator import CompanyPrevalidator + + # Use self.db if db is passed as None, or use passed db (legacy support) + session = db if db else self.db + + company = self.get_by_id(session, company_id, tenant_id, company_id_unused) if not company: return None # Update only provided fields update_data = company_data.model_dump(exclude_unset=True) - for field, value in update_data.items(): + + # 1. Update Company fields + company_fields = self._extract_company_fields(update_data) + + # Hybrid Approach: has_express_line is String, is_service_company is Boolean + if "has_express_line" in company_fields and isinstance(company_fields["has_express_line"], bool): + company_fields["has_express_line"] = "S" if company_fields["has_express_line"] else "N" + + for field, value in company_fields.items(): setattr(company, field, value) + # 2. Update Certification + cert_fields = self._extract_certification_fields(update_data) + if cert_fields: + if company.certification: + for field, value in cert_fields.items(): + setattr(company.certification, field, value) + else: + new_cert = CompanyCertification(**cert_fields, company_id=company.id) + session.add(new_cert) + + # 3. Update Prevalidator + preval_fields = self._extract_prevalidator_fields(update_data) + if preval_fields: + if company.prevalidator: + for field, value in preval_fields.items(): + setattr(company.prevalidator, field, value) + else: + new_preval = CompanyPrevalidator(**preval_fields, company_id=company.id) + session.add(new_preval) + try: - db.commit() - db.refresh(company) + session.commit() + session.refresh(company) return company except Exception as e: - db.rollback() + session.rollback() logger.error(f"Error updating company {company_id}: {str(e)}") - raise HTTPException(status_code=500, detail="Error updating company") + raise HTTPException(status_code=500, detail=f"Error al actualizar la empresa: {str(e)}") @staticmethod def delete( @@ -134,19 +299,56 @@ class CompanyService: return False try: + # Manual cascade delete for submodels to ensure order and avoid FK issues + # (Even though cascade="all, delete-orphan" is set, manual deletion is safer for strict DBs) + + # 1. Delete Certification + if company.certification: + db.delete(company.certification) + + # 2. Delete Prevalidator + if company.prevalidator: + db.delete(company.prevalidator) + + # 3. Delete Electronic Agent + if company.electronic_agent: + db.delete(company.electronic_agent) + + # 4. Delete VU + if company.ventanilla_unica: + db.delete(company.ventanilla_unica) + + # 5. Delete CFDI + if company.cfdi: + db.delete(company.cfdi) + + # 6. Delete Digital Certificates + for cert in company.digital_certificates: + db.delete(cert) + + # 7. Delete Addresses + for addr in company.addresses: + db.delete(addr) + + # Flush to execute submodel deletions first + db.flush() + db.delete(company) db.commit() return True except IntegrityError as e: db.rollback() logger.error(f"IntegrityError deleting company {company_id}: {str(e)}") - # Check if it's a foreign key constraint - if "foreign key constraint" in str(e).lower(): - raise HTTPException( - status_code=400, - detail="No se puede eliminar la empresa porque tiene registros relacionados (facturas, conceptos, etc.)" - ) - raise HTTPException(status_code=400, detail="Error al eliminar la empresa") + # Try to get detailed error from psycopg2 + detail = "No se puede eliminar la empresa porque tiene registros relacionados." + if hasattr(e, 'orig') and hasattr(e.orig, 'diag'): + if e.orig.diag.message_detail: + detail += f" Detalles: {e.orig.diag.message_detail}" + + raise HTTPException( + status_code=400, + detail=detail + ) except Exception as e: db.rollback() logger.error(f"Error deleting company {company_id}: {str(e)}") @@ -169,32 +371,4 @@ class CompanyService: .filter(Company.tenant_id == tenant_id) .first() is not None - ) - - def create_company_manually(self, data: CompanyCreateDTO, tenant_id: int) -> Company: - - try: - # 1. Preparar datos - obj_data = data.model_dump(exclude_unset=True) - - # 2. Crear objeto SQLAlchemy - db_obj = Company(**obj_data, tenant_id=tenant_id) - - # 3. Guardar - self.db.add(db_obj) - self.db.commit() - self.db.refresh(db_obj) - - return db_obj - - except IntegrityError as e: - self.db.rollback() - logger.error(f"IntegrityError creating company manually: {str(e)}") - raise HTTPException( - status_code=400, - detail="Error de integridad: Es posible que esta empresa ya exista.", - ) - except Exception as e: - self.db.rollback() - logger.error(f"Error creating company manually: {str(e)}") - raise HTTPException(status_code=500, detail=f"Error creando empresa: {str(e)}") \ No newline at end of file + ) \ No newline at end of file diff --git a/backend/api/v1/modules/a76/general_catalogs/company/submodels/certification.py b/backend/api/v1/modules/a76/general_catalogs/company/submodels/certification.py index 5624704b..eea80e08 100644 --- a/backend/api/v1/modules/a76/general_catalogs/company/submodels/certification.py +++ b/backend/api/v1/modules/a76/general_catalogs/company/submodels/certification.py @@ -2,7 +2,7 @@ Modelo de certificaciones de empresa """ from typing import Optional, TYPE_CHECKING -from sqlalchemy import Integer, String, SmallInteger, ForeignKey +from sqlalchemy import Integer, String, SmallInteger, ForeignKey, Boolean from sqlalchemy.orm import Mapped, mapped_column, relationship from core.database import Base from api.v1.common.base_models import TimestampMixin diff --git a/backend/api/v1/modules/a76/general_catalogs/exchange_rate/routes.py b/backend/api/v1/modules/a76/general_catalogs/exchange_rate/routes.py index 00870adf..22ab8ec9 100644 --- a/backend/api/v1/modules/a76/general_catalogs/exchange_rate/routes.py +++ b/backend/api/v1/modules/a76/general_catalogs/exchange_rate/routes.py @@ -27,10 +27,25 @@ route_handler = TenantCRUDRoutes( max_page_size=100, ) -router = route_handler.router +crud_router = route_handler.router + +# Create a custom router for specific endpoints that must be matched BEFORE generic CRUD routes +# We use the same prefix so they are grouped together +from fastapi import APIRouter +custom_router = APIRouter(prefix="/exchange-rate", tags=[]) + +@custom_router.get("/test-ping") +async def test_ping(): + return {"message": "pong"} + +# Master router to export +router = APIRouter() +# Include custom routes FIRST to avoid shadowing by /{id} +router.include_router(custom_router) +# router.include_router(crud_router) -@router.get( +@custom_router.get( "/", response_model=Dict[str, Any], summary="List Exchange Rates", @@ -66,3 +81,37 @@ async def list_exchange_rates( "page": page, "page_size": page_size, } + +@custom_router.get( + "/dof-search", + response_model=Dict[str, Any], + summary="Fetch Exchange Rate from DOF", + description="Fetches the exchange rate from the Official Journal of the Federation (DOF) for a specific date.", +) +async def fetch_exchange_rate_dof( + date: str = Query(..., description="Date in YYYY-MM-DD format"), + db: Session = Depends(get_core_db), + current_user: Dict[str, Any] = Depends(get_current_user), +): + # This endpoint can be public or protected. Assuming protected for now. + # No specific tenant validation needed since it's an external query, + # but good to ensure user is authenticated. + + try: + print(f"DEBUG: Route called with date={date}") + rate = ExchangeRateService.fetch_from_dof(date) + + if rate is None: + return {"success": False, "message": "No se encontró el tipo de cambio en el DOF para la fecha especificada o el servicio no está disponible.", "value": None} + + return {"success": True, "value": rate} + except Exception as e: + print(f"DEBUG: Error in route: {e}") + import traceback + traceback.print_exc() + return {"success": False, "message": f"Error interno: {str(e)}", "value": None} + +# Include routers at the end to ensure all routes are registered +# Include custom routes FIRST to avoid shadowing by /{id} of crud_router +router.include_router(custom_router) +router.include_router(crud_router) diff --git a/backend/api/v1/modules/a76/general_catalogs/exchange_rate/services.py b/backend/api/v1/modules/a76/general_catalogs/exchange_rate/services.py index f7749b43..ee33f82a 100644 --- a/backend/api/v1/modules/a76/general_catalogs/exchange_rate/services.py +++ b/backend/api/v1/modules/a76/general_catalogs/exchange_rate/services.py @@ -1,10 +1,18 @@ from typing import Optional, Tuple, List, Dict, Any from datetime import datetime, time +import requests +import re from sqlalchemy.orm import Session from sqlalchemy import cast, Date from . import dto, models +import urllib3 +from core.config import settings + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + class ExchangeRateService: @@ -101,8 +109,8 @@ class ExchangeRateService: def update( db: Session, exchange_rate_id: int, - exchange_rate_data: dto.ExchangeRateUpdateDTO, tenant_id: int, + exchange_rate_data: dto.ExchangeRateUpdateDTO, company_id: int, ) -> Optional[models.ExchangeRate]: """Update an exchange rate""" @@ -135,3 +143,92 @@ class ExchangeRateService: db.delete(exchange_rate) db.commit() return True + + @staticmethod + def _get_sitar_api_token(base_url, username, password) -> Optional[str]: + """Helper to get authentication token from external API""" + try: + print(base_url) + login_url = f"{base_url}/exchange-rate/auth/login" + payload = {"username": username, "password": password} + headers = {"Content-Type": "application/json"} + + response = requests.post(login_url, json=payload, headers=headers, timeout=5) + if response.status_code not in [200, 201]: + print(f"External API Login Failed: {response.status_code} - {response.text}") + return None + + data = response.json() + return data.get("token") or data.get("access_token") + except Exception as e: + print(f"External API Login Error: {e}") + return None + + @staticmethod + def fetch_from_dof(date_str: str) -> Optional[float]: + """ + Fetches the exchange rate from an external API (replacing direct DOF scraping). + The API handles date logic (holidays, weekends) automatically. + + Args: + date_str (str): Date in 'YYYY-MM-DD' format. + + Returns: + Optional[float]: The exchange rate value if found, None otherwise. + """ + # API Credentials + API_BASE_URL = settings.SITAR_API_URL + API_USER = settings.SITAR_API_USER + API_PASS = settings.SITAR_API_PASSWORD + + if not API_USER or not API_PASS: + print("ERROR: External API credentials not properly configured in settings") + return None + + try: + print(f"DEBUG: Fetching External API for date: {date_str}") + + # 1. Get Token + token = ExchangeRateService._get_sitar_api_token(API_BASE_URL, API_USER, API_PASS) + if not token: + print("Failed to obtain external API token") + return None + + # 2. Fetch Exchange Rate + # The API endpoint is /tipoCambio/{YYYY-MM-DD} + tc_endpoint = f"{API_BASE_URL}/exchange-rate/tipoCambio/{date_str}" + + # Auth header: The API expects just the token string in common usage, but we try standard first + # based on user feedback/code: 'Authorization:' . $token + headers = { + "Authorization": token, + "Content-Type": "application/json" + } + + response = requests.get(tc_endpoint, headers=headers, timeout=5) + + # Retry logic as per PHP reference (if 401, maybe formatting issue, but requests handles headers well) + if response.status_code == 401: + # Try with Bearer prefix just in case, though PHP code suggested raw token + print("DEBUG: 401 received, retrying with Bearer prefix...") + headers["Authorization"] = f"Bearer {token}" + response = requests.get(tc_endpoint, headers=headers, timeout=5) + + if response.status_code != 200: + print(f"External API TC Error: {response.status_code} - {response.text}") + return None + + data = response.json() + # Expected response: {"Id":..., "Fecha":"...", "TipoCambio":17.452, "Mov":"..."} + + if "TipoCambio" in data: + val = float(data["TipoCambio"]) + print(f"DEBUG: External API returned value: {val}") + return val + + print(f"DEBUG: 'TipoCambio' key not found in response: {data}") + return None + + except Exception as e: + print(f"Error fetching from External API: {e}") + return None diff --git a/backend/api/v1/modules/a76/general_catalogs/packages/models.py b/backend/api/v1/modules/a76/general_catalogs/packages/models.py index f191fa94..92b07647 100644 --- a/backend/api/v1/modules/a76/general_catalogs/packages/models.py +++ b/backend/api/v1/modules/a76/general_catalogs/packages/models.py @@ -19,7 +19,7 @@ class Package(Base, TenantScopedMixin, TimestampMixin): __table_args__ = ( PrimaryKeyConstraint("id", name="packages_pkey"), UniqueConstraint("tenant_id", "company_id", "key", name="packages_key_ukey"), - {"schema": "a76"}, + {"schema": "a76", "extend_existing": True}, ) id: Mapped[int] = mapped_column(Integer, primary_key=True) diff --git a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/dto.py b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/dto.py index 56c9d37f..ef5997fe 100644 --- a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/dto.py +++ b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/dto.py @@ -36,14 +36,8 @@ class UnitOfMeasureBase(BaseModel): oma_code: Optional[str] = Field(None, max_length=20) -class UnitOfMeasureGeneralBase(BaseModel): - code: str = Field(..., max_length=20, description="Unit Code") - description: Optional[str] = Field(None, max_length=100) - conversion_factor: Optional[Decimal] = None - mexico_unit: Optional[str] = Field(None, max_length=20) - american_unit_code: Optional[str] = Field(None, max_length=20) - customs_code: Optional[int] = Field(None) - ace_code: Optional[str] = Field(None, max_length=20) +class UnitOfMeasureGeneralBase(UnitOfMeasureBase): + pass # --- Create DTOs --- @@ -105,14 +99,8 @@ class UnitOfMeasureUpdate(BaseModel): oma_code: Optional[str] = Field(None, max_length=20) -class UnitOfMeasureGeneralUpdate(BaseModel): - code: Optional[str] = Field(None, max_length=20) - description: Optional[str] = Field(None, max_length=100) - conversion_factor: Optional[Decimal] = None - mexico_unit: Optional[str] = Field(None, max_length=20) - american_unit_code: Optional[str] = Field(None, max_length=20) - customs_code: Optional[int] = Field(None) - ace_code: Optional[str] = Field(None, max_length=20) +class UnitOfMeasureGeneralUpdate(UnitOfMeasureUpdate): + pass # --- Response DTOs --- @@ -142,6 +130,5 @@ class UnitOfMeasureResponse(UnitOfMeasureBase): model_config = ConfigDict(from_attributes=True) -class UnitOfMeasureGeneralResponse(UnitOfMeasureGeneralBase): - id: int - model_config = ConfigDict(from_attributes=True) +class UnitOfMeasureGeneralResponse(UnitOfMeasureResponse): + pass diff --git a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/routes.py b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/routes.py index 9a9b3db7..93fb39de 100644 --- a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/routes.py +++ b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/routes.py @@ -17,6 +17,7 @@ ace_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(ace_router) @@ -32,6 +33,7 @@ oma_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(oma_router) @@ -47,6 +49,7 @@ american_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(american_router) @@ -62,6 +65,7 @@ customs_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(customs_router) @@ -77,6 +81,7 @@ general_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(general_router) @@ -93,5 +98,6 @@ main_router = TenantCRUDRoutes( id_name="id", enable_list=True, enable_filters=True, + max_page_size=10000, ).router router.include_router(main_router) diff --git a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/service.py b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/service.py index f032f76e..c514c2ee 100644 --- a/backend/api/v1/modules/a76/general_catalogs/units_of_measure/service.py +++ b/backend/api/v1/modules/a76/general_catalogs/units_of_measure/service.py @@ -154,7 +154,7 @@ class UnitOfMeasureService(BaseService): class UnitOfMeasureGeneralService(BaseService): - model = UnitOfMeasureGeneral + model = UnitOfMeasure def get_all_uom_general(session: Session, skip: int = 0, limit: int = 100) -> Sequence[UnitOfMeasureGeneral]: diff --git a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/common.py b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/common.py index 0440bf81..afba527a 100644 --- a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/common.py +++ b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/common.py @@ -12,6 +12,76 @@ from api.v1.modules.public.reference_data.currency_types.models import CurrencyT from api.v1.modules.public.reference_data.customs_sections.models import CustomsSection from ....models import TransportType, Currency, WeightUnit from core.exceptions import ErrorCollector +from typing import Dict, Any + + +def validate_required_fields_by_operation( + invoice_data: Dict[str, Any], + operation_type: str, + errors: ErrorCollector +) -> None: + """ + Valida campos obligatorios según tipo de operación. + Usar ANTES de guardar en BD. + """ + + # PROVEEDOR (SIEMPRE OBLIGATORIO - mensaje dinámico) + if not invoice_data.get('provider_id'): + # Mensaje dinámico según el header seleccionado + provider_labels = { + 'proveedor': 'Proveedor', + 'exportador': 'Exportador' + } + provider_header = invoice_data.get('provider_header') or 'proveedor' + field_label = provider_labels.get(provider_header, 'Proveedor') + + errors.add_error( + field="provider_id", + message=f"Debe seleccionar {field_label}", + solution=["Seleccione un proveedor de la lista desplegable"], + code="REQUIRED", + value=None + ) + + # VENDIDO A / CONSIGNADO A (SIEMPRE OBLIGATORIO - mensaje dinámico) + if not invoice_data.get('sold_to_id'): + # Mensaje dinámico según el header seleccionado + sold_to_labels = { + 'consignado_a': 'Consignado a', + 'vendido_a': 'Vendido a', + 'exportado_a': 'Exportado a', + 'importador': 'Importador' + } + sold_to_header = invoice_data.get('sold_to_header') or 'consignado_a' + field_label = sold_to_labels.get(sold_to_header, 'Cliente') + + errors.add_error( + field="sold_to_id", + message=f"Debe seleccionar {field_label}", + solution=["Seleccione una opción de la lista desplegable"], + code="REQUIRED", + value=None + ) + + # ENVIADO A (SIEMPRE OBLIGATORIO - mensaje fijo) + if not invoice_data.get('shipped_to_id'): + errors.add_error( + field="shipped_to_id", + message="Debe seleccionar el Destinatario", + solution=["Seleccione un destinatario de la lista desplegable"], + code="REQUIRED", + value=None + ) + + # AGENTE ADUANAL (OBLIGATORIO si hay pedimento) + if invoice_data.get('pedimento_id') and not invoice_data.get('customs_broker_id'): + errors.add_error( + field="customs_broker_id", + message="Debe seleccionar un Agente Aduanal", + solution=["Seleccione un agente aduanal de la lista desplegable"], + code="REQUIRED", + value=None + ) def validate_common( @@ -245,78 +315,87 @@ def validate_common( value=invoice.document_type, ) - provider_exists = ( - db.query(ClientProvider) - .filter( - ClientProvider.id == invoice.compliance_mx.provider_id, - ClientProvider.tenant_id == tenant_id, - ClientProvider.company_id == company_id, - ) - .first() - ) - if not provider_exists: - errors.add_error( - field="compliance_mx.provider_id", - message="El Proveedor no existe en el Catálogo de Clientes y Proveedores.", - solution=["Verifica el ID del Proveedor", "Revisa el catálogo"], - code="NOT_FOUND", - value=invoice.compliance_mx.provider_id, + # Validar proveedor solo si se proporciona + if invoice.compliance_mx.provider_id: + provider_exists = ( + db.query(ClientProvider) + .filter( + ClientProvider.id == invoice.compliance_mx.provider_id, + ClientProvider.tenant_id == tenant_id, + ClientProvider.company_id == company_id, + ) + .first() ) + if not provider_exists: + errors.add_error( + field="compliance_mx.provider_id", + message="El Proveedor no existe en el Catálogo de Clientes y Proveedores.", + solution=["Verifica el ID del Proveedor", "Revisa el catálogo"], + code="NOT_FOUND", + value=invoice.compliance_mx.provider_id, + ) - selled_to_exists = ( - db.query(ClientProvider) - .filter( - ClientProvider.id == invoice.compliance_mx.sold_to_id, - ClientProvider.tenant_id == tenant_id, - ClientProvider.company_id == company_id, - ) - .first() - ) - if not selled_to_exists: - errors.add_error( - field="compliance_mx.sold_to_id", - message="El Cliente no existe en el Catálogo de Clientes y Proveedores.", - solution=["Verifica el ID del Cliente", "Revisa el catálogo"], - code="NOT_FOUND", - value=invoice.compliance_mx.sold_to_id, + # Validar vendido a solo si se proporciona + if invoice.compliance_mx.sold_to_id: + selled_to_exists = ( + db.query(ClientProvider) + .filter( + ClientProvider.id == invoice.compliance_mx.sold_to_id, + ClientProvider.tenant_id == tenant_id, + ClientProvider.company_id == company_id, + ) + .first() ) + if not selled_to_exists: + errors.add_error( + field="compliance_mx.sold_to_id", + message="El Cliente no existe en el Catálogo de Clientes y Proveedores.", + solution=["Verifica el ID del Cliente", "Revisa el catálogo"], + code="NOT_FOUND", + value=invoice.compliance_mx.sold_to_id, + ) - shipped_to_exists = ( - db.query(ClientProvider) - .filter( - ClientProvider.id == invoice.compliance_mx.shipped_to_id, - ClientProvider.tenant_id == tenant_id, - ClientProvider.company_id == company_id, - ) - .first() - ) - if not shipped_to_exists: - errors.add_error( - field="compliance_mx.shipped_to_id", - message="El Destinatario no existe en el Catálogo de Clientes y Proveedores.", - solution=["Verifica el ID del Destinatario", "Revisa el catálogo"], - code="NOT_FOUND", - value=invoice.compliance_mx.shipped_to_id, + # Validar destinatario solo si se proporciona + if invoice.compliance_mx.shipped_to_id: + shipped_to_exists = ( + db.query(ClientProvider) + .filter( + ClientProvider.id == invoice.compliance_mx.shipped_to_id, + ClientProvider.tenant_id == tenant_id, + ClientProvider.company_id == company_id, + ) + .first() ) + if not shipped_to_exists: + errors.add_error( + field="compliance_mx.shipped_to_id", + message="El Destinatario no existe en el Catálogo de Clientes y Proveedores.", + solution=["Verifica el ID del Destinatario", "Revisa el catálogo"], + code="NOT_FOUND", + value=invoice.compliance_mx.shipped_to_id, + ) - customs_broker_exists = ( - db.query(CustomsBroker) - .filter( - CustomsBroker.id == invoice.compliance_mx.customs_broker_id, - CustomsBroker.tenant_id == tenant_id, - CustomsBroker.company_id == company_id, - ) - .first() - ) - if not customs_broker_exists: - errors.add_error( - field="compliance_mx.customs_broker_id", - message="El Agente Aduanal no existe en el Catálogo de Clientes y Proveedores.", - solution=["Verifica el ID del Agente Aduanal", "Revisa el catálogo"], - code="NOT_FOUND", - value=invoice.compliance_mx.customs_broker_id, + # Validar agente aduanal solo si se proporciona + if invoice.compliance_mx.customs_broker_id: + customs_broker_exists = ( + db.query(CustomsBroker) + .filter( + CustomsBroker.id == invoice.compliance_mx.customs_broker_id, + CustomsBroker.tenant_id == tenant_id, + CustomsBroker.company_id == company_id, + ) + .first() ) + if not customs_broker_exists: + errors.add_error( + field="compliance_mx.customs_broker_id", + message="El Agente Aduanal no existe en el Catálogo de Clientes y Proveedores.", + solution=["Verifica el ID del Agente Aduanal", "Revisa el catálogo"], + code="NOT_FOUND", + value=invoice.compliance_mx.customs_broker_id, + ) + # Validar transportista solo si se proporciona if invoice.logistics.carrier_id: carrier_exists = ( db.query(ClientProvider) diff --git a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/create.py b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/create.py index be6f6fc1..56800ff5 100644 --- a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/create.py +++ b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/create.py @@ -3,7 +3,7 @@ from sqlalchemy.orm import Session from api.v1.modules.a76.general_catalogs.exchange_rate.models import ExchangeRate from core.exceptions import ErrorCollector from ....schemas import InvoiceHeaderCreate -from .common import validate_common +from .common import validate_common, validate_required_fields_by_operation def validate_create(db: Session, invoice: InvoiceHeaderCreate, tenant_id: int, company_id: int, errors: ErrorCollector) -> None: """ Valida la creación de una nueva factura de importe temporal """ @@ -21,22 +21,31 @@ def validate_create(db: Session, invoice: InvoiceHeaderCreate, tenant_id: int, c errors.add_required_error("invoice_number") if not invoice.invoice_date: - errors.add_required_error("invoice_date") - - if not invoice.compliance_mx.provider_id: - errors.add_required_error("compliance_mx.provider_id") + errors.add_required_error("invoice_date") - if not invoice.compliance_mx.sold_to_id: - errors.add_required_error("compliance_mx.sold_to_id") - - if not invoice.compliance_mx.shipped_to_id: - errors.add_required_error("compliance_mx.shipped_to_id") - - if not invoice.compliance_mx.customs_broker_id: - errors.add_required_error("compliance_mx.customs_broker_id") - if errors.has_errors(): - """Se retorna por que hay campos obligatiorios para las validaciones que tienen que ser llenados""" + """Se retorna porque hay campos obligatorios básicos que deben ser llenados""" + return + + # Validar campos obligatorios según tipo de operación + invoice_data = { + 'provider_header': invoice.compliance_mx.provider_header if invoice.compliance_mx else None, + 'provider_id': invoice.compliance_mx.provider_id if invoice.compliance_mx else None, + 'sold_to_id': invoice.compliance_mx.sold_to_id if invoice.compliance_mx else None, + 'sold_to_header': invoice.compliance_mx.sold_to_header if invoice.compliance_mx else None, + 'shipped_to_id': invoice.compliance_mx.shipped_to_id if invoice.compliance_mx else None, + 'customs_broker_id': invoice.compliance_mx.customs_broker_id if invoice.compliance_mx else None, + 'pedimento_id': invoice.compliance_mx.pedimento_id if invoice.compliance_mx else None, + } + + validate_required_fields_by_operation( + invoice_data=invoice_data, + operation_type=invoice.operation_type, + errors=errors + ) + + if errors.has_errors(): + """Se retorna porque hay campos obligatorios según el tipo de operación que deben ser llenados""" return validate_common(db, invoice, tenant_id, company_id, errors) diff --git a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/update.py b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/update.py index 58efd41a..da4cc970 100644 --- a/backend/api/v1/modules/a76/invoices/imports/temporary/validators/update.py +++ b/backend/api/v1/modules/a76/invoices/imports/temporary/validators/update.py @@ -5,6 +5,7 @@ from decimal import Decimal from core.exceptions import ErrorCollector from ....schemas import InvoiceHeaderUpdate from ....models import InvoiceHeader +from .common import validate_required_fields_by_operation # Helper function para limpiar strings (equivalente a Clip()) @@ -33,6 +34,22 @@ def validate_update( None (modifica invoice_data in-place y acumula errores en errors) """ + # Validar campos requeridos según el tipo de operación + invoice_dict = { + 'provider_id': invoice_data.compliance_mx.provider_id if invoice_data.compliance_mx else None, + 'sold_to_id': invoice_data.compliance_mx.sold_to_id if invoice_data.compliance_mx else None, + 'sold_to_header': invoice_data.compliance_mx.sold_to_header if invoice_data.compliance_mx else None, + 'shipped_to_id': invoice_data.compliance_mx.shipped_to_id if invoice_data.compliance_mx else None, + 'customs_broker_id': invoice_data.compliance_mx.customs_broker_id if invoice_data.compliance_mx else None, + 'pedimento_id': invoice_data.compliance_mx.pedimento_id if invoice_data.compliance_mx else None, + } + + validate_required_fields_by_operation( + invoice_data=invoice_dict, + operation_type=invoice_data.operation_type or 'IMP', + errors=errors + ) + # Primero ejecutar validaciones comunes # validate_common(invoice_data, errors) diff --git a/backend/api/v1/modules/a76/invoices/schemas.py b/backend/api/v1/modules/a76/invoices/schemas.py index 88b7cf0c..37ac73b2 100644 --- a/backend/api/v1/modules/a76/invoices/schemas.py +++ b/backend/api/v1/modules/a76/invoices/schemas.py @@ -113,17 +113,17 @@ class InvoiceComplianceMxBase(BaseModel): manifest_number: Optional[str] = Field( None, max_length=15, description="Manifest number" ) - provider_header: Optional[str] = Field(None, max_length=20, description="Provider header") - provider_id: Optional[int] = Field(None, description="Provider ID") - sold_to_header: Optional[str] = Field(None, max_length=20, description="Sold to header") - sold_to_id: Optional[int] = Field(None, description="Sold to ID") - shipped_to_header: Optional[str] = Field(None, max_length=20, description="Shipped to header") - shipped_to_id: Optional[int] = Field(None, description="Shipped to ID") - shipped_by_header: Optional[str] = Field( + provider_header: str = Field(None, max_length=20, description="Provider header") + provider_id: int = Field(None, description="Provider ID") + sold_to_header: str = Field(None, max_length=20, description="Sold to header") + sold_to_id: int = Field(None, description="Sold to ID") + shipped_to_header: str = Field(None, max_length=20, description="Shipped to header") + shipped_to_id: int = Field(None, description="Shipped to ID") + shipped_by_header: Optional[int] = Field( None, max_length=20, description="Shipped by header" ) shipped_by_id: Optional[int] = Field(None, description="Shipped by ID") - customs_broker_id: Optional[int] = Field(None, description="Customs broker ID") + customs_broker_id: int = Field(None, description="Customs broker ID") customs_broker_us_id: Optional[int] = Field( None, description="US customs broker ID" ) diff --git a/backend/api/v1/modules/a76/items/imports/temporary/validators/create.py b/backend/api/v1/modules/a76/items/imports/temporary/validators/create.py index d6080ac3..b14a9746 100644 --- a/backend/api/v1/modules/a76/items/imports/temporary/validators/create.py +++ b/backend/api/v1/modules/a76/items/imports/temporary/validators/create.py @@ -1,6 +1,7 @@ """ Validaciones para creación de items vía API. """ + from sqlalchemy.orm import Session from core.exceptions import ErrorCollector from api.v1.modules.a76.items.line_items.schemas import LineItemCreate @@ -12,11 +13,11 @@ def validate_create( line: LineItemCreate, tenant_id: int, company_id: int, - errors: ErrorCollector + errors: ErrorCollector, ) -> None: """ Validaciones para crear LineItems vía API (actualmente en uso). - + Args: db: Sesión de base de datos line: Datos del line item @@ -30,43 +31,34 @@ def validate_create( field="line_number", message="El número de línea es obligatorio", solution="Proporciona un número de línea válido", - code="REQUIRED" + code="REQUIRED", ) - - # 2. Validar part_number_id - if not line.part_number_id: - errors.add_error( - field="part_number_id", - message="Part Number ID es obligatorio", - solution="Selecciona un número de parte válido del catálogo", - code="REQUIRED" - ) - - # 3. Validar class_id + + # 2. Validar class_id if not line.class_id: errors.add_error( field="class_id", message="Clase (ID) es obligatorio", solution="Selecciona una clasificación válida del catálogo", - code="REQUIRED" + code="REQUIRED", ) - + # 4. Validar unit_of_measure if not line.unit_of_measure: errors.add_error( field="unit_of_measure", message="U.M. es obligatorio", solution="Proporciona una unidad de medida válida", - code="REQUIRED" + code="REQUIRED", ) - + # 5. Validar quantity.quantity if not line.quantity: errors.add_error( field="quantity", message="Quantity es obligatorio", solution="Proporciona una cantidad válida", - code="REQUIRED" + code="REQUIRED", ) else: # Validar con nombre amigable @@ -75,44 +67,69 @@ def validate_create( field="quantity.quantity", message="Quantity debe ser mayor a cero", solution="Proporciona una cantidad válida", - code="INVALID_VALUE" if line.quantity.quantity is not None else "REQUIRED" + code=( + "INVALID_VALUE" + if line.quantity.quantity is not None + else "REQUIRED" + ), ) - + # 6. Validar financial.unit_cost if not line.financial: errors.add_error( field="financial", message="Unit Cost es obligatorio", solution="Proporciona el costo unitario del item", - code="REQUIRED" + code="REQUIRED", ) else: has_cost = ( - line.financial.unit_cost_usd or - line.financial.unit_cost_mxn or - line.financial.unit_cost_capture + line.financial.unit_cost_usd + or line.financial.unit_cost_mxn + or line.financial.unit_cost_capture ) if not has_cost: errors.add_error( field="financial.unit_cost", message="Unit Cost es obligatorio", solution="Proporciona al menos un costo unitario (USD, MXN o captura)", - code="REQUIRED" + code="REQUIRED", ) - + # 7. Validar description.description_spanish if line.description: - if not line.description.description_spanish or not line.description.description_spanish.strip(): + if ( + not line.description.description_spanish + or not line.description.description_spanish.strip() + ): errors.add_error( field="description.description_spanish", message="Description in Spanish es obligatorio", solution="Proporciona una descripción del item en español", - code="REQUIRED" + code="REQUIRED", ) else: errors.add_error( field="description.description_spanish", message="Description in Spanish es obligatorio", solution="Proporciona una descripción del item en español", + code="REQUIRED", + ) + + # 8. Validar customs.origin_country + if not line.customs or not line.customs.origin_country: + errors.add_error( + field="customs.origin_country", + message="País de Origen es obligatorio", + solution="Selecciona el país de origen del item", + code="REQUIRED" + ) + + # 9. Validar customs.fraction_type + if not line.customs or not line.customs.fraction_type: + errors.add_error( + field="customs.fraction_type", + message="Tipo de Tarifa es obligatorio", + solution="Selecciona el tipo de tarifa (GENERAL, PROSEC, ALADI, TLCS)", code="REQUIRED" ) \ No newline at end of file diff --git a/backend/api/v1/modules/a76/items/imports/temporary/validators/update.py b/backend/api/v1/modules/a76/items/imports/temporary/validators/update.py index 8feaa515..78b044aa 100644 --- a/backend/api/v1/modules/a76/items/imports/temporary/validators/update.py +++ b/backend/api/v1/modules/a76/items/imports/temporary/validators/update.py @@ -1,6 +1,7 @@ """ Validaciones para actualización de items vía API. """ + from sqlalchemy.orm import Session from core.exceptions import ErrorCollector from api.v1.modules.a76.items.line_items.schemas import LineItemUpdate @@ -13,12 +14,12 @@ def validate_update( tenant_id: int, company_id: int, errors: ErrorCollector, - invoice_id: int = None + invoice_id: int = None, ) -> None: """ Validaciones para actualizar LineItems vía API. Incluye todas las validaciones de negocio de Clarion. - + Args: db: Sesión de base de datos line: Datos del line item a actualizar @@ -33,36 +34,27 @@ def validate_update( field="line_number", message="El número de línea no puede estar vacío", solution="Proporciona un número de línea válido", - code="REQUIRED" + code="REQUIRED", ) - - # 2. Validar part_number_id si se proporciona - if line.part_number_id is not None and not line.part_number_id: - errors.add_error( - field="part_number_id", - message="Part Number ID no puede estar vacío", - solution="Selecciona un número de parte válido del catálogo", - code="REQUIRED" - ) - - # 3. Validar class_id si se proporciona + + # 2. Validar class_id si se proporciona if line.class_id is not None and not line.class_id: errors.add_error( field="class_id", message="Clase (ID) no puede estar vacío", solution="Selecciona una clasificación válida del catálogo", - code="REQUIRED" + code="REQUIRED", ) - + # 4. Validar unit_of_measure si se proporciona if line.unit_of_measure is not None and not line.unit_of_measure: errors.add_error( field="unit_of_measure", message="U.M. no puede estar vacío", solution="Proporciona una unidad de medida válida", - code="REQUIRED" + code="REQUIRED", ) - + # 5. Validar cantidad si se proporciona if line.quantity: # Si se proporciona el objeto quantity, validar que quantity.quantity sea válido @@ -72,7 +64,7 @@ def validate_update( field="quantity.quantity", message="Quantity debe ser mayor a cero", solution="Proporciona una cantidad válida", - code="INVALID_VALUE" + code="INVALID_VALUE", ) else: # Si se proporciona quantity pero quantity.quantity es None, es requerido @@ -80,9 +72,9 @@ def validate_update( field="quantity.quantity", message="Quantity es obligatorio", solution="Proporciona una cantidad mayor a 0", - code="REQUIRED" + code="REQUIRED", ) - + # 6. Validar peso neto si se proporciona if line.quantity and line.quantity.net_weight is not None: if line.quantity.net_weight <= 0: @@ -90,25 +82,25 @@ def validate_update( field="quantity.net_weight", message="Net Weight debe ser mayor a cero", solution="Proporciona un peso neto válido", - code="INVALID_VALUE" + code="INVALID_VALUE", ) - + # 7. Validar costo unitario si se proporciona financial (excepto subpartidas) if line.financial: is_subitem = line.fa_data and line.fa_data.is_subitem if line.fa_data else False - + if not is_subitem: has_cost = ( - line.financial.unit_cost_usd or - line.financial.unit_cost_mxn or - line.financial.unit_cost_capture + line.financial.unit_cost_usd + or line.financial.unit_cost_mxn + or line.financial.unit_cost_capture ) if not has_cost: errors.add_error( field="financial.unit_cost", message="Unit Cost es obligatorio", solution="Proporciona al menos un costo unitario (USD, MXN o captura)", - code="REQUIRED" + code="REQUIRED", ) # Validar que sean positivos if line.financial.unit_cost_usd is not None: @@ -117,7 +109,7 @@ def validate_update( field="financial.unit_cost_usd", message="Unit Cost (USD) debe ser mayor a cero", solution="Proporciona un costo unitario válido", - code="INVALID_VALUE" + code="INVALID_VALUE", ) if line.financial.unit_cost_mxn is not None: if line.financial.unit_cost_mxn <= 0: @@ -125,7 +117,7 @@ def validate_update( field="financial.unit_cost_mxn", message="Unit Cost (MXN) debe ser mayor a cero", solution="Proporciona un costo unitario válido", - code="INVALID_VALUE" + code="INVALID_VALUE", ) if line.financial.unit_cost_capture is not None: if line.financial.unit_cost_capture <= 0: @@ -133,19 +125,30 @@ def validate_update( field="financial.unit_cost_capture", message="Unit Cost (Captura) debe ser mayor a cero", solution="Proporciona un costo unitario válido", - code="INVALID_VALUE" + code="INVALID_VALUE", ) - + # 8. Validar datos aduanales si se proporcionan if line.customs: - # Validar país de origen - if line.customs.origin_country is not None and not line.customs.origin_country: - errors.add_error( - field="customs.origin_country", - message="Origin Country no puede estar vacío", - solution="Selecciona el país de origen del item", - code="REQUIRED" - ) + # Validar país de origen (OBLIGATORIO) + if line.customs.origin_country is not None: + if not line.customs.origin_country: + errors.add_error( + field="customs.origin_country", + message="País de Origen es obligatorio", + solution="Selecciona el país de origen del item", + code="REQUIRED" + ) + + # Validar tipo de tarifa (OBLIGATORIO) + if line.customs.fraction_type is not None: + if not line.customs.fraction_type: + errors.add_error( + field="customs.fraction_type", + message="Tipo de Tarifa es obligatorio", + solution="Selecciona el tipo de tarifa (GENERAL, PROSEC, ALADI, TLCS)", + code="REQUIRED" + ) # Validar preferencia arancelaria if line.customs.preference is not None and not line.customs.preference: @@ -153,46 +156,53 @@ def validate_update( field="customs.preference", message="La preferencia arancelaria no puede estar vacía", solution="Selecciona la preferencia arancelaria", - code="REQUIRED" + code="REQUIRED", ) - + # Validar formato de pago de impuestos if line.customs.tax_paid: val_tax = line.customs.tax_paid.upper() - if val_tax not in ['SI', 'NO', 'S', 'N']: + if val_tax not in ["SI", "NO", "S", "N"]: errors.add_error( field="customs.tax_paid", message="El valor de pago de impuesto debe ser SI/NO o S/N", solution="Proporciona un valor válido: SI, NO, S o N", - code="INVALID_VALUE" + code="INVALID_VALUE", ) - + # Validar forma de pago si existe if line.customs.payment_form: - from api.v1.modules.a76.general_catalogs.forms_of_payment.models import PaymentForm - - payment = db.query(PaymentForm).filter( - PaymentForm.code == line.customs.payment_form, - PaymentForm.tenant_id == tenant_id - ).first() - + from api.v1.modules.a76.general_catalogs.forms_of_payment.models import ( + PaymentForm, + ) + + payment = ( + db.query(PaymentForm) + .filter( + PaymentForm.code == line.customs.payment_form, + PaymentForm.tenant_id == tenant_id, + ) + .first() + ) + if not payment: errors.add_error( field="customs.payment_form", message=f"La forma de pago '{line.customs.payment_form}' no es válida", solution="Selecciona una forma de pago válida del catálogo", - code="INVALID_VALUE" + code="INVALID_VALUE", ) - # 9. Validar descripción en español si se proporciona + # 9. Validar descripción en español (OBLIGATORIA) if line.description and hasattr(line.description, 'description_spanish'): - if line.description.description_spanish is not None and not line.description.description_spanish: - errors.add_error( - field="description.description_spanish", - message="La descripción en español no puede estar vacía", - solution="Proporciona una descripción del item en español", - code="REQUIRED" - ) + if line.description.description_spanish is not None: + if not line.description.description_spanish.strip(): + errors.add_error( + field="description.description_spanish", + message="Descripción en Español es obligatoria", + solution="Proporciona una descripción del item en español", + code="REQUIRED" + ) # 10. Validar subpartidas si se actualizan if line.fa_data and line.fa_data.is_subitem: @@ -202,30 +212,35 @@ def validate_update( field="fa_data.main_line_id", message="La subpartida debe tener asignada una partida principal", solution="Selecciona la partida principal de esta subpartida", - code="REQUIRED" + code="REQUIRED", ) elif invoice_id: # Validar que la partida principal exista en la misma factura from api.v1.modules.a76.items.line_items.models import LineItem from api.v1.modules.a76.items.models import Item - - parent = db.query(LineItem).join(LineItem.item).filter( - LineItem.line_number == line.fa_data.main_line_id, - Item.invoice_id == invoice_id, - LineItem.company_id == company_id - ).first() - + + parent = ( + db.query(LineItem) + .join(LineItem.item) + .filter( + LineItem.line_number == line.fa_data.main_line_id, + Item.invoice_id == invoice_id, + LineItem.company_id == company_id, + ) + .first() + ) + if not parent: errors.add_error( field="fa_data.main_line_id", message=f"La partida principal {line.fa_data.main_line_id} no existe en esta factura", solution="Verifica el número de la partida principal", - code="NOT_FOUND" + code="NOT_FOUND", ) elif parent.fa_data and parent.fa_data.is_subitem: errors.add_error( field="fa_data.main_line_id", message="La partida principal no puede ser otra subpartida", solution="Selecciona una partida normal como principal", - code="INVALID_VALUE" + code="INVALID_VALUE", ) diff --git a/backend/api/v1/modules/a76/items/line_items/models.py b/backend/api/v1/modules/a76/items/line_items/models.py index 6ac7bee0..a7603d11 100644 --- a/backend/api/v1/modules/a76/items/line_items/models.py +++ b/backend/api/v1/modules/a76/items/line_items/models.py @@ -40,11 +40,11 @@ class LineItem(Base, TenantScopedMixin, TimestampMixin): line_number: Mapped[int] = mapped_column(Integer) # LINEAIMPO/LINEAEXPO/LINEA # Part identification - part_number: Mapped[Optional[str]] = mapped_column( - ForeignKey("a76.parts.id") + part_number: Mapped[Optional[int]] = mapped_column( + Integer, ForeignKey("a76.parts.id") ) # NUMPARTE - component_part_number: Mapped[Optional[str]] = mapped_column( - ForeignKey("a76.parts.id") + component_part_number: Mapped[Optional[int]] = mapped_column( + Integer, ForeignKey("a76.parts.id") ) # NUMPARTECOM class_id: Mapped[Optional[int]] = mapped_column( ForeignKey("a76.classes.id") diff --git a/backend/api/v1/modules/a76/items/line_items/schemas.py b/backend/api/v1/modules/a76/items/line_items/schemas.py index 0bea3647..5c23910a 100644 --- a/backend/api/v1/modules/a76/items/line_items/schemas.py +++ b/backend/api/v1/modules/a76/items/line_items/schemas.py @@ -44,22 +44,22 @@ from api.v1.modules.a24.fa.fa_item_lines.dto import ( class LineItemBase(BaseModel): """Base schema for line items""" + model_config = ConfigDict(populate_by_name=True) + line_number: int = Field(..., description="Line number") # Part identification - part_number_id: Optional[int] = Field(None, description="Part number") + part_number_id: Optional[int] = Field( + None, description="Part number", alias="part_number", serialization_alias="part_number_id" + ) component_part_number_id: Optional[int] = Field( - None, description="Component part number" + None, description="Component part number", alias="component_part_number", serialization_alias="component_part_number_id" ) class_id: Optional[int] = Field(None, description="Class code") # Unit of measure - unit_of_measure: Optional[int] = Field( - None, description="Unit of measure" - ) - alternate_unit: Optional[int] = Field( - None, description="Alternate unit" - ) + unit_of_measure: Optional[int] = Field(None, description="Unit of measure") + alternate_unit: Optional[int] = Field(None, description="Alternate unit") uma_key: Optional[str] = Field(None, max_length=2, description="UMA key") auxiliary_unit: Optional[str] = Field( None, max_length=5, description="Auxiliary unit" @@ -257,6 +257,12 @@ class LineItemResponse(LineItemBase): if hasattr(data, key): result[key] = getattr(data, key) + # Map model field names to schema field names for aliased fields + if hasattr(data, "part_number"): + result["part_number_id"] = data.part_number + if hasattr(data, "component_part_number"): + result["component_part_number_id"] = data.component_part_number + # Extract class info if hasattr(data, "class_info") and data.class_info is not None: result["class_code"] = data.class_info.class_code diff --git a/backend/api/v1/modules/a76/items/line_quantities/models.py b/backend/api/v1/modules/a76/items/line_quantities/models.py index c7a60558..24831f9d 100644 --- a/backend/api/v1/modules/a76/items/line_quantities/models.py +++ b/backend/api/v1/modules/a76/items/line_quantities/models.py @@ -4,6 +4,8 @@ from sqlalchemy import String, Integer, Numeric, SmallInteger, ForeignKey from sqlalchemy.orm import Mapped, mapped_column, relationship from core.database import Base +from api.v1.modules.a76.general_catalogs.packages.models import Package + if TYPE_CHECKING: from ..line_items.models import LineItem @@ -34,17 +36,17 @@ class LineQuantity(Base): serial_count: Mapped[Optional[int]] = mapped_column(Integer) # CANT_SERIES/CANT_SERIESDEF # Weight - weight_unit: Mapped[Optional[str]] = mapped_column(String(3)) # 'KG' o 'LB' net_weight: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8)) # PESONETO gross_weight: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8)) # PESOBRUTO + # Packaging - package_key: Mapped[Optional[str]] = mapped_column(String(5)) # CLAVEBULTOS + package_id: Mapped[Optional[int]] = mapped_column(ForeignKey("a76.packages.id")) package_quantity: Mapped[Optional[int]] = mapped_column(Integer) # CANTBULTOS - package_description: Mapped[Optional[str]] = mapped_column(String(40)) # DESCBULTOS container_quantity: Mapped[Optional[int]] = mapped_column(SmallInteger) # CANTBULCONT container_description: Mapped[Optional[str]] = mapped_column(String(40)) # DESCCONTENEDOR box_count: Mapped[Optional[str]] = mapped_column(String(30)) # NOCAJAS # Relationship (one-to-one) - line: Mapped["LineItem"] = relationship(back_populates="quantity") \ No newline at end of file + line: Mapped["LineItem"] = relationship(back_populates="quantity") + package_info: Mapped[Optional["Package"]] = relationship(Package) \ No newline at end of file diff --git a/backend/api/v1/modules/a76/items/line_quantities/schemas.py b/backend/api/v1/modules/a76/items/line_quantities/schemas.py index 71552342..f8582b99 100644 --- a/backend/api/v1/modules/a76/items/line_quantities/schemas.py +++ b/backend/api/v1/modules/a76/items/line_quantities/schemas.py @@ -22,14 +22,12 @@ class LineQuantityBase(BaseModel): serial_count: Optional[int] = Field(None, description="Serial count (CANT_SERIES/CANT_SERIESDEF)") # Weight - weight_unit: Optional[str] = Field(None, max_length=3, description="Weight unit ('KG' or 'LB')") net_weight: Optional[Decimal] = Field(None, description="Net weight (PESONETO)") gross_weight: Optional[Decimal] = Field(None, description="Gross weight (PESOBRUTO)") # Packaging - package_key: Optional[str] = Field(None, max_length=5, description="Package key (CLAVEBULTOS)") + package_id: Optional[int] = Field(None, description="Package ID (GBultos)") package_quantity: Optional[int] = Field(None, description="Package quantity (CANTBULTOS)") - package_description: Optional[str] = Field(None, max_length=40, description="Package description (DESCBULTOS)") container_quantity: Optional[int] = Field(None, description="Container quantity (CANTBULCONT)") container_description: Optional[str] = Field(None, max_length=40, description="Container description (DESCCONTENEDOR)") box_count: Optional[str] = Field(None, max_length=30, description="Box count (NOCAJAS)") diff --git a/backend/api/v1/modules/a76/items/service.py b/backend/api/v1/modules/a76/items/service.py index 2866fb3d..2efe582a 100644 --- a/backend/api/v1/modules/a76/items/service.py +++ b/backend/api/v1/modules/a76/items/service.py @@ -33,7 +33,7 @@ from api.v1.modules.a24.fa.fa_item_lines.models import FaLineItem from .models import Item from api.v1.modules.a76.invoices.models import InvoiceHeader from api.v1.modules.a76.general_catalogs.company.models import Company - + logger = logging.getLogger(__name__) @@ -158,79 +158,86 @@ class ItemService: company_id: int, ) -> Item: """Create a new item with all related nested data (multiple lines)""" - + # Validaciones con ErrorCollector errors = ErrorCollector() - + # Validar que la factura exista y no esté actualizada (si viene invoice_id) invoice = None if item_data.invoice_id: - invoice = db.query(InvoiceHeader).filter( - InvoiceHeader.id == item_data.invoice_id, - InvoiceHeader.tenant_id == tenant_id, - InvoiceHeader.company_id == company_id - ).first() - + invoice = ( + db.query(InvoiceHeader) + .filter( + InvoiceHeader.id == item_data.invoice_id, + InvoiceHeader.tenant_id == tenant_id, + InvoiceHeader.company_id == company_id, + ) + .first() + ) + if not invoice: errors.add_error( field="invoice_id", message="La factura especificada no existe", code="NOT_FOUND", - value=str(item_data.invoice_id) + value=str(item_data.invoice_id), ) - + # Validar cada line item que se va a crear if item_data.lines: for idx, line_data in enumerate(item_data.lines): # Convertir a LineItemCreate para validar line_create = LineItemCreate(**line_data.model_dump()) - + validate_create(db, line_create, tenant_id, company_id, errors) - + # Validaciones adicionales específicas del negocio - + # Validar apóstrofes en número de parte if line_data.part_number_id and "'" in str(line_data.part_number_id): errors.add_error( - field=f"lines[{idx}].part_number_id", + field=f"lines[{idx}].part_number", message=f"Advertencia: El Número de Parte contiene apóstrofes y serán omitidos", - code="WARNING_APOSTROPHE" + code="WARNING_APOSTROPHE", ) - + # Validar tipo de partida - if hasattr(line_data, 'item_type'): + if hasattr(line_data, "item_type"): tipo_partida = line_data.item_type - if tipo_partida and tipo_partida not in ['N', 'S']: + if tipo_partida and tipo_partida not in ["N", "S"]: errors.add_error( field=f"lines[{idx}].item_type", message=f"Tipo de partida debe ser 'N' (Normal) o 'S' (Subpartida), recibido: '{tipo_partida}'", code="INVALID_ITEM_TYPE", - value=str(tipo_partida) + value=str(tipo_partida), ) - + # Si es subpartida (S), debe tener partida principal - if tipo_partida == 'S': - if not hasattr(line_data, 'main_line_id') or not line_data.main_line_id: + if tipo_partida == "S": + if ( + not hasattr(line_data, "main_line_id") + or not line_data.main_line_id + ): errors.add_error( field=f"lines[{idx}].main_line_id", message="Las subpartidas (tipo 'S') deben tener una partida principal", - code="MISSING_MAIN_LINE" + code="MISSING_MAIN_LINE", ) - + # Validar que el line_number sea consecutivo (si se especifica) - if hasattr(line_data, 'line_number') and line_data.line_number: + if hasattr(line_data, "line_number") and line_data.line_number: expected_line = idx + 1 if line_data.line_number != expected_line: errors.add_error( field=f"lines[{idx}].line_number", message=f"Número de línea esperado: {expected_line}, recibido: {line_data.line_number}", code="INVALID_LINE_SEQUENCE", - value=str(line_data.line_number) + value=str(line_data.line_number), ) - + # Si hay errores, lanzar excepción ANTES de intentar crear errors.raise_if_errors("Error al crear el item") - + try: # Extract lines data lines_data = item_data.lines or [] @@ -269,6 +276,12 @@ class ItemService: line_dict["tenant_id"] = tenant_id line_dict["company_id"] = company_id + # Map schema field names to model field names + if "part_number_id" in line_dict: + line_dict["part_number"] = line_dict.pop("part_number_id") + if "component_part_number_id" in line_dict: + line_dict["component_part_number"] = line_dict.pop("component_part_number_id") + # Create line item db_line = LineItem(**line_dict) db.add(db_line) @@ -311,7 +324,9 @@ class ItemService: # Create FA data if provided if fa_data: - fa_dict = fa_data.model_dump(exclude={"line_item_id"}) # Exclude line_item_id from DTO + fa_dict = fa_data.model_dump( + exclude={"line_item_id"} + ) # Exclude line_item_id from DTO fa_dict["id"] = db_line.id # FA table uses same ID as line item fa_dict["tenant_id"] = tenant_id fa_dict["company_id"] = company_id @@ -343,47 +358,54 @@ class ItemService: company_id: int, ) -> Item: """Update an item and optionally its nested data (multiple lines)""" - + # Get existing item db_item = ItemService.get_by_id(db, item_id, tenant_id, company_id) if not db_item: raise HTTPException(status_code=404, detail="Item not found") - + # Validaciones con ErrorCollector errors = ErrorCollector() - + # Si se está actualizando el invoice_id, validar la factura invoice = None if item_data.invoice_id: - invoice = db.query(InvoiceHeader).filter( - InvoiceHeader.id == item_data.invoice_id, - InvoiceHeader.tenant_id == tenant_id, - InvoiceHeader.company_id == company_id - ).first() - + invoice = ( + db.query(InvoiceHeader) + .filter( + InvoiceHeader.id == item_data.invoice_id, + InvoiceHeader.tenant_id == tenant_id, + InvoiceHeader.company_id == company_id, + ) + .first() + ) + if not invoice: errors.add_error( field="invoice_id", message="La factura especificada no existe", code="NOT_FOUND", - value=str(item_data.invoice_id) + value=str(item_data.invoice_id), ) else: # Si no se está actualizando invoice_id, obtener la factura actual por invoice_id from api.v1.modules.a76.invoices.models import InvoiceHeader - invoice = db.query(InvoiceHeader).filter( - InvoiceHeader.id == db_item.invoice_id - ).first() - + + invoice = ( + db.query(InvoiceHeader) + .filter(InvoiceHeader.id == db_item.invoice_id) + .first() + ) + # Validar cada line item que se va a actualizar if item_data.lines: for idx, line_data in enumerate(item_data.lines): # Si el line tiene ID, es actualización; si no, es creación - if hasattr(line_data, 'id') and line_data.id: + if hasattr(line_data, "id") and line_data.id: # Buscar el line item existente existing_line = next( (line for line in db_item.lines if line.id == line_data.id), - None + None, ) if existing_line: # Convertir a LineItemUpdate para validar @@ -393,43 +415,46 @@ class ItemService: # Es un nuevo line item, validar como creación line_create = LineItemCreate(**line_data.model_dump()) validate_create(db, line_create, tenant_id, company_id, errors) - + # Validaciones adicionales específicas del negocio # (Aplican tanto para crear como actualizar) - + # Validar apóstrofes en número de parte if line_data.part_number_id and "'" in str(line_data.part_number_id): errors.add_error( - field=f"lines[{idx}].part_number_id", + field=f"lines[{idx}].part_number", message=f"Advertencia: El Número de Parte contiene apóstrofes y serán omitidos", solution=None, - code="WARNING_APOSTROPHE" + code="WARNING_APOSTROPHE", ) - + # Validar tipo de partida - if hasattr(line_data, 'item_type'): + if hasattr(line_data, "item_type"): tipo_partida = line_data.item_type - if tipo_partida and tipo_partida not in ['N', 'S']: + if tipo_partida and tipo_partida not in ["N", "S"]: errors.add_error( field=f"lines[{idx}].item_type", message=f"Tipo de partida debe ser 'N' (Normal) o 'S' (Subpartida), recibido: '{tipo_partida}'", solution=None, code="INVALID_ITEM_TYPE", - value=str(tipo_partida) + value=str(tipo_partida), ) - + # Si es subpartida (S), debe tener partida principal - if tipo_partida == 'S': - if not hasattr(line_data, 'main_line_id') or not line_data.main_line_id: + if tipo_partida == "S": + if ( + not hasattr(line_data, "main_line_id") + or not line_data.main_line_id + ): errors.add_error( field=f"lines[{idx}].main_line_id", message="Las subpartidas (tipo 'S') deben tener una partida principal", solution=None, - code="MISSING_MAIN_LINE" + code="MISSING_MAIN_LINE", ) - + # Validar que el line_number sea consecutivo (si se especifica) - if hasattr(line_data, 'line_number') and line_data.line_number: + if hasattr(line_data, "line_number") and line_data.line_number: expected_line = idx + 1 if line_data.line_number != expected_line: errors.add_error( @@ -437,12 +462,12 @@ class ItemService: message=f"Número de línea esperado: {expected_line}, recibido: {line_data.line_number}", solution=None, code="INVALID_LINE_SEQUENCE", - value=str(line_data.line_number) + value=str(line_data.line_number), ) - + # Si hay errores, lanzar excepción ANTES de actualizar errors.raise_if_errors("Error al actualizar el item") - + try: # Extract lines data @@ -485,6 +510,12 @@ class ItemService: line_dict["tenant_id"] = tenant_id line_dict["company_id"] = company_id + # Map schema field names to model field names + if "part_number_id" in line_dict: + line_dict["part_number"] = line_dict.pop("part_number_id") + if "component_part_number_id" in line_dict: + line_dict["component_part_number"] = line_dict.pop("component_part_number_id") + db_line = LineItem(**line_dict) db.add(db_line) db.flush() @@ -519,7 +550,9 @@ class ItemService: # Create FA data if provided if fa_data is not None: - fa_dict = fa_data.model_dump(exclude_unset=True, exclude={"line_item_id"}) + fa_dict = fa_data.model_dump( + exclude_unset=True, exclude={"line_item_id"} + ) fa_dict["id"] = db_line.id # FA table uses same ID as line item fa_dict["tenant_id"] = tenant_id fa_dict["company_id"] = company_id diff --git a/backend/api/v1/modules/a76/pedmientos/routes/pedimentos.py b/backend/api/v1/modules/a76/pedmientos/routes/pedimentos.py index d4edfaee..fbc8f887 100644 --- a/backend/api/v1/modules/a76/pedmientos/routes/pedimentos.py +++ b/backend/api/v1/modules/a76/pedmientos/routes/pedimentos.py @@ -16,7 +16,7 @@ router = TenantCRUDRoutes( prefix="", # No prefix here, will be added in main router tags=["a76 / pedimentos"], # Tag for Swagger documentation resource_name="Pedimento", - id_name="pedimento_id", + id_name="id", # Use standard REST convention enable_list=True, # Enable GET / with pagination enable_filters=True, # Enable status, client_id, year filters default_page_size=50, diff --git a/backend/api/v1/modules/a76/reports/exportacion/__init__.py b/backend/api/v1/modules/a76/reports/exportacion/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/__init__.py b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/routes.py b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/routes.py new file mode 100644 index 00000000..09cf878f --- /dev/null +++ b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/routes.py @@ -0,0 +1,46 @@ + +from typing import Dict, Any +from fastapi import APIRouter, Depends, Query +from sqlalchemy.orm import Session +from celery.result import AsyncResult +from core.celery_app import celery_app +from core.database import get_core_db +from core.security import get_current_user, validate_access_to_resource +from .task import generar_pdf_aviso_consolidado_exp_async + +router = APIRouter() + +@router.get("/tasks/{task_id}") +async def get_task_status( + task_id: str, + current_user: Dict[str, Any] = Depends(get_current_user), + db: Session = Depends(get_core_db) +): + task_result = AsyncResult(task_id, app=celery_app) + + response = { + "task_id": task_id, + "state": task_result.state, + "result": None, + "info": None + } + + if task_result.state == 'FAILURE': + response["result"] = str(task_result.result) + elif task_result.state == 'SUCCESS': + response["result"] = task_result.result + elif task_result.state == 'PROCESSING': + response["info"] = task_result.info + + return response + +@router.post("/{invoice_id}/download-async") +async def trigger_descarga_aviso_consolidado_exp( + invoice_id: int, + company_id: int = Query(..., description="ID de la empresa"), + current_user: Dict[str, Any] = Depends(get_current_user), + db: Session = Depends(get_core_db) +): + validate_access_to_resource(db, company_id, current_user) + task = generar_pdf_aviso_consolidado_exp_async.delay(invoice_id, company_id) + return {"task_id": task.id, "message": "Generación iniciada"} diff --git a/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/service.py b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/service.py new file mode 100644 index 00000000..9f96a81e --- /dev/null +++ b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/service.py @@ -0,0 +1,658 @@ + +import shutil +import base64 +import pdfkit +from pathlib import Path +from typing import Tuple, List, Callable, Optional, Dict, Any +from jinja2 import Environment, FileSystemLoader, select_autoescape +from fastapi import HTTPException +from sqlalchemy.orm import Session +from pydantic import BaseModel +from io import BytesIO +import pdf417gen + +# --- MODELOS --- +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceComplianceMx, InvoiceFinancials, InvoiceLogistics +from api.v1.modules.a76.general_catalogs.company.models import Company +from api.v1.modules.a76.pedmientos.models.pedimentos import Pedimentos +from api.v1.modules.a76.pedmientos.models.pedimento_validation import PedimentoValidation +from api.v1.modules.a76.customs_brokers.models import CustomsBroker, CustomsBrokerPersonnel +from api.v1.modules.a76.items.models import Item +from api.v1.modules.a76.clients_and_providers.models import ClientProvider, ClientProviderAddress, ClientProviderPrograms + +# --- SCHEMAS FOR TEMPLATE CONTEXT --- +class EmpresaSchema(BaseModel): + rfc: str + razon_social: str + direccion_completa: str + tax_id: Optional[str] = None # Extra info just in case + +class PersonaSchema(BaseModel): + nombre: str + rfc: str + curp: str + +class AvisoSchema(BaseModel): + pedimento_completo: str + tipo_operacion: str + clave_pedimento: str + acus_valor: str + aduana_seccion: str + numero_remesa: str + peso_bruto: str + codigo_aceptacion: str + codigo_barras_b64: Optional[str] = None + clave_seccion: str + marcas_numeros_bultos: str + candados: List[str] + vehiculo_placas: str + vehiculo_tipo: str + observaciones: str + numero_certificado: str + tipo_documento: str # NEW: Invoice Type + firma_electronica: str + +class AvisoConsolidadoContext(BaseModel): + aviso: AvisoSchema + empresa: EmpresaSchema + agente: PersonaSchema + mandatario: PersonaSchema + +class AvisoConsolidadoExportacionService: + def __init__(self): + self.template_dir = Path(__file__).parent / "templates" + self.jinja_env = Environment( + loader=FileSystemLoader(self.template_dir), + autoescape=select_autoescape(['html', 'xml']) + ) + self.template = self.jinja_env.get_template('avcon_exp.html') + + def _get_wkhtmltopdf_config(self): + path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" + if not Path(path).exists(): + raise RuntimeError("wkhtmltopdf no encontrado.") + return pdfkit.configuration(wkhtmltopdf=path) + + def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> AvisoConsolidadoContext: + try: + with open("/tmp/barcode_debug.log", "a") as f: f.write(f"ENTER obtener_datos ID={invoice_id}\n") + if progress_callback: progress_callback(10, "Buscando factura...") + + # Fetch minimal real data if possible, or use placeholders as requested + header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() + if not header: + # We can't strictly raise 404 if we want to support testing with non-existent IDs for pure UI check, + # but valid workflow requires a real invoice. Raising 404 is better practice. + raise HTTPException(status_code=404, detail="Factura no encontrada") + + company = db.query(Company).filter(Company.id == company_id).first() + + if progress_callback: progress_callback(30, "Preparando datos...") + + # --- FETCHING REAL DATA --- + + # 1. Compliance & Pedimento + compliance = header.compliance_mx + pedimento = None + if compliance and compliance.pedimento_id: + pedimento = db.query(Pedimentos).filter(Pedimentos.id == compliance.pedimento_id).first() + + # Pedimento Completo Construction + pedimento_txt = "S/P" + clave_ped = "" + if pedimento: + # Format: YY OFF LIC NUMBER + year = pedimento.year or "" + office = pedimento.customs_office or "" + lic = pedimento.license or "" + num = pedimento.pedimento_number or "" + pedimento_txt = f"{year} {office} {lic} {num}" + clave_ped = pedimento.pedimento_code or "" + + # 2. Importer/Exporter Data (Clarion 100% Match) + # Logic: + # IF EqiFex:EsCambioRegimen = 'S' THEN + # CliPro:Cliente = EqiFex:VendidoA + # ELSE + # CliPro:Cliente = EqiFex:Proveedor + # END + + target_entity_data = { + "rfc": "", + "razon_social": "", + "direccion_completa": "DOMICILIO NO REGISTRADO" + } + + target_client_id = None + + if compliance: + if compliance.is_regime_change: + target_client_id = compliance.sold_to_id + else: + target_client_id = compliance.provider_id + + if target_client_id: + client_obj = db.query(ClientProvider).filter(ClientProvider.id == target_client_id).first() + if client_obj: + # Fetch Address + c_addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == target_client_id).first() + # Fetch Fiscal Data (RFC) + c_prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == target_client_id).first() + + c_rfc = "" + if c_prog and c_prog.tax_id: c_rfc = c_prog.tax_id + elif hasattr(client_obj, 'rfc'): c_rfc = client_obj.rfc + + c_dir_str = "DOMICILIO NO REGISTRADO" + if c_addr: + parts_c = [] + if c_addr.streets: parts_c.append(c_addr.streets) + if c_addr.exterior_number: parts_c.append(f"No. {c_addr.exterior_number}") + if c_addr.interior_number: parts_c.append(f"Int. {c_addr.interior_number}") + if c_addr.neighborhood: parts_c.append(f"Col. {c_addr.neighborhood}") + if c_addr.postal_code: parts_c.append(f"CP {c_addr.postal_code}") + if c_addr.city: parts_c.append(c_addr.city) + if c_addr.state: parts_c.append(c_addr.state) + if c_addr.country: parts_c.append(c_addr.country) + + if parts_c: + c_dir_str = ", ".join(parts_c).upper() + + target_entity_data = { + "rfc": c_rfc or "", + "razon_social": client_obj.name or client_obj.short_name or "", + "direccion_completa": c_dir_str + } + + empresa = EmpresaSchema( + rfc=target_entity_data["rfc"], + razon_social=target_entity_data["razon_social"], + direccion_completa=target_entity_data["direccion_completa"] + ) + + # Destino/Origen (Clarion: Loc:DestinoOrigen = 'Destino/Origen: '&EqiFex:DestinoOrigenCOVE) + destino_origen_str = "" + if compliance and compliance.origin_destination_cove: + # Assuming enum value or string is what we want. + # If it's an Enum object, accessing .value is safer. + val = compliance.origin_destination_cove + if hasattr(val, 'value'): val = val.value + destino_origen_str = f"Destino/Origen: {val}" + + + + # 3. Datos Aviso (Invoice/Compliance/Logistics/Financials) + financials = header.financials + logistics = header.logistics + + # Fetch Items associated with this invoice (MOVED UP FOR WEIGHT CALCULATION) + items = db.query(Item).filter(Item.invoice_id == invoice_id).all() + + # Peso Bruto + peso_bruto_val = "0.0" + calculated_gross_weight = 0.0 + + # Calculate sum from items first + if items: + for item in items: + if item.lines: + for line in item.lines: + if line.quantity and line.quantity.gross_weight: + try: + calculated_gross_weight += float(line.quantity.gross_weight) + except (ValueError, TypeError): + pass + + if financials and financials.gross_weight and float(financials.gross_weight) > 0: + peso_bruto_val = f"{financials.gross_weight:,.2f}" + elif calculated_gross_weight > 0: + peso_bruto_val = f"{calculated_gross_weight:,.2f}" + elif pedimento and pedimento.gross_weight: + peso_bruto_val = f"{pedimento.gross_weight:,.2f}" + + # Candados (Seals) + candados_list = [] + if logistics and logistics.seal_number: + # Split by comma or space if multiple + candados_list = [s.strip() for s in logistics.seal_number.replace(',', ' ').split() if s.strip()] + + # Vehiculo / Contenedor Logic (Replicating Clarion) + # Clarion Logic: + # 1. Check for explicit `DatosVehiculo`. + # 2. Check for `EsFerrocarril`. + # 3. Build string from Trailer + Transport. + + # Since we don't have a direct "DatosVehiculo" text field in Logistics (usually), we construct it. + # However, we'll check if `license_plate` is being used as a catch-all or if we should build it. + + vehiculo_str = "" + tipo_display = "" + + # Basic Logistics Data + l_trailer = logistics.trailer_num.strip() if (logistics and logistics.trailer_num) else "" + l_placa = logistics.license_plate.strip() if (logistics and logistics.license_plate) else "" + l_trans_type = logistics.transport_type.strip() if (logistics and logistics.transport_type) else "" + l_vehicle_num = logistics.vehicle_num.strip() if (logistics and logistics.vehicle_num) else "" + l_container_types = logistics.container_types.strip() if (logistics and logistics.container_types) else "" + + # Check for Ferrocarril explicitly + is_rail = False + if "FERRO" in l_trans_type.upper() or "RAIL" in l_trans_type.upper(): + is_rail = True + + # --- LOGIC NUMERO / TIPO --- + final_numero = "" + final_tipo = "" + + # 1. Container Logic (Clarion: ContenedoresTipo parsing) + # Format expected: "CONTENEDOR|TIPO,CONTENEDOR2|TIPO2..." + if l_container_types: + # Take first container + first_cont_group = l_container_types.split(',')[0] # Split by comma + if '|' in first_cont_group: + parts = first_cont_group.split('|') + final_numero = parts[0].strip() + final_tipo = parts[1].strip() + else: + # Fallback if no pipe + final_numero = first_cont_group.strip() + final_tipo = "CONT" # Default? + + # 2. Transport = Container Logic + elif l_trans_type.upper() == "CONTENEDOR": + # Use trailer num as container num + if l_trailer: + final_numero = l_trailer + # Try to find Type? In Clarion it does a DB lookup into GTrailers.ClaveContenedor + # We assume 'CONTENEDOR' or a default if not found in simplified logic + final_tipo = "CONT" + + # 3. Trailer/General Logic (Fallback) + if not final_numero: + # Construct valid string + parts_veh = [] + if l_trailer: + parts_veh.append(f"TRAILER: {l_trailer}") + if not tipo_display: tipo_display = "TRAILER" + + if l_trans_type and l_trans_type.upper() != "NINGUNO": + if is_rail: + if l_vehicle_num: + parts_veh.append(f"CONTENEDOR: {l_vehicle_num}") + tipo_display = "FERROCARRIL" + else: + segment = l_trans_type + if l_vehicle_num: segment += f": {l_vehicle_num}" + parts_veh.append(segment) + if not tipo_display: tipo_display = l_trans_type + + if not parts_veh and l_placa: + parts_veh.append(f"PLACAS: {l_placa}") + + final_numero = ", ".join(parts_veh).upper() + final_tipo = tipo_display.upper() + + # Codigo de Aceptacion aka Acuse de Validacion + codigo_aceptacion_val = "" + if pedimento and pedimento.pedimento_validation: + # Assuming relationship "pedimento_validation" exists on Pedimentos model (lazy loaded) + # Or we can query it if relationship is scalar 'uselist=False' + if pedimento.pedimento_validation.validation_ack: + codigo_aceptacion_val = pedimento.pedimento_validation.validation_ack + + aviso = AvisoSchema( + pedimento_completo=pedimento_txt, + tipo_operacion=header.operation_type.upper() if header.operation_type else "EXP", + clave_pedimento=clave_ped, + acus_valor=compliance.edocument.upper() if (compliance and compliance.edocument) else "", + aduana_seccion=compliance.aduana if (compliance and compliance.aduana) else "", + numero_remesa=str(compliance.remesa) if (compliance and compliance.remesa) else "", + peso_bruto=peso_bruto_val, + codigo_aceptacion=codigo_aceptacion_val, + codigo_barras_b64=None, + clave_seccion=compliance.aduana if (compliance and compliance.aduana) else "", # Using Aduana as Section Key + marcas_numeros_bultos=f"{financials.bundle_count} BULTOS" if (financials and financials.bundle_count) else "1 BULTOS", + candados=candados_list, + vehiculo_placas=final_numero, + vehiculo_tipo=final_tipo, + observaciones=(header.observation_es or "") + ("\n" + destino_origen_str if destino_origen_str else ""), + numero_certificado=compliance.certificate_number if (compliance and compliance.certificate_number) else "", + tipo_documento=header.document_type or "FACTURA", # Default + firma_electronica=compliance.electronic_signature if (compliance and compliance.electronic_signature) else "" + ) + + # --- BARCODE GENERATION (PDF417) --- + # Replicating Clarion "LLENADOCODIGODEBARRAS" logic + try: + # Debug Log + debug_log = [] + debug_log.append(f"Processing Invoice {invoice_id}") + + # 1. Patente (4 Digits) - From Pedimento or Compliance + patente_txt = pedimento.license if pedimento and pedimento.license else "" + if not patente_txt and pedimento_txt: + # Fallback parsing "YY OFF LIC NUMBER" -> LIC is index 2 (0, 1, 2) + try: + parts = pedimento_txt.split() + if len(parts) >= 3: patente_txt = parts[2] + except: pass + + # 2. Pedimento Number (7 Digits) + pedimento_num = pedimento.pedimento_number if pedimento and pedimento.pedimento_number else "" + if not pedimento_num and pedimento_txt: + try: + parts = pedimento_txt.split() + if len(parts) >= 4: pedimento_num = parts[3] + except: pass + + # 3. Recinto (3 chars) - Default to 000 if invalid/missing as per Clarion 'ELSE LINEPRINT('000'...' + # Clarion: Loc:Recinto = EqiFex:Recinto + recinto_txt = "000" + if compliance and compliance.enclosure: + recinto_txt = compliance.enclosure[:3] + if not recinto_txt: recinto_txt = "000" + + # 4. E-Document + edoc_txt = aviso.acus_valor # Already uppercased + + # 5. Num Contenedor (Rail) or 000... + # Clarion: IF Loc:EsFerrocarril = 'SI' ... LINEPRINT(CLIP(Loc:NumContenedor)) ELSE LINEPRINT('0000000000000') + # We reused logic for 'vehiculo_placas' and 'vehiculo_tipo' earlier. + # Let's re-evaluate "EsFerrocarril" logic safely + is_rail_bar = False + if "FERRO" in final_tipo.upper() or "RAIL" in final_tipo.upper(): + is_rail_bar = True + + field_5 = "0000000000000" + if is_rail_bar: + # We extracted container into 'parts_veh' earlier but let's grab from raw if possible or from aviso? + # In our logic above: "CONTENEDOR: {l_vehicle_num}" was added to textual description. + # Let's use compliance.container_ids or logistics.vehicle_num + c_num = logistics.vehicle_num if logistics and logistics.vehicle_num else "" + if c_num: field_5 = c_num + + # 6. Firma Electronica + firma_txt = aviso.firma_electronica + + # 7. Cantidad Comercial (Format @n015.3 -> 15 chars total, 3 decimals?) + # We need to sum quantities. + cant_total = 0.0 + + if items: + for item in items: + if item.lines: + for line in item.lines: + # Priority: Quantity (UMA or Standard) + q = 0.0 + if line.quantity: + try: + if line.quantity.quantity_uma is not None: + q = float(line.quantity.quantity_uma) + elif line.quantity.quantity is not None: + q = float(line.quantity.quantity) + except (ValueError, TypeError): + q = 0.0 + cant_total += q + + # Format: 15 chars, 3 decimals? Actually Clarion LINEPRINT usually just prints the text. + # Clarion 'CLIP(FORMAT(Loc:CantTotal,@n015.3))' removes spaces. + cant_total_str = f"{cant_total:.3f}" + + + + # 8. Valor Total Dlls + # Clarion: LINEPRINT(FORMAT(Loc:ValorTotalDlls,@n012)) -> Integer? Or just standard? + # Clarion @n012 usually means right justified or just specific length? + # Code says: Loc:ValorTotalDlls = GSQLFile3.SQL3:C1 + (rounding logic). + val_usd = 0.0 + if financials: + try: + # Use value_me (Foreign Currency) as primary source for USD amount + if financials.value_me is not None: + val_usd = float(financials.value_me) + elif financials.value_mn is not None: + # Fallback to MN if ME is missing (though technically incorrect for USD field, avoids crash) + val_usd = float(financials.value_mn) + except (ValueError, TypeError): + val_usd = 0.0 + + # Clarion logic: + # IF GSQLFile3.SQL3:C1 > 0 AND GSQLFile3.SQL3:C1 < 1 THEN + # Loc:ValorTotalDlls = GSQLFile3.SQL3:C1 + (1 - GSQLFile3.SQL3:C1) (Result is 1.0) + # ELSE ... ROUND(...,1) or Raw. + + final_val_usd = val_usd + if 0.0 < val_usd < 1.0: + final_val_usd = 1.0 + elif (val_usd - int(val_usd)) > 0 and (val_usd - int(val_usd)) < 0.5: + # Clarion: IF Loc:Decimal > 0 AND Loc:Decimal < 0.5 THEN Loc:ValorTotalDlls = ROUND(GSQLFile3.SQL3:C1,1) + # Round to 1 decimal place? Or standard round? Python round matches generally. + final_val_usd = round(val_usd, 1) + + val_usd_str = f"{final_val_usd:.2f}" + + # 9. Cant Embarques (Rail) + field_9 = "000000000000" + if is_rail_bar: + # Logic for Cant Embarques? + # Clarion: EqiFex:CantGuiasEmbarque + # usage unknown in current DB. Defaulting to 0. + pass + + # 10. NIU / DTA (Rail) + field_10 = "0000000000000" + if is_rail_bar: + # Clarion: EqiFex:NumeroNIU + if compliance and compliance.niu: + field_10 = compliance.niu + + # 11. Remesa (4 chars) + remesa_txt = str(compliance.remesa) if (compliance and compliance.remesa) else "0" + + # 12. Filler + field_12 = "00000000.000" + + # Construct Line Prints (Text content for barcode) + # Clarion LINEPRINT separates by NewLine? Or is it one long string? + # "Glo:GeneraTXT" is a file. LINEPRINT appends a line. + # So the Barcode Content is a multi-line string or specific format. + # PDF417 normally encodes the full text block. + + # 1. Patente (4 Digits) + # Formatted: @P####P -> 4 digits. + # Assuming simple string slice or pad. + patente_formatted = f"{patente_txt}".strip()[:4] + + # 2. Pedimento (7 Digits) + pedimento_formatted = f"{pedimento_num}".strip()[:7] + + # 3. Recinto (3 Digits Zero Padded @n03) + # Ensure it's numeric-like for zero padding or just string pad? + # Clarion FORMAT(Loc:Recinto,@n03) implies numeric. + try: + recinto_val = int(recinto_txt) + recinto_formatted = f"{recinto_val:03d}" + except: + recinto_formatted = "000" + + # 4. E-Document (Left aligned, clipped) + edoc_formatted = edoc_txt.strip() + + # 5. Container (13 chars?) or Rail Logic + # Clarion: IF Rail -> CLIP(Loc:NumContenedor) ELSE '0000000000000' + if is_rail_bar and field_5 and len(field_5) > 0: + field_5_formatted = field_5.strip() + else: + field_5_formatted = "0000000000000" + + # 6. Firma (Clipped) + firma_formatted = firma_txt.strip() + + # 7. Cantidad (FORMAT(Loc:CantTotal,@n015.3)) -> 15 chars, 3 decimals, Zero Padded? + # Python f"{val:015.3f}" produces 15 chars total (including dot) with zero padding. + cant_total_formatted = f"{cant_total:015.3f}" + + # 8. Valor USD (FORMAT(Loc:ValorTotalDlls,@n012)) -> 12 chars, Integer?, Zero Padded? + # If Clarion @n012 means Integer: + # But previously we calculated rounding. If it is integer, we cast to int. + # Clarion default doubles formatted with @n012 usually rounds to integer. + # Let's assume Integer Zero Padded for now based on @n012 (no decimal part). + val_usd_formatted = f"{int(final_val_usd):012d}" + + # 9. Cant Embarques (Rail) (FORMAT(...,@n012)) + field_9_formatted = "000000000000" + if is_rail_bar: + # If we had a value... assuming 0 generally. + pass + + # 10. NIU (Rail) (@s13 -> String 13 chars?) or DTA + # Clarion: LINEPRINT(CLIP(FORMAT(Loc:NumeroNIU,@s13)),Glo:GeneraTXT) + # CLIP removes spaces, FORMAT @s13 makes it string 13? + # Actually CLIP(FORMAT(...,@s13)) might just mean "The string value". + # The ELSE is '0000000000000' (13 chars). + field_10_formatted = "0000000000000" + if is_rail_bar and field_10 != "0000000000000": + field_10_formatted = field_10.strip() + + # 11. Remesa (FORMAT(...,@n04) -> 4 digits zero padded) + try: + remesa_val = int(remesa_txt) + remesa_formatted = f"{remesa_val:04d}" + except: + remesa_formatted = "0000" + + # 12. Filler / Appendix 17 + # Clarion Logic: + # IF TipoFactura = 'IMPOTEMP'/'EXPO'/'IMPODEF' ... IF Apendice17=1 -> '000000000003' ELSE '00000000.000' + # Default '00000000.000' + field_12_formatted = "00000000.000" + if compliance and compliance.appendix_17 == 1: + # Check Doc Type? Assuming broadly for now based on flag. + field_12_formatted = "000000000003" + + barcode_lines = [ + patente_formatted, + pedimento_formatted, + recinto_formatted, + edoc_formatted, + field_5_formatted, + firma_formatted, + cant_total_formatted, + val_usd_formatted, + field_9_formatted, + field_10_formatted, + remesa_formatted, + field_12_formatted + ] + + # Join with appropriate separator. Clarion LINEPRINT adds CR/LF (Windows). + barcode_content = "\r\n".join(barcode_lines) + + # Generate Image + codes = pdf417gen.encode(barcode_content, columns=14) + image = pdf417gen.render_image(codes, scale=5, padding=5) + + # Convert to B64 + buffered = BytesIO() + image.save(buffered, format="PNG") + img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") + + aviso.codigo_barras_b64 = f"data:image/png;base64,{img_str}" + debug_log.append("SUCCESS: Barcode generated.") + + except Exception as e: + import traceback + error_msg = f"Error generando codigo de barras InvID={invoice_id}: {str(e)}\n{traceback.format_exc()}" + print(error_msg) + debug_log.append(f"ERROR: {error_msg}") + aviso.codigo_barras_b64 = None + + # Write Debug Log + try: + with open("/tmp/barcode_debug.log", "a") as f: + f.write("\n".join(debug_log) + "\n--------------------------------\n") + except Exception as e_log: + print(f"FAILED TO WRITE LOG: {e_log}") + + # 4. Agente Aduanal + nombre_agente = "" + rfc_agente = "" + curp_agente = "" + + if compliance and compliance.customs_broker_id: + broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() + if broker: + nombre_agente = broker.name or "" + rfc_agente = broker.tax_id or "" + curp_agente = broker.personal_id or "" + + agente = PersonaSchema( + nombre=nombre_agente, + rfc=rfc_agente, + curp=curp_agente + ) + + # 5. Mandatario (CustomsBrokerPersonnel) + mandatario = PersonaSchema(nombre="", rfc="", curp="") + + if broker: + # Try to find personnel associated with this broker + # Using direct query to ensure specific order if needed, typically just the first valid one + personnel = db.query(CustomsBrokerPersonnel).filter( + CustomsBrokerPersonnel.customs_broker_id == broker.id + ).first() + + if personnel: + # Construct name if main field is empty + full_name = personnel.name + if not full_name: + parts = [] + if personnel.first_name: parts.append(personnel.first_name) + if personnel.last_name: parts.append(personnel.last_name) + if personnel.middle_name: parts.append(personnel.middle_name) + full_name = " ".join(parts) + + mandatario = PersonaSchema( + nombre=full_name or "", + rfc=personnel.tax_id or "", + curp=personnel.personal_id or "" + ) + + return AvisoConsolidadoContext( + aviso=aviso, + empresa=empresa, + agente=agente, + mandatario=mandatario + ) + + except Exception as e: + print(f"Error Service A76 Export Aviso Consolidado: {e}") + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + def generar_pdf(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> Tuple[bytes, str, str]: + if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") + + datos = self.obtener_datos(db, invoice_id, company_id, progress_callback) + + if progress_callback: progress_callback(80, "Renderizando plantilla...") + + context = datos.model_dump() + html_content = self.template.render(**context) + nombre = f"AvisoConsolidado_Exp_{invoice_id}.pdf" + + if progress_callback: progress_callback(90, "Generando PDF final...") + + options = { + 'page-size': 'Letter', + 'margin-top': '0.5in', + 'margin-right': '0.5in', + 'margin-bottom': '0.5in', + 'margin-left': '0.5in', + 'encoding': "UTF-8", + 'enable-local-file-access': None + } + + pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) + + if progress_callback: progress_callback(100, "Completado") + return pdf, nombre, "application/pdf" diff --git a/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/task.py b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/task.py new file mode 100644 index 00000000..651919d4 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/task.py @@ -0,0 +1,50 @@ + +import base64 +import logging +from core.celery_app import celery_app +from core.database import CoreSessionLocal + +from .service import AvisoConsolidadoExportacionService + +logger = logging.getLogger(__name__) + +@celery_app.task(name="generar_pdf_aviso_consolidado_exp_async", bind=True) +def generar_pdf_aviso_consolidado_exp_async(self, invoice_id: int, company_id: int): + # 1. Abrimos conexión a la DB + db = CoreSessionLocal() + try: + logger.info(f"Worker procesando Aviso Consolidado Exp {invoice_id}...") + + # 2. Instanciamos el servicio + service = AvisoConsolidadoExportacionService() + + # Update state to PROCESSING + self.update_state(state='PROCESSING', meta={'current': 5, 'total': 100, 'status': 'Iniciando generación...'}) + + def progress_callback(progress: int, status: str): + self.update_state(state='PROCESSING', meta={'current': progress, 'total': 100, 'status': status}) + + # 3. Generamos los bytes del PDF + pdf_bytes, nombre, media_type = service.generar_pdf( + db=db, + invoice_id=invoice_id, + company_id=company_id, + progress_callback=progress_callback + ) + + # 4. Codificamos a base64 + pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8') + + return { + "status": "success", + "file_name": nombre, + "content": pdf_base64, + "media_type": media_type + } + + except Exception as e: + logger.error(f"Error en Celery Worker Aviso Consolidado Exp: {str(e)}") + return {"status": "error", "message": str(e)} + + finally: + db.close() diff --git a/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/templates/avcon_exp.html b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/templates/avcon_exp.html new file mode 100644 index 00000000..d24ba325 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/exportacion/aviso_consolidado/templates/avcon_exp.html @@ -0,0 +1,357 @@ + + + + + + Aviso Consolidado - {{ aviso.pedimento_completo }} + + + + + + + + + +
+

AVISO CONSOLIDADO

+
+

Página 1 de 1

+
+ + + + + + + + +
+ NUM. PEDIMENTO: + {{ aviso.pedimento_completo }} + + T. OPER: + {{ aviso.tipo_operacion }} + + CVE. PEDIMENTO: + {{ aviso.clave_pedimento }} + + CERTIFICACIONES +
+ TIPO: {{ aviso.tipo_documento }} +
+ + + + + + + + + + + + + + + + + +
+ NUMERO DE ACUSE DE VALOR: + {{ aviso.acus_valor }} + +

 

+
+ ADUANA E/S: + {{ aviso.aduana_seccion }} + + NUM. REMESA: + {{ aviso.numero_remesa }} + + PESO BRUTO: + {{ aviso.peso_bruto }} +
DATOS DEL IMPORTADOR/EXPORTADOR
+
+

RFC:

+

{{ empresa.rfc }}

+
+
+

NOMBRE, DENOMINACION O RAZON SOCIAL:

+

{{ empresa.razon_social }}

+

{{ empresa.direccion_completa }}

+
+
+ + + + + + + +
+

CODIGO DE ACEPTACION:

+

{{ aviso.codigo_aceptacion }}

+
+

CODIGO DE BARRAS

+
+ {% if aviso.codigo_barras_b64 %} + + {% else %} +


+ {% endif %} +
+
+

CLAVE DE LA SECCION ADUANERA DE DESPACHO:

+

{{ aviso.clave_seccion }}

+
+ + + + + + + + +
MARCAS, NUMEROS Y TOTAL DE BULTOS: +
+

{{ aviso.marcas_numeros_bultos }}

+
+ + + + + + + + + + +
NUMERO DE CANDADO: + {{ aviso.candados[0] if aviso.candados|length > 0 }}{{ aviso.candados[1] if aviso.candados|length > 1 }}{{ aviso.candados[2] if aviso.candados|length > 2 }}{{ aviso.candados[3] if aviso.candados|length > 3 }}{{ aviso.candados[4] if aviso.candados|length > 4 }}
+ + + + + + + + + + + + + + +
1RA. REVISION +
2DA. REVISION +
+ + + + + + + + +
NUMERO/TIPO:{{ aviso.vehiculo_placas }}{{ aviso.vehiculo_tipo }}
+ + + + + + + + +
OBSERVACIONES
+

{{ aviso.observaciones }}

+
+ + + + + +
+

AGENTE ADUANAL, APODERADO ADUANAL:

+ +
+ NOMBRE: + {{ agente.nombre }} +
+ +
+
+ RFC: + {{ agente.rfc }} +
+
+ CURP: + {{ agente.curp }} +
+
+ +
+ MANDATARIO/PERSONA AUTORIZADA: +
+ +
+ NOMBRE: + {{ mandatario.nombre }} +
+ +
+
+ RFC: + {{ mandatario.rfc }} +
+
+ CURP: + {{ mandatario.curp }} +
+
+ +
+ NUMERO DE SERIE DEL CERTIFICADO: + {{ aviso.numero_certificado }} +
+
+ e.firma: +

{{ aviso.firma_electronica }}

+
+
+ +

*********************************************************************** FIN DE LA + IMPRESION ***********************************************************************

+ + + + \ No newline at end of file diff --git a/backend/api/v1/modules/a76/reports/importacion/consolidados/mex/service.py b/backend/api/v1/modules/a76/reports/importacion/consolidados/mex/service.py index 5cff09b4..34cbc9ef 100644 --- a/backend/api/v1/modules/a76/reports/importacion/consolidados/mex/service.py +++ b/backend/api/v1/modules/a76/reports/importacion/consolidados/mex/service.py @@ -10,18 +10,24 @@ from fastapi import HTTPException from sqlalchemy.orm import Session # --- MODELOS --- -from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics, InvoiceComplianceMx +from api.v1.modules.a76.invoices.models import ( + InvoiceHeader, + InvoiceLogistics, + InvoiceComplianceMx, +) from api.v1.modules.a76.items.line_financials.models import LineFinancial from api.v1.modules.a76.items.line_quantities.models import LineQuantity from api.v1.modules.a76.items.line_items.models import LineItem from api.v1.modules.a76.clients_and_providers.models import ( - ClientProvider, ClientProviderAddress, ClientProviderPrograms + ClientProvider, + ClientProviderAddress, + ClientProviderPrograms, ) from api.v1.modules.a76.parts.models import Part from api.v1.modules.a76.pedmientos.models import Pedimentos from api.v1.modules.a76.general_catalogs.company.models import Company from api.v1.modules.a76.customs_brokers.models import CustomsBroker -from api.v1.modules.a76.items.models import Item +from api.v1.modules.a76.items.models import Item # --- TRANSPORTATION MODELS --- from api.v1.modules.a76.transportation.transporters.models import Transporter @@ -32,20 +38,27 @@ from api.v1.modules.a76.transportation.drivers.models import Driver # --- MODELO DE FRACCIONES --- from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction +# --- MODELO DE UNIDADES DE MEDIDA --- +from api.v1.modules.a76.general_catalogs.units_of_measure.models import UnitOfMeasure + # --- SCHEMAS --- from .schemas import ( - ClienteSchema, PartidaSchema, TotalesSchema, - FacturaSchema, FacturaImportacionCompleta + ClienteSchema, + PartidaSchema, + TotalesSchema, + FacturaSchema, + FacturaImportacionCompleta, ) + class ConsolidadoImportacionMexService: def __init__(self): self.template_dir = Path(__file__).parent.parent / "templates" self.jinja_env = Environment( loader=FileSystemLoader(self.template_dir), - autoescape=select_autoescape(['html', 'xml']) + autoescape=select_autoescape(["html", "xml"]), ) - self.template = self.jinja_env.get_template('cons_mex_ver.html') + self.template = self.jinja_env.get_template("cons_mex_ver.html") def _get_wkhtmltopdf_config(self): path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" @@ -54,28 +67,49 @@ class ConsolidadoImportacionMexService: return pdfkit.configuration(wkhtmltopdf=path) def formatear_numero(self, valor, decimales: int = 2): - if valor is None: return 0.0 + if valor is None: + return 0.0 try: return round(float(valor), decimales) - except: return 0.0 + except: + return 0.0 def _format_fraccion_fallback(self, fraccion_raw: str) -> str: if not fraccion_raw or len(fraccion_raw) < 8: return fraccion_raw return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" - def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + def _obtener_datos_cliente( + self, db: Session, client_id: int, rol: str + ) -> ClienteSchema: main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() if not main: - return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX") - - addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() - prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + return ClienteSchema( + header=rol, + nombre="Desconocido", + direccion="", + tax_id="", + codigo_postal="", + ciudad="", + estado="", + pais="MEX", + ) + + addr = ( + db.query(ClientProviderAddress) + .filter(ClientProviderAddress.client_id == client_id) + .first() + ) + prog = ( + db.query(ClientProviderPrograms) + .filter(ClientProviderPrograms.client_id == client_id) + .first() + ) return ClienteSchema( header=rol, nombre=(main.name or main.short_name) or "S/N", - direccion=(addr.streets or "") if addr else "", + direccion=(addr.streets or "") if addr else "", num_exterior=(addr.exterior_number or "") if addr else "", num_interior=(addr.interior_number or "") if addr else "", colonia=(addr.neighborhood or "") if addr else "", @@ -83,48 +117,115 @@ class ConsolidadoImportacionMexService: ciudad=(addr.city or "") if addr else "", estado=(addr.state or "") if addr else "", pais=(addr.country or "MEX") if addr else "MEX", - tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), - programa="IMMEX" if (prog and prog.program) else "", - autorizacion=prog.program_number if prog else "", - prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", - reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( - prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + tax_id=( + prog.tax_id + if (prog and prog.tax_id) + else (getattr(main, "rfc", "") or "") + ), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=( + prog.prosec_authorization + if (prog and prog.prosec and prog.prosec_authorization) + else "" + ), + reg_emp=( + prog.val_certified_company_registry + if (prog and hasattr(prog, "val_certified_company_registry")) + else ( + prog.certified_company_registry + if (prog and prog.certified_company_registry) + else "" + ) + ), + cert=( + prog.is_certified_company + if (prog and prog.is_certified_company) + else "" ), - cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" ) - def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> FacturaImportacionCompleta: + def obtener_datos( + self, + db: Session, + invoice_id: int, + company_id: int, + progress_callback: Optional[Callable] = None, + ) -> FacturaImportacionCompleta: try: - if progress_callback: progress_callback(10, "Buscando factura...") - header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() - if not header: raise HTTPException(status_code=404, detail="Factura no encontrada") + if progress_callback: + progress_callback(10, "Buscando factura...") + header = ( + db.query(InvoiceHeader) + .filter( + InvoiceHeader.id == invoice_id, + InvoiceHeader.company_id == company_id, + ) + .first() + ) + if not header: + raise HTTPException(status_code=404, detail="Factura no encontrada") - compliance = header.compliance_mx + compliance = header.compliance_mx logistics = header.logistics if header.logistics else None financials = header.financials if header.financials else None - if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...") - pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id - pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None - - if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...") + if progress_callback: + progress_callback(20, "Obteniendo datos de pedimento...") + pedimento_id = ( + compliance.pedimento_id + if (compliance and compliance.pedimento_id) + else header.related_doc_id + ) + pedimento = ( + db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() + if pedimento_id + else None + ) + + if progress_callback: + progress_callback(30, "Obteniendo cliente y proveedor...") proveedor_id = compliance.provider_id if compliance else None - cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + cliente_proveedor = ( + self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") + if proveedor_id + else ClienteSchema( + header="Proveedor", + nombre="No Asignado", + direccion="", + tax_id="", + codigo_postal="", + ciudad="", + estado="", + pais="", + ) + ) nombre_agente = "" if compliance and compliance.customs_broker_id: - broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() - if broker: nombre_agente = broker.name + broker = ( + db.query(CustomsBroker) + .filter(CustomsBroker.id == compliance.customs_broker_id) + .first() + ) + if broker: + nombre_agente = broker.name company = db.query(Company).filter(Company.id == header.company_id).first() # Datos Default (Company/Importer) - Used for fallback or Right Side (Enviado A) # Default Header (Company) cliente_default = ClienteSchema( header="Importer / Consignee:", - nombre=getattr(company, 'name', "Empresa Local"), + nombre=getattr(company, "name", "Empresa Local"), direccion="DOMICILIO FISCAL", - num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", - tax_id=getattr(company, 'rfc', ""), - programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + num_exterior="", + colonia="", + codigo_postal="", + ciudad="", + estado="", + pais="MEX", + tax_id=getattr(company, "rfc", ""), + programa=getattr(company, "program", "IMMEX"), + autorizacion=getattr(company, "program_number", ""), ) # Left Side Logic (Consignatario / Sold To) @@ -136,34 +237,49 @@ class ConsolidadoImportacionMexService: clean_header = "Consignee / Consignatario:" else: clean_header = "Sold To / Vendido a:" - - cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) - + + cliente_vendido = self._obtener_datos_cliente( + db, compliance.sold_to_id, clean_header + ) + # Right Side Logic (Enviado A / Shipped To) cliente_enviado = cliente_default if compliance and compliance.shipped_to_id: # Map to Shipped To / Enviado a clean_header_shipped = "Shipped To / Enviado a:" - - # Fetch client data - cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) - remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" - acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + # Fetch client data + cliente_enviado = self._obtener_datos_cliente( + db, compliance.shipped_to_id, clean_header_shipped + ) + + remesa_valor = ( + str(compliance.remesa) if (compliance and compliance.remesa) else "" + ) + acuse_valor = ( + str(compliance.edocument) + if (compliance and compliance.edocument) + else "N/A" + ) patente_val = "" if pedimento and pedimento.license: patente_val = pedimento.license - elif 'broker' in locals() and broker and broker.license: + elif "broker" in locals() and broker and broker.license: patente_val = broker.license - # --- Transport Data Fetching --- - transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + transporte_txt = ( + str(logistics.transport_type) + if (logistics and logistics.transport_type) + else "" + ) num_transporte_val = (logistics.trailer_num or "") if logistics else "" - + # Init values - placas_val = (logistics.license_plate or "") if logistics else "" # Placas Tracto + placas_val = ( + (logistics.license_plate or "") if logistics else "" + ) # Placas Tracto placas_remolque_val = "" transportista_val = (logistics.carrier_id or "") if logistics else "" caat_val = "" @@ -177,54 +293,74 @@ class ConsolidadoImportacionMexService: if logistics: # 1. Transporter (CAAT / SCAC) if logistics.carrier_id: - transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + transporter_obj = ( + db.query(Transporter) + .filter(Transporter.transporter_key == logistics.carrier_id) + .first() + ) if transporter_obj: caat_val = transporter_obj.caat_code or "" - scac_val = transporter_obj.transport_code or "" # Mapping transport_code to SCAC + scac_val = ( + transporter_obj.transport_code or "" + ) # Mapping transport_code to SCAC transportista_val = transporter_obj.name or logistics.carrier_id # Clarion Logic: Name first # Line 1: Name transport_lines.append(transporter_obj.name or "") - + # Line 2: Streets if transporter_obj.streets: transport_lines.append(transporter_obj.streets) - + # Line 3: City, State, Country loc_line = "" if transporter_obj.city: - loc_line = transporter_obj.city - if transporter_obj.state: - loc_line += f", {transporter_obj.state}, " - else: - loc_line += ", " + loc_line = transporter_obj.city + if transporter_obj.state: + loc_line += f", {transporter_obj.state}, " + else: + loc_line += ", " else: - if transporter_obj.state: - loc_line = f"{transporter_obj.state}," - - country_desc = transporter_obj.country or "" + if transporter_obj.state: + loc_line = f"{transporter_obj.state}," + + country_desc = transporter_obj.country or "" if loc_line: loc_line += f" {country_desc}" elif country_desc: loc_line = country_desc - + if loc_line.strip(", "): transport_lines.append(loc_line) # 2. Vehicle (Placas Tracto) - Try transport_id first if logistics.transport_id: - veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + veh_obj = ( + db.query(Vehicle) + .filter(Vehicle.vehicle_key == logistics.transport_id) + .first() + ) if veh_obj: - placas_val = veh_obj.plate_number or placas_val - elif logistics.vehicle_num: # Fallback to vehicle_num if populated and transport_id failed/empty - veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() - if veh_obj: - placas_val = veh_obj.plate_number or placas_val + placas_val = veh_obj.plate_number or placas_val + elif ( + logistics.vehicle_num + ): # Fallback to vehicle_num if populated and transport_id failed/empty + veh_obj = ( + db.query(Vehicle) + .filter(Vehicle.vehicle_key == logistics.vehicle_num) + .first() + ) + if veh_obj: + placas_val = veh_obj.plate_number or placas_val # 3. Trailer (Placas Remolque) if logistics.trailer_num: - trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + trl_obj = ( + db.query(Trailer) + .filter(Trailer.trailer_number == logistics.trailer_num) + .first() + ) if trl_obj: placas_remolque_val = trl_obj.plate_number or "" @@ -232,36 +368,40 @@ class ConsolidadoImportacionMexService: if logistics.carrier_id and logistics.driver_name: conductor_nombre = logistics.driver_name # Attempt to find driver by name + carrier - drv_obj = db.query(Driver).filter( - Driver.transporter_key == logistics.carrier_id, - Driver.driver_name == logistics.driver_name - ).first() + drv_obj = ( + db.query(Driver) + .filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name, + ) + .first() + ) if drv_obj: - licencia_cond_val = drv_obj.license_number or "" - + licencia_cond_val = drv_obj.license_number or "" + # --- Building the rest of the block --- - + # Line 4: Driver if conductor_nombre: - transport_lines.append(f"Driver/Conductor: {conductor_nombre}") - + transport_lines.append(f"Driver/Conductor: {conductor_nombre}") + # Line 5: Conveyance / Transporte t_label = "Conveyance / Transporte" - t_val = placas_val # Default to Truck Plate - + t_val = placas_val # Default to Truck Plate + if logistics.transport_type: ttype = str(logistics.transport_type).lower() if "caja" in ttype or "trailer" in ttype: t_label = "Trailer / Caja" t_val = placas_remolque_val or num_transporte_val elif "placa" in ttype: - t_label = "Plates / Placas" + t_label = "Plates / Placas" elif "camion" in ttype or "truck" in ttype: - t_label = "Truck / Camión" - + t_label = "Truck / Camión" + if t_val: - transport_lines.append(f"{t_label}: {t_val}") - + transport_lines.append(f"{t_label}: {t_val}") + # Line 6: SCAC / CAAT codes_line = "" if scac_val: @@ -271,9 +411,9 @@ class ConsolidadoImportacionMexService: codes_line += f", CAAT Code/Clave: {caat_val}" else: codes_line = f"CAAT Code/Clave: {caat_val}" - + if codes_line: - transport_lines.append(codes_line) + transport_lines.append(codes_line) # Join with newlines transport_block_str = "\n".join([l for l in transport_lines if l]) @@ -281,11 +421,23 @@ class ConsolidadoImportacionMexService: factura_schema = FacturaSchema( numero=header.invoice_number or "S/N", fecha=str(header.invoice_date) if header.invoice_date else "", - tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), - moneda=getattr(header, 'currency', "USD") or "USD", + tipo_cambio=( + float(financials.exchange_rate) + if (financials and financials.exchange_rate) + else ( + float(pedimento.exchange_rate) + if pedimento and pedimento.exchange_rate + else 1.0 + ) + ), + moneda=getattr(header, "currency", "USD") or "USD", incoterm=(logistics.incoterm or "") if logistics else "", observaciones=header.observation_es or header.observation_en or "", - pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + pedimento=( + f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" + if pedimento + else "" + ), clave_pedimento=pedimento.pedimento_code if pedimento else "", regimen=header.document_type or "", patente=patente_val, @@ -298,68 +450,104 @@ class ConsolidadoImportacionMexService: caat=caat_val, scac=scac_val, licencia_conductor=licencia_cond_val, - aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + aduana=( + compliance.aduana + if (compliance and compliance.aduana) + else ( + pedimento.customs_office[:2] + if (pedimento and pedimento.customs_office) + else "" + ) + ), precinto=(logistics.seal_number or "") if logistics else "", destino=(logistics.destination_goods or "") if logistics else "", - remesa=remesa_valor, acuse_electronico=acuse_valor, - representante_legal=getattr(company, 'responsible', "") or "", - nombre_empresa=getattr(company, 'name', "") or "", - transportista_info=transport_block_str + remesa=remesa_valor, + acuse_electronico=acuse_valor, + representante_legal=getattr(company, "responsible", "") or "", + nombre_empresa=getattr(company, "name", "") or "", + transportista_info=transport_block_str, ) - - if progress_callback: progress_callback(50, "Procesando partidas...") - + + if progress_callback: + progress_callback(50, "Procesando partidas...") + # --- Fetch Lines from SINGLE Invoice (Requested Scope Change) --- # User requested to ONLY report items from the specific selected invoice, # NOT consolidating all invoices from the same Pedimento. target_invoice_ids = [header.id] - - lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter( - Item.invoice_id.in_(target_invoice_ids) - ).all() + + lines = ( + db.query(LineItem) + .join(Item, LineItem.item_id == Item.id) + .filter(Item.invoice_id.in_(target_invoice_ids)) + .all() + ) partidas_list = [] - + # --- AGGREGATION LOGIC (Refactoring based on Clarion) --- from collections import defaultdict + # Key: (us_fraction_code, origin_country) # Value: Object with accumulated fields - aggregated_data = defaultdict(lambda: { - "qty": 0.0, - "net_weight_kgs": 0.0, - "gross_weight_kgs": 0.0, - "total_value": 0.0, - "est_total_value": 0.0, - "description": "", - "advalorem_txt": "0%", - "unit_measure": "PZA", # Placeholder, takes first one found - "hts_code_print": "", - "part_number_display": "CONSOLIDADO" - }) + aggregated_data = defaultdict( + lambda: { + "qty": 0.0, + "net_weight_kgs": 0.0, + "gross_weight_kgs": 0.0, + "total_value": 0.0, + "est_total_value": 0.0, + "description": "", + "advalorem_txt": "0%", + "unit_measure": "PZA", # Placeholder, takes first one found + "hts_code_print": "", + "part_number_display": "CONSOLIDADO", + } + ) # Pre-fetch US Tariff Fractions for efficiency if possible, or query inside loop (caching recommended) - # For simplicity in this step, we query inside or rely on Part data. + # For simplicity in this step, we query inside or rely on Part data. # Ideally fetch USTariffFraction from DB based on Part.us_fraction # --- Optimización: Cargar Facturas en Memoria --- - invoices_list = db.query(InvoiceHeader).filter(InvoiceHeader.id.in_(target_invoice_ids)).all() + invoices_list = ( + db.query(InvoiceHeader) + .filter(InvoiceHeader.id.in_(target_invoice_ids)) + .all() + ) invoice_map = {inv.id: inv for inv in invoices_list} - from api.v1.modules.a76.general_catalogs.us_tariff_fractions.models import USTariffFraction + from api.v1.modules.a76.general_catalogs.us_tariff_fractions.models import ( + USTariffFraction, + ) for line in lines: - qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() - fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() + qty = ( + db.query(LineQuantity) + .filter(LineQuantity.item_line_id == line.id) + .first() + ) + fin = ( + db.query(LineFinancial) + .filter(LineFinancial.item_line_id == line.id) + .first() + ) part_master = db.query(Part).filter(Part.id == line.part_number).first() - + # --- Resolver Identificadores (MOVED INSIDE MAIN LOOP) --- us_fraction_raw = "" origin_final = "MEX" - + if part_master: - origin_final = part_master.fa_data.origin_country if (part_master.fa_data and part_master.fa_data.origin_country) else "MEX" - us_fraction_raw = part_master.us_fraction if part_master.us_fraction else "" - + origin_final = ( + part_master.fa_data.origin_country + if (part_master.fa_data and part_master.fa_data.origin_country) + else "MEX" + ) + us_fraction_raw = ( + part_master.us_fraction if part_master.us_fraction else "" + ) + # Key for aggregation us_frac_clean = us_fraction_raw.strip() agg_key = (us_frac_clean, origin_final) @@ -367,13 +555,13 @@ class ConsolidadoImportacionMexService: q_line = float(qty.quantity) if (qty and qty.quantity) else 0.0 nw_line = float(qty.net_weight) if qty else 0.0 gw_line = float(qty.gross_weight) if qty else 0.0 - + # --- Multi-Currency Normalization Logic --- # Determine Line Currency context # Use manual lookup instead of specific attribute invoice_id = line.item.invoice_id if line.item else None line_invoice = invoice_map.get(invoice_id) if invoice_id else None - + line_currency_is_mxn = False line_exchange_rate = 1.0 @@ -381,30 +569,36 @@ class ConsolidadoImportacionMexService: # Check explicit currency string AND code curr_desc = str(line_invoice.financials.currency or "").upper() curr_code = str(line_invoice.financials.currency_type or "").upper() - + # Logic: It is MXN if description says PESO/MX or code is MXN/MN - is_mx_desc = ("MX" in curr_desc or "PESO" in curr_desc) - is_mx_code = ("MXN" in curr_code or "MN" == curr_code) - + is_mx_desc = "MX" in curr_desc or "PESO" in curr_desc + is_mx_code = "MXN" in curr_code or "MN" == curr_code + # But if code allows clarifying USD, prioritize that - is_usd_code = ("USD" in curr_code) - + is_usd_code = "USD" in curr_code + if is_usd_code: line_currency_is_mxn = False elif is_mx_code or is_mx_desc: line_currency_is_mxn = True else: - line_currency_is_mxn = False # Default to Foreign/USD if unsure + line_currency_is_mxn = False # Default to Foreign/USD if unsure + + line_exchange_rate = float( + line_invoice.financials.exchange_rate or 1.0 + ) - line_exchange_rate = float(line_invoice.financials.exchange_rate or 1.0) - # Target Report Currency - report_is_mxn = (factura_schema.moneda == 'MXN') + report_is_mxn = factura_schema.moneda == "MXN" # DEBUG LOGGING if line_invoice: - print(f"DEBUG: Line {line.id} - Inv {line_invoice.id} - CurrDesc: '{curr_desc}' Code: '{curr_code}' - Rate: {line_exchange_rate}") - print(f"DEBUG: Is MXN Context? {line_currency_is_mxn}. Report is MXN? {report_is_mxn}") + print( + f"DEBUG: Line {line.id} - Inv {line_invoice.id} - CurrDesc: '{curr_desc}' Code: '{curr_code}' - Rate: {line_exchange_rate}" + ) + print( + f"DEBUG: Is MXN Context? {line_currency_is_mxn}. Report is MXN? {report_is_mxn}" + ) # --- Get Financials for Line (Raw) --- v_total_raw = 0.0 @@ -421,11 +615,11 @@ class ConsolidadoImportacionMexService: total_comm = float(fin.total_commercial_value or 0.0) unit_comm_usd = float(fin.unit_cost_commercial_usd or 0.0) unit_usd = float(fin.unit_cost_usd or 0.0) - + # 1. Direct Total: Custom Value (Best case) if val_usd > 0: v_total_raw = val_usd - + # 2. Direct Total: Commercial Total elif total_comm > 0: # Convert if invoice currency is MXN @@ -433,18 +627,18 @@ class ConsolidadoImportacionMexService: v_total_raw = total_comm / line_exchange_rate else: v_total_raw = total_comm - + # 3. Calc from Commercial Unit Cost (Safe Fallback) elif unit_comm_usd > 0 and q_line > 0: v_total_raw = unit_comm_usd * q_line - + # 4. Calc from Customs Unit Cost (Unknown Risk - Last Resort) elif unit_usd > 0 and q_line > 0: v_total_raw = unit_usd * q_line - + else: v_total_raw = 0.0 - + # NOTE: v_unitario_raw is left as 0.0 here. # It will be calculated in the 'Calculation Gap Fill' block below: # v_unitario_raw = v_total_raw / q_line @@ -474,40 +668,70 @@ class ConsolidadoImportacionMexService: # else: # v_total_line = 0.0 # v_unitario_line = 0.0 - + print(f"DEBUG: ValRaw: {v_total_raw} -> ValFinal: {v_total_line}") - + # --- Resolve Fraction Details (Description & Rate) --- # Only if this is the first time we see this key (or overwrite, doesn't matter much as they should be same for same HTS) - # We check if we already have description set to avoid re-querying if we want optimization, + # We check if we already have description set to avoid re-querying if we want optimization, # but relying on DB query per distinct fraction is safer. - + current_agg = aggregated_data[agg_key] - + if not current_agg["description"]: - us_frac_db = db.query(USTariffFraction).filter(USTariffFraction.code == us_frac_clean).first() + us_frac_db = ( + db.query(USTariffFraction) + .filter(USTariffFraction.code == us_frac_clean) + .first() + ) if us_frac_db: - current_agg["description"] = us_frac_db.description or "Sin Descripción" - # Parse AdValorem from DB if available, else 0 ?? - # Creating logical placeholder. The provided Clarion code used `FraAme.Adv` - adv_val = us_frac_db.ad_valorem # Assuming field exists based on viewing file later? - # Wait, in us-tariff-fractions.ts I saw `ad_valorem: number | null`. - current_agg["advalorem_txt"] = f"{adv_val}%" if adv_val is not None else "0%" + current_agg["description"] = ( + us_frac_db.description or "Sin Descripción" + ) + # Parse AdValorem from DB if available, else 0 ?? + # Creating logical placeholder. The provided Clarion code used `FraAme.Adv` + adv_val = ( + us_frac_db.ad_valorem + ) # Assuming field exists based on viewing file later? + # Wait, in us-tariff-fractions.ts I saw `ad_valorem: number | null`. + current_agg["advalorem_txt"] = ( + f"{adv_val}%" if adv_val is not None else "0%" + ) else: - current_agg["description"] = part_master.description_spanish if part_master else "S/D" + current_agg["description"] = ( + part_master.description_spanish if part_master else "S/D" + ) current_agg["hts_code_print"] = us_frac_clean - current_agg["unit_measure"] = qty.weight_unit if qty else "KGS" # Default to first found + + # Obtener descripción de la unidad de medida desde la tabla a76.item_lines + if line.unit_of_measure: + uom = ( + db.query(UnitOfMeasure) + .filter( + UnitOfMeasure.id == line.unit_of_measure, + UnitOfMeasure.company_id == company_id, + ) + .first() + ) + current_agg["unit_measure"] = ( + uom.description + if (uom and uom.description) + else (uom.code if uom else "KGS") + ) + else: + current_agg["unit_measure"] = "KGS" # Default fallback # --- Calculate Estimated Tax for this Line --- rate = 0.0 try: clean_adv = current_agg["advalorem_txt"].replace("%", "").strip() rate = float(clean_adv) / 100.0 - except: rate = 0.0 - + except: + rate = 0.0 + v_est_line = v_total_line * rate - + # --- Accumulate --- current_agg["qty"] += q_line current_agg["net_weight_kgs"] += nw_line @@ -515,51 +739,59 @@ class ConsolidadoImportacionMexService: current_agg["total_value"] += v_total_line current_agg["est_total_value"] += v_est_line - # --- Convert Aggregated Data to Schema List --- partidas_list = [] - + for (hts, origin), data in aggregated_data.items(): - + # Calculate Unit Price based on Total Value / Total Qty unit_price = 0.0 if data["qty"] > 0: unit_price = data["total_value"] / data["qty"] - - partidas_list.append(PartidaSchema( - numero_parte="VARIOS", # Or empty - descripcion=data["description"], - fraccion=data["hts_code_print"], - origen=origin, - advalorem=data["advalorem_txt"], - preferencia="General", - cantidad_importacion=self.formatear_numero(data["qty"]), - unidad_medida=data["unit_measure"], - cantidad_bultos=0, # Summing bultos might be tricky if not homogeneous, check logic later - clave_bultos="", - peso_neto=self.formatear_numero(data["net_weight_kgs"]), - peso_bruto=self.formatear_numero(data["gross_weight_kgs"]), - valor_costo_unitario=self.formatear_numero(unit_price), - valor_total=self.formatear_numero(data["total_value"]), - valor_estimado=self.formatear_numero(data["est_total_value"]) - )) - + + partidas_list.append( + PartidaSchema( + numero_parte="VARIOS", # Or empty + descripcion=data["description"], + fraccion=data["hts_code_print"], + origen=origin, + advalorem=data["advalorem_txt"], + preferencia="General", + cantidad_importacion=self.formatear_numero(data["qty"]), + unidad_medida=data["unit_measure"], + cantidad_bultos=0, # Summing bultos might be tricky if not homogeneous, check logic later + clave_bultos="", + peso_neto=self.formatear_numero(data["net_weight_kgs"]), + peso_bruto=self.formatear_numero(data["gross_weight_kgs"]), + valor_costo_unitario=self.formatear_numero(unit_price), + valor_total=self.formatear_numero(data["total_value"]), + valor_estimado=self.formatear_numero(data["est_total_value"]), + ) + ) + # Sort by Fraction (HTS Code) partidas_list.sort(key=lambda x: x.fraccion) - totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + totales = self.calcular_totales( + partidas_list, Decimal(factura_schema.tipo_cambio) + ) return FacturaImportacionCompleta( - cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, - cliente_enviado=cliente_enviado, factura=factura_schema, - partidas=partidas_list, totales=totales + cliente_proveedor=cliente_proveedor, + cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, + factura=factura_schema, + partidas=partidas_list, + totales=totales, ) except Exception as e: print(f"Error Service A76: {e}") raise HTTPException(status_code=500, detail=f"Error: {str(e)}") - def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + def calcular_totales( + self, partidas: List[PartidaSchema], tipo_cambio: Decimal + ) -> TotalesSchema: cant = sum(p.cantidad_importacion for p in partidas) valor = sum(p.valor_total for p in partidas) peso_n = sum(p.peso_neto for p in partidas) @@ -567,23 +799,41 @@ class ConsolidadoImportacionMexService: bultos = sum(p.cantidad_bultos for p in partidas) claves = [p.clave_bultos for p in partidas if p.clave_bultos] clave_comun = max(set(claves), key=claves.count) if claves else "" - if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" - v_est = sum(p.valor_estimado for p in partidas if isinstance(p.valor_estimado, (int, float, Decimal))) - - tc = float(tipo_cambio) if tipo_cambio else 1.0 - return TotalesSchema( - cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, - peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), - valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0), - valor_estimado_total=self.formatear_numero(v_est) + if bultos > 1 and clave_comun and not clave_comun.endswith("S"): + clave_comun += "S" + v_est = sum( + p.valor_estimado + for p in partidas + if isinstance(p.valor_estimado, (int, float, Decimal)) ) - def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None) -> Tuple[bytes, str, str]: - if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") + tc = float(tipo_cambio) if tipo_cambio else 1.0 + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), + bultos_total=bultos, + clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), + peso_bruto_total=self.formatear_numero(peso_b), + valor_total_total=self.formatear_numero(valor), + valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0), + valor_estimado_total=self.formatear_numero(v_est), + ) + + def generar_factura_completa( + self, + db: Session, + invoice_id: int, + company_id: int, + formato: str = "pdf", + progress_callback: Optional[Callable] = None, + ) -> Tuple[bytes, str, str]: + if progress_callback: + progress_callback(5, "Iniciando servicio de reporte...") datos = self.obtener_datos(db, invoice_id, company_id, progress_callback) - - if progress_callback: progress_callback(80, "Renderizando plantilla...") - + + if progress_callback: + progress_callback(80, "Renderizando plantilla...") + # LOGO LOGIC logo_b64 = None try: @@ -592,7 +842,7 @@ class ConsolidadoImportacionMexService: comp_logo = db.query(Company).filter(Company.id == company_id).first() if comp_logo and comp_logo.logo: p = Path(comp_logo.logo) - + # Logic robusta de búsqueda (igual que en routes.py) target_path = p if not target_path.exists(): @@ -604,27 +854,49 @@ class ConsolidadoImportacionMexService: if target_path.exists(): with open(target_path, "rb") as image_file: - encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + encoded_string = base64.b64encode(image_file.read()).decode( + "utf-8" + ) # Detect MIME type loosely mime = "image/png" - if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + if target_path.suffix.lower() in [".jpg", ".jpeg"]: + mime = "image/jpeg" logo_b64 = f"data:{mime};base64,{encoded_string}" except Exception as e: print(f"Error loading logo: {e}") context = { - 'cliente_proveedor': datos.cliente_proveedor.model_dump(), 'cliente_vendido': datos.cliente_vendido.model_dump(), - 'cliente_enviado': datos.cliente_enviado.model_dump(), 'factura': datos.factura.model_dump(), - 'partidas': [p.model_dump() for p in datos.partidas], 'totales': datos.totales.model_dump(), - 'logo_b64': logo_b64 + "cliente_proveedor": datos.cliente_proveedor.model_dump(), + "cliente_vendido": datos.cliente_vendido.model_dump(), + "cliente_enviado": datos.cliente_enviado.model_dump(), + "factura": datos.factura.model_dump(), + "partidas": [p.model_dump() for p in datos.partidas], + "totales": datos.totales.model_dump(), + "logo_b64": logo_b64, } html_content = self.template.render(**context) nombre = f"Consolidado_{datos.factura.numero}.{formato}" - if formato == "html": return html_content.encode('utf-8'), nombre, "text/html" - - if progress_callback: progress_callback(90, "Generando PDF final...") - options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} - pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) - - if progress_callback: progress_callback(100, "Completado") + if formato == "html": + return html_content.encode("utf-8"), nombre, "text/html" + + if progress_callback: + progress_callback(90, "Generando PDF final...") + options = { + "page-size": "Letter", + "margin-top": "0.5in", + "margin-right": "0.5in", + "margin-bottom": "0.5in", + "margin-left": "0.5in", + "encoding": "UTF-8", + "enable-local-file-access": None, + } + pdf = pdfkit.from_string( + html_content, + False, + options=options, + configuration=self._get_wkhtmltopdf_config(), + ) + + if progress_callback: + progress_callback(100, "Completado") return pdf, nombre, "application/pdf" diff --git a/backend/api/v1/modules/a76/reports/importacion/consolidados/temporary/mex/service.py b/backend/api/v1/modules/a76/reports/importacion/consolidados/temporary/mex/service.py new file mode 100644 index 00000000..5cff09b4 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/consolidados/temporary/mex/service.py @@ -0,0 +1,630 @@ +import shutil +import base64 +import pdfkit +from pathlib import Path +from decimal import Decimal +from typing import Tuple, List, Callable, Optional + +from jinja2 import Environment, FileSystemLoader, select_autoescape +from fastapi import HTTPException +from sqlalchemy.orm import Session + +# --- MODELOS --- +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics, InvoiceComplianceMx +from api.v1.modules.a76.items.line_financials.models import LineFinancial +from api.v1.modules.a76.items.line_quantities.models import LineQuantity +from api.v1.modules.a76.items.line_items.models import LineItem +from api.v1.modules.a76.clients_and_providers.models import ( + ClientProvider, ClientProviderAddress, ClientProviderPrograms +) +from api.v1.modules.a76.parts.models import Part +from api.v1.modules.a76.pedmientos.models import Pedimentos +from api.v1.modules.a76.general_catalogs.company.models import Company +from api.v1.modules.a76.customs_brokers.models import CustomsBroker +from api.v1.modules.a76.items.models import Item + +# --- TRANSPORTATION MODELS --- +from api.v1.modules.a76.transportation.transporters.models import Transporter +from api.v1.modules.a76.transportation.vehicles.models import Vehicle +from api.v1.modules.a76.transportation.trailers.models import Trailer +from api.v1.modules.a76.transportation.drivers.models import Driver + +# --- MODELO DE FRACCIONES --- +from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction + +# --- SCHEMAS --- +from .schemas import ( + ClienteSchema, PartidaSchema, TotalesSchema, + FacturaSchema, FacturaImportacionCompleta +) + +class ConsolidadoImportacionMexService: + def __init__(self): + self.template_dir = Path(__file__).parent.parent / "templates" + self.jinja_env = Environment( + loader=FileSystemLoader(self.template_dir), + autoescape=select_autoescape(['html', 'xml']) + ) + self.template = self.jinja_env.get_template('cons_mex_ver.html') + + def _get_wkhtmltopdf_config(self): + path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" + if not Path(path).exists(): + raise RuntimeError("wkhtmltopdf no encontrado.") + return pdfkit.configuration(wkhtmltopdf=path) + + def formatear_numero(self, valor, decimales: int = 2): + if valor is None: return 0.0 + try: + return round(float(valor), decimales) + except: return 0.0 + + def _format_fraccion_fallback(self, fraccion_raw: str) -> str: + if not fraccion_raw or len(fraccion_raw) < 8: + return fraccion_raw + return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" + + def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() + if not main: + return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX") + + addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() + prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + + return ClienteSchema( + header=rol, + nombre=(main.name or main.short_name) or "S/N", + direccion=(addr.streets or "") if addr else "", + num_exterior=(addr.exterior_number or "") if addr else "", + num_interior=(addr.interior_number or "") if addr else "", + colonia=(addr.neighborhood or "") if addr else "", + codigo_postal=(addr.postal_code or "") if addr else "", + ciudad=(addr.city or "") if addr else "", + estado=(addr.state or "") if addr else "", + pais=(addr.country or "MEX") if addr else "MEX", + tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", + reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( + prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + ), + cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" + ) + + def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> FacturaImportacionCompleta: + try: + if progress_callback: progress_callback(10, "Buscando factura...") + header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() + if not header: raise HTTPException(status_code=404, detail="Factura no encontrada") + + compliance = header.compliance_mx + logistics = header.logistics if header.logistics else None + financials = header.financials if header.financials else None + if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...") + pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id + pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None + + if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...") + proveedor_id = compliance.provider_id if compliance else None + cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + + nombre_agente = "" + if compliance and compliance.customs_broker_id: + broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() + if broker: nombre_agente = broker.name + + company = db.query(Company).filter(Company.id == header.company_id).first() + # Datos Default (Company/Importer) - Used for fallback or Right Side (Enviado A) + # Default Header (Company) + cliente_default = ClienteSchema( + header="Importer / Consignee:", + nombre=getattr(company, 'name', "Empresa Local"), + direccion="DOMICILIO FISCAL", + num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", + tax_id=getattr(company, 'rfc', ""), + programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + ) + + # Left Side Logic (Consignatario / Sold To) + cliente_vendido = cliente_default + if compliance and compliance.sold_to_id: + # Map known headers or default to Sold To / Vendido a + raw = (compliance.sold_to_header or "").upper() + if "CONSIGN" in raw: + clean_header = "Consignee / Consignatario:" + else: + clean_header = "Sold To / Vendido a:" + + cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) + + # Right Side Logic (Enviado A / Shipped To) + cliente_enviado = cliente_default + if compliance and compliance.shipped_to_id: + # Map to Shipped To / Enviado a + clean_header_shipped = "Shipped To / Enviado a:" + + # Fetch client data + cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) + + remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" + acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + + patente_val = "" + if pedimento and pedimento.license: + patente_val = pedimento.license + elif 'broker' in locals() and broker and broker.license: + patente_val = broker.license + + + # --- Transport Data Fetching --- + transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + num_transporte_val = (logistics.trailer_num or "") if logistics else "" + + # Init values + placas_val = (logistics.license_plate or "") if logistics else "" # Placas Tracto + placas_remolque_val = "" + transportista_val = (logistics.carrier_id or "") if logistics else "" + caat_val = "" + scac_val = "" + licencia_cond_val = "" + conductor_nombre = "" + + # Block Logic (Clarion Style) for transportista_info + transport_lines = [] + + if logistics: + # 1. Transporter (CAAT / SCAC) + if logistics.carrier_id: + transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + if transporter_obj: + caat_val = transporter_obj.caat_code or "" + scac_val = transporter_obj.transport_code or "" # Mapping transport_code to SCAC + transportista_val = transporter_obj.name or logistics.carrier_id + + # Clarion Logic: Name first + # Line 1: Name + transport_lines.append(transporter_obj.name or "") + + # Line 2: Streets + if transporter_obj.streets: + transport_lines.append(transporter_obj.streets) + + # Line 3: City, State, Country + loc_line = "" + if transporter_obj.city: + loc_line = transporter_obj.city + if transporter_obj.state: + loc_line += f", {transporter_obj.state}, " + else: + loc_line += ", " + else: + if transporter_obj.state: + loc_line = f"{transporter_obj.state}," + + country_desc = transporter_obj.country or "" + if loc_line: + loc_line += f" {country_desc}" + elif country_desc: + loc_line = country_desc + + if loc_line.strip(", "): + transport_lines.append(loc_line) + + # 2. Vehicle (Placas Tracto) - Try transport_id first + if logistics.transport_id: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + elif logistics.vehicle_num: # Fallback to vehicle_num if populated and transport_id failed/empty + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + + # 3. Trailer (Placas Remolque) + if logistics.trailer_num: + trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + if trl_obj: + placas_remolque_val = trl_obj.plate_number or "" + + # 4. Driver (License) + if logistics.carrier_id and logistics.driver_name: + conductor_nombre = logistics.driver_name + # Attempt to find driver by name + carrier + drv_obj = db.query(Driver).filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name + ).first() + if drv_obj: + licencia_cond_val = drv_obj.license_number or "" + + # --- Building the rest of the block --- + + # Line 4: Driver + if conductor_nombre: + transport_lines.append(f"Driver/Conductor: {conductor_nombre}") + + # Line 5: Conveyance / Transporte + t_label = "Conveyance / Transporte" + t_val = placas_val # Default to Truck Plate + + if logistics.transport_type: + ttype = str(logistics.transport_type).lower() + if "caja" in ttype or "trailer" in ttype: + t_label = "Trailer / Caja" + t_val = placas_remolque_val or num_transporte_val + elif "placa" in ttype: + t_label = "Plates / Placas" + elif "camion" in ttype or "truck" in ttype: + t_label = "Truck / Camión" + + if t_val: + transport_lines.append(f"{t_label}: {t_val}") + + # Line 6: SCAC / CAAT + codes_line = "" + if scac_val: + codes_line = f"SCAC Code/Clave: {scac_val}" + if caat_val: + if codes_line: + codes_line += f", CAAT Code/Clave: {caat_val}" + else: + codes_line = f"CAAT Code/Clave: {caat_val}" + + if codes_line: + transport_lines.append(codes_line) + + # Join with newlines + transport_block_str = "\n".join([l for l in transport_lines if l]) + + factura_schema = FacturaSchema( + numero=header.invoice_number or "S/N", + fecha=str(header.invoice_date) if header.invoice_date else "", + tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), + moneda=getattr(header, 'currency', "USD") or "USD", + incoterm=(logistics.incoterm or "") if logistics else "", + observaciones=header.observation_es or header.observation_en or "", + pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + clave_pedimento=pedimento.pedimento_code if pedimento else "", + regimen=header.document_type or "", + patente=patente_val, + agente_aduanal=nombre_agente, + transporte=transporte_txt, + num_transporte=num_transporte_val, + placas=placas_val, + placas_remolque=placas_remolque_val, + transportista=transportista_val, + caat=caat_val, + scac=scac_val, + licencia_conductor=licencia_cond_val, + aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + precinto=(logistics.seal_number or "") if logistics else "", + destino=(logistics.destination_goods or "") if logistics else "", + remesa=remesa_valor, acuse_electronico=acuse_valor, + representante_legal=getattr(company, 'responsible', "") or "", + nombre_empresa=getattr(company, 'name', "") or "", + transportista_info=transport_block_str + ) + + if progress_callback: progress_callback(50, "Procesando partidas...") + + # --- Fetch Lines from SINGLE Invoice (Requested Scope Change) --- + # User requested to ONLY report items from the specific selected invoice, + # NOT consolidating all invoices from the same Pedimento. + target_invoice_ids = [header.id] + + lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter( + Item.invoice_id.in_(target_invoice_ids) + ).all() + + partidas_list = [] + + # --- AGGREGATION LOGIC (Refactoring based on Clarion) --- + from collections import defaultdict + # Key: (us_fraction_code, origin_country) + # Value: Object with accumulated fields + aggregated_data = defaultdict(lambda: { + "qty": 0.0, + "net_weight_kgs": 0.0, + "gross_weight_kgs": 0.0, + "total_value": 0.0, + "est_total_value": 0.0, + "description": "", + "advalorem_txt": "0%", + "unit_measure": "PZA", # Placeholder, takes first one found + "hts_code_print": "", + "part_number_display": "CONSOLIDADO" + }) + + # Pre-fetch US Tariff Fractions for efficiency if possible, or query inside loop (caching recommended) + # For simplicity in this step, we query inside or rely on Part data. + # Ideally fetch USTariffFraction from DB based on Part.us_fraction + + # --- Optimización: Cargar Facturas en Memoria --- + invoices_list = db.query(InvoiceHeader).filter(InvoiceHeader.id.in_(target_invoice_ids)).all() + invoice_map = {inv.id: inv for inv in invoices_list} + + from api.v1.modules.a76.general_catalogs.us_tariff_fractions.models import USTariffFraction + + for line in lines: + qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() + fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() + part_master = db.query(Part).filter(Part.id == line.part_number).first() + + # --- Resolver Identificadores (MOVED INSIDE MAIN LOOP) --- + us_fraction_raw = "" + origin_final = "MEX" + + if part_master: + origin_final = part_master.fa_data.origin_country if (part_master.fa_data and part_master.fa_data.origin_country) else "MEX" + us_fraction_raw = part_master.us_fraction if part_master.us_fraction else "" + + # Key for aggregation + us_frac_clean = us_fraction_raw.strip() + agg_key = (us_frac_clean, origin_final) + # --- Weights & Qty --- + q_line = float(qty.quantity) if (qty and qty.quantity) else 0.0 + nw_line = float(qty.net_weight) if qty else 0.0 + gw_line = float(qty.gross_weight) if qty else 0.0 + + # --- Multi-Currency Normalization Logic --- + # Determine Line Currency context + # Use manual lookup instead of specific attribute + invoice_id = line.item.invoice_id if line.item else None + line_invoice = invoice_map.get(invoice_id) if invoice_id else None + + line_currency_is_mxn = False + line_exchange_rate = 1.0 + + if line_invoice and line_invoice.financials: + # Check explicit currency string AND code + curr_desc = str(line_invoice.financials.currency or "").upper() + curr_code = str(line_invoice.financials.currency_type or "").upper() + + # Logic: It is MXN if description says PESO/MX or code is MXN/MN + is_mx_desc = ("MX" in curr_desc or "PESO" in curr_desc) + is_mx_code = ("MXN" in curr_code or "MN" == curr_code) + + # But if code allows clarifying USD, prioritize that + is_usd_code = ("USD" in curr_code) + + if is_usd_code: + line_currency_is_mxn = False + elif is_mx_code or is_mx_desc: + line_currency_is_mxn = True + else: + line_currency_is_mxn = False # Default to Foreign/USD if unsure + + line_exchange_rate = float(line_invoice.financials.exchange_rate or 1.0) + + # Target Report Currency + report_is_mxn = (factura_schema.moneda == 'MXN') + + # DEBUG LOGGING + if line_invoice: + print(f"DEBUG: Line {line.id} - Inv {line_invoice.id} - CurrDesc: '{curr_desc}' Code: '{curr_code}' - Rate: {line_exchange_rate}") + print(f"DEBUG: Is MXN Context? {line_currency_is_mxn}. Report is MXN? {report_is_mxn}") + + # --- Get Financials for Line (Raw) --- + v_total_raw = 0.0 + v_unitario_raw = 0.0 + + if fin: + # NEW PRIORITY LOGIC (To avoid Inflation from dirty Customs Unit Cost) + # Priority 1: Use 'fin.value_usd' if it exists and > 0. + # Priority 2: Use 'fin.total_commercial_value' if it exists and > 0. + # Priority 3: Calculate using 'fin.unit_cost_commercial_usd' * 'q_line'. + # Priority 4: Only use 'fin.unit_cost_usd' * 'q_line' if commercial data is also missing. + + val_usd = float(fin.value_usd or 0.0) + total_comm = float(fin.total_commercial_value or 0.0) + unit_comm_usd = float(fin.unit_cost_commercial_usd or 0.0) + unit_usd = float(fin.unit_cost_usd or 0.0) + + # 1. Direct Total: Custom Value (Best case) + if val_usd > 0: + v_total_raw = val_usd + + # 2. Direct Total: Commercial Total + elif total_comm > 0: + # Convert if invoice currency is MXN + if line_currency_is_mxn and line_exchange_rate > 0: + v_total_raw = total_comm / line_exchange_rate + else: + v_total_raw = total_comm + + # 3. Calc from Commercial Unit Cost (Safe Fallback) + elif unit_comm_usd > 0 and q_line > 0: + v_total_raw = unit_comm_usd * q_line + + # 4. Calc from Customs Unit Cost (Unknown Risk - Last Resort) + elif unit_usd > 0 and q_line > 0: + v_total_raw = unit_usd * q_line + + else: + v_total_raw = 0.0 + + # NOTE: v_unitario_raw is left as 0.0 here. + # It will be calculated in the 'Calculation Gap Fill' block below: + # v_unitario_raw = v_total_raw / q_line + # This guarantees consistency and avoids the inflated unit cost record (198.00). + + # --- Calculation Gap Fill (Raw) --- + if q_line > 0: + if v_total_raw == 0 and v_unitario_raw > 0: + v_total_raw = v_unitario_raw * q_line + if v_unitario_raw == 0 and v_total_raw > 0: + v_unitario_raw = v_total_raw / q_line + + # --- Conversion to Report Currency (DISABLED TEMPORARILY) --- + # User confirms all are USD. Forcing direct sum to avoid logic errors in detection. + v_total_line = v_total_raw + v_unitario_line = v_unitario_raw + + # if report_is_mxn and not line_currency_is_mxn: + # # USD -> MXN + # v_total_line = v_total_raw * line_exchange_rate + # v_unitario_line = v_unitario_raw * line_exchange_rate + # elif not report_is_mxn and line_currency_is_mxn: + # # MXN -> USD + # if line_exchange_rate > 0: + # v_total_line = v_total_raw / line_exchange_rate + # v_unitario_line = v_unitario_raw / line_exchange_rate + # else: + # v_total_line = 0.0 + # v_unitario_line = 0.0 + + print(f"DEBUG: ValRaw: {v_total_raw} -> ValFinal: {v_total_line}") + + # --- Resolve Fraction Details (Description & Rate) --- + # Only if this is the first time we see this key (or overwrite, doesn't matter much as they should be same for same HTS) + # We check if we already have description set to avoid re-querying if we want optimization, + # but relying on DB query per distinct fraction is safer. + + current_agg = aggregated_data[agg_key] + + if not current_agg["description"]: + us_frac_db = db.query(USTariffFraction).filter(USTariffFraction.code == us_frac_clean).first() + if us_frac_db: + current_agg["description"] = us_frac_db.description or "Sin Descripción" + # Parse AdValorem from DB if available, else 0 ?? + # Creating logical placeholder. The provided Clarion code used `FraAme.Adv` + adv_val = us_frac_db.ad_valorem # Assuming field exists based on viewing file later? + # Wait, in us-tariff-fractions.ts I saw `ad_valorem: number | null`. + current_agg["advalorem_txt"] = f"{adv_val}%" if adv_val is not None else "0%" + else: + current_agg["description"] = part_master.description_spanish if part_master else "S/D" + + current_agg["hts_code_print"] = us_frac_clean + current_agg["unit_measure"] = qty.weight_unit if qty else "KGS" # Default to first found + + # --- Calculate Estimated Tax for this Line --- + rate = 0.0 + try: + clean_adv = current_agg["advalorem_txt"].replace("%", "").strip() + rate = float(clean_adv) / 100.0 + except: rate = 0.0 + + v_est_line = v_total_line * rate + + # --- Accumulate --- + current_agg["qty"] += q_line + current_agg["net_weight_kgs"] += nw_line + current_agg["gross_weight_kgs"] += gw_line + current_agg["total_value"] += v_total_line + current_agg["est_total_value"] += v_est_line + + + # --- Convert Aggregated Data to Schema List --- + partidas_list = [] + + for (hts, origin), data in aggregated_data.items(): + + # Calculate Unit Price based on Total Value / Total Qty + unit_price = 0.0 + if data["qty"] > 0: + unit_price = data["total_value"] / data["qty"] + + partidas_list.append(PartidaSchema( + numero_parte="VARIOS", # Or empty + descripcion=data["description"], + fraccion=data["hts_code_print"], + origen=origin, + advalorem=data["advalorem_txt"], + preferencia="General", + cantidad_importacion=self.formatear_numero(data["qty"]), + unidad_medida=data["unit_measure"], + cantidad_bultos=0, # Summing bultos might be tricky if not homogeneous, check logic later + clave_bultos="", + peso_neto=self.formatear_numero(data["net_weight_kgs"]), + peso_bruto=self.formatear_numero(data["gross_weight_kgs"]), + valor_costo_unitario=self.formatear_numero(unit_price), + valor_total=self.formatear_numero(data["total_value"]), + valor_estimado=self.formatear_numero(data["est_total_value"]) + )) + + # Sort by Fraction (HTS Code) + partidas_list.sort(key=lambda x: x.fraccion) + + totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + + return FacturaImportacionCompleta( + cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, factura=factura_schema, + partidas=partidas_list, totales=totales + ) + + except Exception as e: + print(f"Error Service A76: {e}") + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + cant = sum(p.cantidad_importacion for p in partidas) + valor = sum(p.valor_total for p in partidas) + peso_n = sum(p.peso_neto for p in partidas) + peso_b = sum(p.peso_bruto for p in partidas) + bultos = sum(p.cantidad_bultos for p in partidas) + claves = [p.clave_bultos for p in partidas if p.clave_bultos] + clave_comun = max(set(claves), key=claves.count) if claves else "" + if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" + v_est = sum(p.valor_estimado for p in partidas if isinstance(p.valor_estimado, (int, float, Decimal))) + + tc = float(tipo_cambio) if tipo_cambio else 1.0 + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), + valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0), + valor_estimado_total=self.formatear_numero(v_est) + ) + + def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None) -> Tuple[bytes, str, str]: + if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") + datos = self.obtener_datos(db, invoice_id, company_id, progress_callback) + + if progress_callback: progress_callback(80, "Renderizando plantilla...") + + # LOGO LOGIC + logo_b64 = None + try: + # Fetch company to get logo path + + comp_logo = db.query(Company).filter(Company.id == company_id).first() + if comp_logo and comp_logo.logo: + p = Path(comp_logo.logo) + + # Logic robusta de búsqueda (igual que en routes.py) + target_path = p + if not target_path.exists(): + # Intentar en la ruta estándar: app_data/logos/{id}/{nombre} + # Esto cubre el caso donde solo se guardó el nombre del archivo o la ruta absoluta cambió + fallback = Path(f"app_data/logos/{company_id}") / p.name + if fallback.exists(): + target_path = fallback + + if target_path.exists(): + with open(target_path, "rb") as image_file: + encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + # Detect MIME type loosely + mime = "image/png" + if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + logo_b64 = f"data:{mime};base64,{encoded_string}" + except Exception as e: + print(f"Error loading logo: {e}") + + context = { + 'cliente_proveedor': datos.cliente_proveedor.model_dump(), 'cliente_vendido': datos.cliente_vendido.model_dump(), + 'cliente_enviado': datos.cliente_enviado.model_dump(), 'factura': datos.factura.model_dump(), + 'partidas': [p.model_dump() for p in datos.partidas], 'totales': datos.totales.model_dump(), + 'logo_b64': logo_b64 + } + html_content = self.template.render(**context) + nombre = f"Consolidado_{datos.factura.numero}.{formato}" + if formato == "html": return html_content.encode('utf-8'), nombre, "text/html" + + if progress_callback: progress_callback(90, "Generando PDF final...") + options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} + pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) + + if progress_callback: progress_callback(100, "Completado") + return pdf, nombre, "application/pdf" diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/mex/schemas.py b/backend/api/v1/modules/a76/reports/importacion/facturas/mex/schemas.py index 9d4455b8..e9a52c8a 100644 --- a/backend/api/v1/modules/a76/reports/importacion/facturas/mex/schemas.py +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/mex/schemas.py @@ -30,6 +30,7 @@ class ClienteSchema(BaseModel): class FacturaSchema(BaseModel): numero: str + titulo_documento: str = "Factura de Importacion" # Titulo dinámico basado en document_type fecha: str tipo_cambio: float moneda: str diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/mex/service.py b/backend/api/v1/modules/a76/reports/importacion/facturas/mex/service.py index 200a3942..619ae2f5 100644 --- a/backend/api/v1/modules/a76/reports/importacion/facturas/mex/service.py +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/mex/service.py @@ -10,18 +10,20 @@ from fastapi import HTTPException from sqlalchemy.orm import Session # --- MODELOS --- -from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics from api.v1.modules.a76.items.line_financials.models import LineFinancial from api.v1.modules.a76.items.line_quantities.models import LineQuantity from api.v1.modules.a76.items.line_items.models import LineItem from api.v1.modules.a76.clients_and_providers.models import ( - ClientProvider, ClientProviderAddress, ClientProviderPrograms + ClientProvider, + ClientProviderAddress, + ClientProviderPrograms, ) from api.v1.modules.a76.parts.models import Part from api.v1.modules.a76.pedmientos.models import Pedimentos from api.v1.modules.a76.general_catalogs.company.models import Company from api.v1.modules.a76.customs_brokers.models import CustomsBroker -from api.v1.modules.a76.items.models import Item +from api.v1.modules.a76.items.models import Item # --- TRANSPORTATION MODELS --- from api.v1.modules.a76.transportation.transporters.models import Transporter @@ -32,21 +34,68 @@ from api.v1.modules.a76.transportation.drivers.models import Driver # --- MODELO DE FRACCIONES --- from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction +# --- MODELO DE UNIDADES DE MEDIDA --- +from api.v1.modules.a76.general_catalogs.units_of_measure.models import UnitOfMeasure + # --- SCHEMAS --- from .schemas import ( - ClienteSchema, PartidaSchema, TotalesSchema, - FacturaSchema, FacturaImportacionCompleta + ClienteSchema, + PartidaSchema, + TotalesSchema, + FacturaSchema, + FacturaImportacionCompleta, ) + class FacturaImportacionMexService: def __init__(self): self.template_dir = Path(__file__).parent.parent / "templates" self.jinja_env = Environment( loader=FileSystemLoader(self.template_dir), - autoescape=select_autoescape(['html', 'xml']) + autoescape=select_autoescape(["html", "xml"]), ) self.template = self.jinja_env.get_template('factura_mex_ver.html') + def _get_document_title(self, invoice_type: str, is_american: bool = False) -> str: + """ + Determina el título del documento basado en el tipo de factura. + + Args: + invoice_type: Tipo de factura (TEM, DEF, MEX, CR) + is_american: Si es factura americana (True) o mexicana (False) + + Returns: + Título formateado para la factura + """ + # Mapeo para facturas mexicanas + mexican_titles = { + "MEX": "Factura Importación Compras Mexicanas", + "DEF": "Importación Definitiva", + "TEM": "Importación Temporal", + "CR": "Importación de Cambio de Régimen", + } + + # Mapeo para facturas americanas + american_titles = { + "MEX": "Mexican Purchases Import Invoice", + "DEF": "Definitive Importation", + "TEM": "Temporary Importation", + "CR": "Regime Change Importation", + } + + # Seleccionar el mapa correcto + titles = american_titles if is_american else mexican_titles + + # Obtener el título (normalizar a mayúsculas) + invoice_type_upper = invoice_type.upper() if invoice_type else "" + title = titles.get(invoice_type_upper, "") + + # Fallback a genéricos si no se encuentra + if not title: + return "Commercial Invoice" if is_american else "Factura de Importación" + + return title + def _get_wkhtmltopdf_config(self): path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" if not Path(path).exists(): @@ -54,28 +103,49 @@ class FacturaImportacionMexService: return pdfkit.configuration(wkhtmltopdf=path) def formatear_numero(self, valor, decimales: int = 2): - if valor is None: return 0.0 + if valor is None: + return 0.0 try: return round(float(valor), decimales) - except: return 0.0 + except: + return 0.0 def _format_fraccion_fallback(self, fraccion_raw: str) -> str: if not fraccion_raw or len(fraccion_raw) < 8: return fraccion_raw return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" - def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + def _obtener_datos_cliente( + self, db: Session, client_id: int, rol: str + ) -> ClienteSchema: main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() if not main: - return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX") - - addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() - prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + return ClienteSchema( + header=rol, + nombre="Desconocido", + direccion="", + tax_id="", + codigo_postal="", + ciudad="", + estado="", + pais="MEX", + ) + + addr = ( + db.query(ClientProviderAddress) + .filter(ClientProviderAddress.client_id == client_id) + .first() + ) + prog = ( + db.query(ClientProviderPrograms) + .filter(ClientProviderPrograms.client_id == client_id) + .first() + ) return ClienteSchema( header=rol, nombre=(main.name or main.short_name) or "S/N", - direccion=(addr.streets or "") if addr else "", + direccion=(addr.streets or "") if addr else "", num_exterior=(addr.exterior_number or "") if addr else "", num_interior=(addr.interior_number or "") if addr else "", colonia=(addr.neighborhood or "") if addr else "", @@ -83,47 +153,108 @@ class FacturaImportacionMexService: ciudad=(addr.city or "") if addr else "", estado=(addr.state or "") if addr else "", pais=(addr.country or "MEX") if addr else "MEX", - tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), - programa="IMMEX" if (prog and prog.program) else "", - autorizacion=prog.program_number if prog else "", - prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", - reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( - prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + tax_id=( + prog.tax_id + if (prog and prog.tax_id) + else (getattr(main, "rfc", "") or "") + ), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=( + prog.prosec_authorization + if (prog and prog.prosec and prog.prosec_authorization) + else "" + ), + reg_emp=( + prog.val_certified_company_registry + if (prog and hasattr(prog, "val_certified_company_registry")) + else ( + prog.certified_company_registry + if (prog and prog.certified_company_registry) + else "" + ) + ), + cert=( + prog.is_certified_company + if (prog and prog.is_certified_company) + else "" ), - cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" ) - def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> FacturaImportacionCompleta: + def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None, currency_code: str = 'ORIGINAL') -> FacturaImportacionCompleta: try: - if progress_callback: progress_callback(10, "Buscando factura...") - header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() - if not header: raise HTTPException(status_code=404, detail="Factura no encontrada") + if progress_callback: + progress_callback(10, "Buscando factura...") + header = ( + db.query(InvoiceHeader) + .filter( + InvoiceHeader.id == invoice_id, + InvoiceHeader.company_id == company_id, + ) + .first() + ) + if not header: + raise HTTPException(status_code=404, detail="Factura no encontrada") - compliance = header.compliance_mx + compliance = header.compliance_mx logistics = header.logistics if header.logistics else None financials = header.financials if header.financials else None - if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...") - pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id - pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None - - if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...") + if progress_callback: + progress_callback(20, "Obteniendo datos de pedimento...") + pedimento_id = ( + compliance.pedimento_id + if (compliance and compliance.pedimento_id) + else header.related_doc_id + ) + pedimento = ( + db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() + if pedimento_id + else None + ) + + if progress_callback: + progress_callback(30, "Obteniendo cliente y proveedor...") proveedor_id = compliance.provider_id if compliance else None - cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + cliente_proveedor = ( + self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") + if proveedor_id + else ClienteSchema( + header="Proveedor", + nombre="No Asignado", + direccion="", + tax_id="", + codigo_postal="", + ciudad="", + estado="", + pais="", + ) + ) nombre_agente = "" if compliance and compliance.customs_broker_id: - broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() - if broker: nombre_agente = broker.name + broker = ( + db.query(CustomsBroker) + .filter(CustomsBroker.id == compliance.customs_broker_id) + .first() + ) + if broker: + nombre_agente = broker.name company = db.query(Company).filter(Company.id == header.company_id).first() # Datos Default (Company/Importer) - Used for fallback or Right Side (Enviado A) cliente_default = ClienteSchema( header="Importador / consignatario:", - nombre=getattr(company, 'name', "Empresa Local"), + nombre=getattr(company, "name", "Empresa Local"), direccion="DOMICILIO FISCAL", - num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", - tax_id=getattr(company, 'rfc', ""), - programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + num_exterior="", + colonia="", + codigo_postal="", + ciudad="", + estado="", + pais="MEX", + tax_id=getattr(company, "rfc", ""), + programa=getattr(company, "program", "IMMEX"), + autorizacion=getattr(company, "program_number", ""), ) # Left Side Logic (Consignatario / Sold To) @@ -131,34 +262,51 @@ class FacturaImportacionMexService: if compliance and compliance.sold_to_id: raw_header = compliance.sold_to_header or "CONSIGNATARIO" clean_header = raw_header.replace("_", " ").capitalize() + ":" - cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) - + cliente_vendido = self._obtener_datos_cliente( + db, compliance.sold_to_id, clean_header + ) + # Right Side Logic (Enviado A / Shipped To) cliente_enviado = cliente_default if compliance and compliance.shipped_to_id: # Clean header: "enviado_a" -> "Enviado a:" raw_header_shipped = compliance.shipped_to_header or "DESTINATARIO" - clean_header_shipped = raw_header_shipped.replace("_", " ").capitalize() + ":" - - # Fetch client data - cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) + clean_header_shipped = ( + raw_header_shipped.replace("_", " ").capitalize() + ":" + ) - remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" - acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + # Fetch client data + cliente_enviado = self._obtener_datos_cliente( + db, compliance.shipped_to_id, clean_header_shipped + ) + + remesa_valor = ( + str(compliance.remesa) if (compliance and compliance.remesa) else "" + ) + acuse_valor = ( + str(compliance.edocument) + if (compliance and compliance.edocument) + else "N/A" + ) patente_val = "" if pedimento and pedimento.license: patente_val = pedimento.license - elif 'broker' in locals() and broker and broker.license: + elif "broker" in locals() and broker and broker.license: patente_val = broker.license - # --- Transport Data Fetching --- - transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + transporte_txt = ( + str(logistics.transport_type) + if (logistics and logistics.transport_type) + else "" + ) num_transporte_val = (logistics.trailer_num or "") if logistics else "" - + # Init values - placas_val = (logistics.license_plate or "") if logistics else "" # Placas Tracto + placas_val = ( + (logistics.license_plate or "") if logistics else "" + ) # Placas Tracto placas_remolque_val = "" transportista_val = (logistics.carrier_id or "") if logistics else "" caat_val = "" @@ -168,46 +316,82 @@ class FacturaImportacionMexService: if logistics: # 1. Transporter (CAAT / SCAC) if logistics.carrier_id: - transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + transporter_obj = ( + db.query(Transporter) + .filter(Transporter.transporter_key == logistics.carrier_id) + .first() + ) if transporter_obj: caat_val = transporter_obj.caat_code or "" - scac_val = transporter_obj.transport_code or "" # Mapping transport_code to SCAC + scac_val = ( + transporter_obj.transport_code or "" + ) # Mapping transport_code to SCAC transportista_val = transporter_obj.name or logistics.carrier_id # 2. Vehicle (Placas Tracto) - Try transport_id first if logistics.transport_id: - veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + veh_obj = ( + db.query(Vehicle) + .filter(Vehicle.vehicle_key == logistics.transport_id) + .first() + ) if veh_obj: - placas_val = veh_obj.plate_number or placas_val - elif logistics.vehicle_num: # Fallback to vehicle_num if populated and transport_id failed/empty - veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() - if veh_obj: - placas_val = veh_obj.plate_number or placas_val + placas_val = veh_obj.plate_number or placas_val + elif ( + logistics.vehicle_num + ): # Fallback to vehicle_num if populated and transport_id failed/empty + veh_obj = ( + db.query(Vehicle) + .filter(Vehicle.vehicle_key == logistics.vehicle_num) + .first() + ) + if veh_obj: + placas_val = veh_obj.plate_number or placas_val # 3. Trailer (Placas Remolque) if logistics.trailer_num: - trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + trl_obj = ( + db.query(Trailer) + .filter(Trailer.trailer_number == logistics.trailer_num) + .first() + ) if trl_obj: placas_remolque_val = trl_obj.plate_number or "" # 4. Driver (License) if logistics.carrier_id and logistics.driver_name: # Attempt to find driver by name + carrier - drv_obj = db.query(Driver).filter( - Driver.transporter_key == logistics.carrier_id, - Driver.driver_name == logistics.driver_name - ).first() + drv_obj = ( + db.query(Driver) + .filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name, + ) + .first() + ) if drv_obj: - licencia_cond_val = drv_obj.license_number or "" + licencia_cond_val = drv_obj.license_number or "" + + # Determine Currency + moneda_final = getattr(header, 'currency', "USD") or "USD" + if currency_code == 'MXN': + moneda_final = 'MXN' + elif currency_code == 'USD': + moneda_final = 'USD' factura_schema = FacturaSchema( numero=header.invoice_number or "S/N", + titulo_documento=self._get_document_title(header.invoice_type or "", is_american=False), fecha=str(header.invoice_date) if header.invoice_date else "", tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), - moneda=getattr(header, 'currency', "USD") or "USD", + moneda=moneda_final, incoterm=(logistics.incoterm or "") if logistics else "", observaciones=header.observation_es or header.observation_en or "", - pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + pedimento=( + f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" + if pedimento + else "" + ), clave_pedimento=pedimento.pedimento_code if pedimento else "", regimen=header.document_type or "", patente=patente_val, @@ -220,45 +404,74 @@ class FacturaImportacionMexService: caat=caat_val, scac=scac_val, licencia_conductor=licencia_cond_val, - aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + aduana=( + compliance.aduana + if (compliance and compliance.aduana) + else ( + pedimento.customs_office[:2] + if (pedimento and pedimento.customs_office) + else "" + ) + ), precinto=(logistics.seal_number or "") if logistics else "", destino=(logistics.destination_goods or "") if logistics else "", - remesa=remesa_valor, acuse_electronico=acuse_valor + remesa=remesa_valor, + acuse_electronico=acuse_valor, + ) + + if progress_callback: + progress_callback(50, "Procesando partidas...") + lines = ( + db.query(LineItem) + .join(Item, LineItem.item_id == Item.id) + .filter(Item.invoice_id == header.id) + .all() ) - - if progress_callback: progress_callback(50, "Procesando partidas...") - lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter(Item.invoice_id == header.id).all() partidas_list = [] - + for line in lines: - qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() - fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() + qty = ( + db.query(LineQuantity) + .filter(LineQuantity.item_line_id == line.id) + .first() + ) + fin = ( + db.query(LineFinancial) + .filter(LineFinancial.item_line_id == line.id) + .first() + ) part_master = db.query(Part).filter(Part.id == line.part_number).first() desc_final = "S/D" num_parte_final = str(line.part_number or "S/N") - fraccion_raw = "" + fraccion_raw = "" origen_final = "MEX" if part_master: - desc_final = part_master.description_spanish or part_master.description_english or "Sin Desc." + desc_final = ( + part_master.description_spanish + or part_master.description_english + or "Sin Desc." + ) num_parte_final = part_master.part_number fraccion_raw = part_master.fraction if part_master.fraction else "" - + # Fetch Origin from Master Catalog (FaPart) if part_master.fa_data and part_master.fa_data.origin_country: origen_final = part_master.fa_data.origin_country - fraccion_limpia = fraccion_raw.replace(".", "").strip() if fraccion_limpia: fraccion_limpia = fraccion_limpia[:8].zfill(8) # Consultar tabla tariff_fractions - fraccion_db = db.query(TariffFraction).filter(TariffFraction.code == fraccion_limpia).first() + fraccion_db = ( + db.query(TariffFraction) + .filter(TariffFraction.code == fraccion_limpia) + .first() + ) - - preferencia_txt = "General" + preferencia_txt = "General" advalorem_txt = "0%" fraccion_imprimir = fraccion_raw @@ -268,20 +481,20 @@ class FacturaImportacionMexService: if adv_db and adv_db.strip() not in ["0", "0.0", "0.00", ""]: advalorem_txt = adv_db if "%" in adv_db else f"{adv_db}%" else: - advalorem_txt = "0%" - + advalorem_txt = "0%" + fraccion_imprimir = fraccion_db.fraction or fraccion_raw else: - + fraccion_imprimir = self._format_fraccion_fallback(fraccion_limpia) # Logic to determine values - Prioritize Specific Currency Columns v_unitario = 0.0 v_total = 0.0 - + if fin: - is_mxn = (factura_schema.moneda == 'MXN') - + is_mxn = factura_schema.moneda == "MXN" + # 1. Try Specific Currency Columns First if is_mxn: v_unitario = float(fin.unit_cost_commercial_mxn or 0.0) @@ -292,50 +505,83 @@ class FacturaImportacionMexService: # 2. Fallback to Generic independently if Specific is 0 if not v_unitario: - v_unitario = float(fin.commercial_unit_cost or 0.0) - + v_unitario = float(fin.commercial_unit_cost or 0.0) + if not v_total: - v_total = float(fin.total_commercial_value or 0.0) + v_total = float(fin.total_commercial_value or 0.0) # 3. Calculate from Quantity if still missing cantidad = float(qty.quantity) if (qty and qty.quantity) else 0.0 - + if cantidad > 0: if v_unitario > 0 and v_total == 0: v_total = v_unitario * cantidad elif v_total > 0 and v_unitario == 0: v_unitario = v_total / cantidad - partidas_list.append(PartidaSchema( - numero_parte=num_parte_final, - descripcion=desc_final, - fraccion=fraccion_imprimir, - origen=origen_final, - advalorem=advalorem_txt, - preferencia=preferencia_txt, - cantidad_importacion=self.formatear_numero(qty.quantity if qty else 0), - unidad_medida=qty.weight_unit if qty else "PZA", - cantidad_bultos=int(qty.package_quantity) if qty and qty.package_quantity else 0, - clave_bultos=(qty.package_key or "") if qty else "", - peso_neto=self.formatear_numero(qty.net_weight if qty else 0), - peso_bruto=self.formatear_numero(qty.gross_weight if qty else 0), - valor_costo_unitario=self.formatear_numero(v_unitario), - valor_total=self.formatear_numero(v_total) - )) + # Obtener descripción de la unidad de medida desde la tabla a76.item_lines + unidad_desc = "" + if line.unit_of_measure: + uom = ( + db.query(UnitOfMeasure) + .filter( + UnitOfMeasure.id == line.unit_of_measure, + UnitOfMeasure.company_id == company_id, + ) + .first() + ) + if uom: + unidad_desc = uom.description or uom.code + else: + unidad_desc = "" - totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + partidas_list.append( + PartidaSchema( + numero_parte=num_parte_final, + descripcion=desc_final, + fraccion=fraccion_imprimir, + origen=origen_final, + advalorem=advalorem_txt, + preferencia=preferencia_txt, + cantidad_importacion=self.formatear_numero( + qty.quantity if qty else 0 + ), + unidad_medida=unidad_desc, + cantidad_bultos=( + int(qty.package_quantity) + if qty and qty.package_quantity + else 0 + ), + clave_bultos=(qty.package_key or "") if qty else "", + peso_neto=self.formatear_numero(qty.net_weight if qty else 0), + peso_bruto=self.formatear_numero( + qty.gross_weight if qty else 0 + ), + valor_costo_unitario=self.formatear_numero(v_unitario), + valor_total=self.formatear_numero(v_total), + ) + ) + + totales = self.calcular_totales( + partidas_list, Decimal(factura_schema.tipo_cambio) + ) return FacturaImportacionCompleta( - cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, - cliente_enviado=cliente_enviado, factura=factura_schema, - partidas=partidas_list, totales=totales + cliente_proveedor=cliente_proveedor, + cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, + factura=factura_schema, + partidas=partidas_list, + totales=totales, ) except Exception as e: print(f"Error Service A76: {e}") raise HTTPException(status_code=500, detail=f"Error: {str(e)}") - def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + def calcular_totales( + self, partidas: List[PartidaSchema], tipo_cambio: Decimal + ) -> TotalesSchema: cant = sum(p.cantidad_importacion for p in partidas) valor = sum(p.valor_total for p in partidas) peso_n = sum(p.peso_neto for p in partidas) @@ -343,17 +589,22 @@ class FacturaImportacionMexService: bultos = sum(p.cantidad_bultos for p in partidas) claves = [p.clave_bultos for p in partidas if p.clave_bultos] clave_comun = max(set(claves), key=claves.count) if claves else "" - if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" + if bultos > 1 and clave_comun and not clave_comun.endswith("S"): + clave_comun += "S" tc = float(tipo_cambio) if tipo_cambio else 1.0 - return TotalesSchema( - cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, - peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), - valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0) + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), + bultos_total=bultos, + clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), + peso_bruto_total=self.formatear_numero(peso_b), + valor_total_total=self.formatear_numero(valor), + valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0), ) - def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None) -> Tuple[bytes, str, str]: + def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None, currency_code: str = 'ORIGINAL') -> Tuple[bytes, str, str]: if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") - datos = self.obtener_datos(db, invoice_id, company_id, progress_callback) + datos = self.obtener_datos(db, invoice_id, company_id, progress_callback, currency_code) if progress_callback: progress_callback(80, "Renderizando plantilla...") @@ -365,7 +616,7 @@ class FacturaImportacionMexService: comp_logo = db.query(Company).filter(Company.id == company_id).first() if comp_logo and comp_logo.logo: p = Path(comp_logo.logo) - + # Logic robusta de búsqueda (igual que en routes.py) target_path = p if not target_path.exists(): @@ -377,27 +628,49 @@ class FacturaImportacionMexService: if target_path.exists(): with open(target_path, "rb") as image_file: - encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + encoded_string = base64.b64encode(image_file.read()).decode( + "utf-8" + ) # Detect MIME type loosely mime = "image/png" - if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + if target_path.suffix.lower() in [".jpg", ".jpeg"]: + mime = "image/jpeg" logo_b64 = f"data:{mime};base64,{encoded_string}" except Exception as e: print(f"Error loading logo: {e}") context = { - 'cliente_proveedor': datos.cliente_proveedor.model_dump(), 'cliente_vendido': datos.cliente_vendido.model_dump(), - 'cliente_enviado': datos.cliente_enviado.model_dump(), 'factura': datos.factura.model_dump(), - 'partidas': [p.model_dump() for p in datos.partidas], 'totales': datos.totales.model_dump(), - 'logo_b64': logo_b64 + "cliente_proveedor": datos.cliente_proveedor.model_dump(), + "cliente_vendido": datos.cliente_vendido.model_dump(), + "cliente_enviado": datos.cliente_enviado.model_dump(), + "factura": datos.factura.model_dump(), + "partidas": [p.model_dump() for p in datos.partidas], + "totales": datos.totales.model_dump(), + "logo_b64": logo_b64, } html_content = self.template.render(**context) nombre = f"Factura_{datos.factura.numero}.{formato}" - if formato == "html": return html_content.encode('utf-8'), nombre, "text/html" - - if progress_callback: progress_callback(90, "Generando PDF final...") - options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} - pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) - - if progress_callback: progress_callback(100, "Completado") - return pdf, nombre, "application/pdf" \ No newline at end of file + if formato == "html": + return html_content.encode("utf-8"), nombre, "text/html" + + if progress_callback: + progress_callback(90, "Generando PDF final...") + options = { + "page-size": "Letter", + "margin-top": "0.5in", + "margin-right": "0.5in", + "margin-bottom": "0.5in", + "margin-left": "0.5in", + "encoding": "UTF-8", + "enable-local-file-access": None, + } + pdf = pdfkit.from_string( + html_content, + False, + options=options, + configuration=self._get_wkhtmltopdf_config(), + ) + + if progress_callback: + progress_callback(100, "Completado") + return pdf, nombre, "application/pdf" diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/routes.py b/backend/api/v1/modules/a76/reports/importacion/facturas/routes.py index f7c0d72d..324bb91a 100644 --- a/backend/api/v1/modules/a76/reports/importacion/facturas/routes.py +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/routes.py @@ -40,9 +40,10 @@ async def get_task_status( async def trigger_descarga_factura( invoice_id: int, company_id: int = Query(..., description="ID de la empresa"), + invoice_type: str = Query('mexican', description="Tipo de factura: 'mexican' o 'american'"), current_user: Dict[str, Any] = Depends(get_current_user), db: Session = Depends(get_core_db) ): validate_access_to_resource(db, company_id, current_user) - task = generar_pdf_factura_async.delay(invoice_id, company_id) + task = generar_pdf_factura_async.delay(invoice_id, company_id, invoice_type) return {"task_id": task.id, "message": "Generación iniciada"} \ No newline at end of file diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/task.py b/backend/api/v1/modules/a76/reports/importacion/facturas/task.py index 6cdf1342..fabd082f 100644 --- a/backend/api/v1/modules/a76/reports/importacion/facturas/task.py +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/task.py @@ -5,35 +5,36 @@ from celery import current_task, states from core.database import CoreSessionLocal from .mex.service import FacturaImportacionMexService +from .usa.service import FacturaImportacionUsaService logger = logging.getLogger(__name__) @celery_app.task(name="generar_pdf_factura_async", bind=True) -def generar_pdf_factura_async(self, invoice_id: int, company_id: int): +def generar_pdf_factura_async(self, invoice_id: int, company_id: int, invoice_type: str = 'mexican', currency_code: str = 'ORIGINAL'): - # 1. Abrimos conexión a la DB db = CoreSessionLocal() try: - logger.info(f"Worker procesando factura {invoice_id}...") + logger.info(f"Worker procesando factura {invoice_id} ({invoice_type}, {currency_code})...") - # 2. Instanciamos el servicio de reportes - service = FacturaImportacionMexService() + if invoice_type == 'american': + service = FacturaImportacionUsaService() + else: + service = FacturaImportacionMexService() - # Update state to PROCESSING self.update_state(state='PROCESSING', meta={'current': 5, 'total': 100, 'status': 'Iniciando generación...'}) def progress_callback(progress: int, status: str): self.update_state(state='PROCESSING', meta={'current': progress, 'total': 100, 'status': status}) - # 3. Generamos los bytes del PDF pdf_bytes, nombre, media_type = service.generar_factura_completa( db=db, invoice_id=invoice_id, company_id=company_id, - progress_callback=progress_callback + progress_callback=progress_callback, + currency_code=currency_code ) - # 4. Codificamos a base64 para que viaje seguro por Valkey + pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8') return { @@ -48,5 +49,5 @@ def generar_pdf_factura_async(self, invoice_id: int, company_id: int): return {"status": "error", "message": str(e)} finally: - # 5. MUY IMPORTANTE: Cerramos la conexión para no saturar Postgres + db.close() \ No newline at end of file diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_mex_ver.html b/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_mex_ver.html index ade499e4..215d8fa8 100644 --- a/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_mex_ver.html +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_mex_ver.html @@ -273,7 +273,7 @@
-

Factura de Importacion

+

{{ factura.titulo_documento }}

diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_usa_ver.html b/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_usa_ver.html new file mode 100644 index 00000000..b23783cc --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/templates/factura_usa_ver.html @@ -0,0 +1,594 @@ + + + + + + Commercial Invoice - {{ factura.numero }} + + + + +
+
+
+

{{ factura.titulo_documento }}

+
+

+
+
+

+


+
+
+
+
+ {% if logo_b64 %} +
+ +
+ {% endif %} +
+

{{ cliente_proveedor.header }}

+

{{ cliente_proveedor.nombre }}

+

{{ cliente_proveedor.direccion }} + {% if cliente_proveedor.num_exterior %} Ext: {{ cliente_proveedor.num_exterior }}{% endif %} + {% if cliente_proveedor.num_interior %} Int: {{ cliente_proveedor.num_interior }}{% endif %} +

+

{{ cliente_proveedor.colonia }} {% if cliente_proveedor.codigo_postal %} Zip Code: {{ + cliente_proveedor.codigo_postal }}{% endif %}

+

{{ cliente_proveedor.ciudad }}, {{ cliente_proveedor.estado }}, {{ cliente_proveedor.pais }}

+

TAX ID: {{ cliente_proveedor.tax_id }} + {% if cliente_proveedor.programa and cliente_proveedor.programa != 'Ninguno' %} + {{ cliente_proveedor.programa }}: {{ cliente_proveedor.autorizacion }} + {% endif %} +

+


+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+

INVOICE:

+
+

{{ factura.numero }}

+
+

Date:

+
+

{{ factura.fecha }}

+
+

Ex. Rate:

+
+

{{ factura.tipo_cambio }}

+
+

INCOTERM:

+
+

{{ factura.incoterm or '' }}

+
+

Customs:

+
+

{{ factura.aduana }}

+
+
+
+ +
+
+

{{ cliente_vendido.header }}

+

{{ cliente_vendido.nombre }}

+

{{ cliente_vendido.direccion }} + {% if cliente_vendido.num_exterior %} Ext: {{ cliente_vendido.num_exterior }}{% endif %} + {% if cliente_vendido.num_interior %} Int: {{ cliente_vendido.num_interior }}{% endif %} +

+

{{ cliente_vendido.colonia }} {% if cliente_vendido.codigo_postal %} Zip Code: {{ + cliente_vendido.codigo_postal }}{% endif %}

+

{{ cliente_vendido.ciudad }}, {{ cliente_vendido.estado }}, {{ cliente_vendido.pais }} +

+

Tax ID: {{ cliente_vendido.tax_id }} + {% if cliente_vendido.programa and cliente_vendido.programa != 'Ninguno' %} + {{ cliente_vendido.programa }}: {{ cliente_vendido.autorizacion }} + {% endif %} +

+

+ {% if cliente_vendido.prosec %}PROSEC: {{ cliente_vendido.prosec }} {% endif %} + {% if cliente_vendido.reg_emp %}REG EMP: {{ cliente_vendido.reg_emp }} {% endif %} + {% if cliente_vendido.cert %}CERT: {{ cliente_vendido.cert }}{% endif %} +

+
+ +
+

{{ cliente_enviado.header }}

+

{{ cliente_enviado.nombre }}

+

{{ cliente_enviado.direccion }} + {% if cliente_enviado.num_exterior %} Ext: {{ cliente_enviado.num_exterior }}{% endif %} + {% if cliente_enviado.num_interior %} Int: {{ cliente_enviado.num_interior }}{% endif %} +

+

{{ cliente_enviado.colonia }} {% if cliente_enviado.codigo_postal %} Zip Code: {{ + cliente_enviado.codigo_postal }}{% endif %}

+

{{ cliente_enviado.ciudad }}, {{ cliente_enviado.estado }}, {{ cliente_enviado.pais }} +

+

Tax ID: {{ cliente_enviado.tax_id }} + {% if cliente_enviado.programa and cliente_enviado.programa != 'Ninguno' %} + {{ cliente_enviado.programa }}: {{ cliente_enviado.autorizacion }} + {% endif %} +

+

+ {% if cliente_enviado.prosec %}PROSEC: {{ cliente_enviado.prosec }} {% endif %} + {% if cliente_enviado.reg_emp %}REG EMP: {{ cliente_enviado.reg_emp }} {% endif %} + {% if cliente_enviado.cert %}CERT: {{ cliente_enviado.cert }}{% endif %} +

+
+
+


+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {% for partida in partidas %} + + + + + + + + + + + + {% endfor %} + + + + + + + + + + + + + + + + + + + + + +
+

Carrier:

+
+

{{ factura.transportista }}

+
+

SCAC: {{ factura.scac }}

+
+

INCOTERM:

+
+

{{ factura.incoterm }}

+
+

Customs: {{ factura.aduana }} / Ped: {{ factura.pedimento }}

+
+


+
+

Transport:

+
+

{{ factura.transporte }}: {{ factura.num_transporte }}

+
+

CAAT: {{ factura.caat }}

+
+

Plates: {{ factura.placas or '' }} / Trl: {{ factura.placas_remolque or + '' }}

+
+

Driver/Lic:

+
+

{{ factura.licencia_conductor or 'N/A' }}

+
+

Line

+
+

Part Number

+

Description

+
+

Commercial

+
+

Packaging

+
+

Weight (KGS)

+
+

Values

+
+

Quantity

+
+

U.M.

+
+

Type

+
+

Net

+
+

Gross

+
+

Unit

+
+

Total

+
+

{{ loop.index }}

+
+

{{ partida.numero_parte }}

+

{{ partida.descripcion }}

+

HTS Code: {{ partida.fraccion }} / Orig: {{ partida.origen or 'MEX' }}

+ +
+

{{ partida.cantidad_importacion }}

+
+

{{ partida.unidad_medida }}

+
+

+ {% if partida.cantidad_bultos != 0 %}{{ partida.cantidad_bultos }}{% endif %} + {{ partida.clave_bultos }} +

+
+

{{ partida.peso_neto }}

+
+

{{ partida.peso_bruto }}

+
+

${{ partida.valor_costo_unitario }}

+
+

${{ partida.valor_total }}

+
+

+ Remarks: + TOTALS +

+
+

{{ totales.cantidad_total }}

+
+

+ {% if totales.bultos_total != 0 %}{{ totales.bultos_total }}{% endif %} + {{ totales.clave_bultos or '' }} +

+
+

{{ totales.peso_neto_total }}

+
+

{{ totales.peso_bruto_total }}

+
+

${{ totales.valor_total_total }}

+
+

{{ factura.observaciones }}

+
+

+

{{ cliente_proveedor.nombre }}

+


+

Values expressed in: {{ factura.moneda + }}

+
+


+

+

I declare under penalty of perjury that the information contained in + this document is true and correct.

+
+ + + \ No newline at end of file diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/temporary/__init__.py b/backend/api/v1/modules/a76/reports/importacion/facturas/temporary/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/temporary/mex/service.py b/backend/api/v1/modules/a76/reports/importacion/facturas/temporary/mex/service.py new file mode 100644 index 00000000..200a3942 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/temporary/mex/service.py @@ -0,0 +1,403 @@ +import shutil +import base64 +import pdfkit +from pathlib import Path +from decimal import Decimal +from typing import Tuple, List, Callable, Optional + +from jinja2 import Environment, FileSystemLoader, select_autoescape +from fastapi import HTTPException +from sqlalchemy.orm import Session + +# --- MODELOS --- +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics +from api.v1.modules.a76.items.line_financials.models import LineFinancial +from api.v1.modules.a76.items.line_quantities.models import LineQuantity +from api.v1.modules.a76.items.line_items.models import LineItem +from api.v1.modules.a76.clients_and_providers.models import ( + ClientProvider, ClientProviderAddress, ClientProviderPrograms +) +from api.v1.modules.a76.parts.models import Part +from api.v1.modules.a76.pedmientos.models import Pedimentos +from api.v1.modules.a76.general_catalogs.company.models import Company +from api.v1.modules.a76.customs_brokers.models import CustomsBroker +from api.v1.modules.a76.items.models import Item + +# --- TRANSPORTATION MODELS --- +from api.v1.modules.a76.transportation.transporters.models import Transporter +from api.v1.modules.a76.transportation.vehicles.models import Vehicle +from api.v1.modules.a76.transportation.trailers.models import Trailer +from api.v1.modules.a76.transportation.drivers.models import Driver + +# --- MODELO DE FRACCIONES --- +from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction + +# --- SCHEMAS --- +from .schemas import ( + ClienteSchema, PartidaSchema, TotalesSchema, + FacturaSchema, FacturaImportacionCompleta +) + +class FacturaImportacionMexService: + def __init__(self): + self.template_dir = Path(__file__).parent.parent / "templates" + self.jinja_env = Environment( + loader=FileSystemLoader(self.template_dir), + autoescape=select_autoescape(['html', 'xml']) + ) + self.template = self.jinja_env.get_template('factura_mex_ver.html') + + def _get_wkhtmltopdf_config(self): + path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" + if not Path(path).exists(): + raise RuntimeError("wkhtmltopdf no encontrado.") + return pdfkit.configuration(wkhtmltopdf=path) + + def formatear_numero(self, valor, decimales: int = 2): + if valor is None: return 0.0 + try: + return round(float(valor), decimales) + except: return 0.0 + + def _format_fraccion_fallback(self, fraccion_raw: str) -> str: + if not fraccion_raw or len(fraccion_raw) < 8: + return fraccion_raw + return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" + + def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() + if not main: + return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX") + + addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() + prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + + return ClienteSchema( + header=rol, + nombre=(main.name or main.short_name) or "S/N", + direccion=(addr.streets or "") if addr else "", + num_exterior=(addr.exterior_number or "") if addr else "", + num_interior=(addr.interior_number or "") if addr else "", + colonia=(addr.neighborhood or "") if addr else "", + codigo_postal=(addr.postal_code or "") if addr else "", + ciudad=(addr.city or "") if addr else "", + estado=(addr.state or "") if addr else "", + pais=(addr.country or "MEX") if addr else "MEX", + tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", + reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( + prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + ), + cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" + ) + + def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> FacturaImportacionCompleta: + try: + if progress_callback: progress_callback(10, "Buscando factura...") + header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() + if not header: raise HTTPException(status_code=404, detail="Factura no encontrada") + + compliance = header.compliance_mx + logistics = header.logistics if header.logistics else None + financials = header.financials if header.financials else None + if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...") + pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id + pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None + + if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...") + proveedor_id = compliance.provider_id if compliance else None + cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + + nombre_agente = "" + if compliance and compliance.customs_broker_id: + broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() + if broker: nombre_agente = broker.name + + company = db.query(Company).filter(Company.id == header.company_id).first() + # Datos Default (Company/Importer) - Used for fallback or Right Side (Enviado A) + cliente_default = ClienteSchema( + header="Importador / consignatario:", + nombre=getattr(company, 'name', "Empresa Local"), + direccion="DOMICILIO FISCAL", + num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", + tax_id=getattr(company, 'rfc', ""), + programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + ) + + # Left Side Logic (Consignatario / Sold To) + cliente_vendido = cliente_default + if compliance and compliance.sold_to_id: + raw_header = compliance.sold_to_header or "CONSIGNATARIO" + clean_header = raw_header.replace("_", " ").capitalize() + ":" + cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) + + # Right Side Logic (Enviado A / Shipped To) + cliente_enviado = cliente_default + if compliance and compliance.shipped_to_id: + # Clean header: "enviado_a" -> "Enviado a:" + raw_header_shipped = compliance.shipped_to_header or "DESTINATARIO" + clean_header_shipped = raw_header_shipped.replace("_", " ").capitalize() + ":" + + # Fetch client data + cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) + + remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" + acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + + patente_val = "" + if pedimento and pedimento.license: + patente_val = pedimento.license + elif 'broker' in locals() and broker and broker.license: + patente_val = broker.license + + + # --- Transport Data Fetching --- + transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + num_transporte_val = (logistics.trailer_num or "") if logistics else "" + + # Init values + placas_val = (logistics.license_plate or "") if logistics else "" # Placas Tracto + placas_remolque_val = "" + transportista_val = (logistics.carrier_id or "") if logistics else "" + caat_val = "" + scac_val = "" + licencia_cond_val = "" + + if logistics: + # 1. Transporter (CAAT / SCAC) + if logistics.carrier_id: + transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + if transporter_obj: + caat_val = transporter_obj.caat_code or "" + scac_val = transporter_obj.transport_code or "" # Mapping transport_code to SCAC + transportista_val = transporter_obj.name or logistics.carrier_id + + # 2. Vehicle (Placas Tracto) - Try transport_id first + if logistics.transport_id: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + elif logistics.vehicle_num: # Fallback to vehicle_num if populated and transport_id failed/empty + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + + # 3. Trailer (Placas Remolque) + if logistics.trailer_num: + trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + if trl_obj: + placas_remolque_val = trl_obj.plate_number or "" + + # 4. Driver (License) + if logistics.carrier_id and logistics.driver_name: + # Attempt to find driver by name + carrier + drv_obj = db.query(Driver).filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name + ).first() + if drv_obj: + licencia_cond_val = drv_obj.license_number or "" + + factura_schema = FacturaSchema( + numero=header.invoice_number or "S/N", + fecha=str(header.invoice_date) if header.invoice_date else "", + tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), + moneda=getattr(header, 'currency', "USD") or "USD", + incoterm=(logistics.incoterm or "") if logistics else "", + observaciones=header.observation_es or header.observation_en or "", + pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + clave_pedimento=pedimento.pedimento_code if pedimento else "", + regimen=header.document_type or "", + patente=patente_val, + agente_aduanal=nombre_agente, + transporte=transporte_txt, + num_transporte=num_transporte_val, + placas=placas_val, + placas_remolque=placas_remolque_val, + transportista=transportista_val, + caat=caat_val, + scac=scac_val, + licencia_conductor=licencia_cond_val, + aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + precinto=(logistics.seal_number or "") if logistics else "", + destino=(logistics.destination_goods or "") if logistics else "", + remesa=remesa_valor, acuse_electronico=acuse_valor + ) + + if progress_callback: progress_callback(50, "Procesando partidas...") + lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter(Item.invoice_id == header.id).all() + partidas_list = [] + + for line in lines: + qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() + fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() + part_master = db.query(Part).filter(Part.id == line.part_number).first() + + desc_final = "S/D" + num_parte_final = str(line.part_number or "S/N") + fraccion_raw = "" + origen_final = "MEX" + + if part_master: + desc_final = part_master.description_spanish or part_master.description_english or "Sin Desc." + num_parte_final = part_master.part_number + fraccion_raw = part_master.fraction if part_master.fraction else "" + + # Fetch Origin from Master Catalog (FaPart) + if part_master.fa_data and part_master.fa_data.origin_country: + origen_final = part_master.fa_data.origin_country + + + fraccion_limpia = fraccion_raw.replace(".", "").strip() + if fraccion_limpia: + fraccion_limpia = fraccion_limpia[:8].zfill(8) + + # Consultar tabla tariff_fractions + fraccion_db = db.query(TariffFraction).filter(TariffFraction.code == fraccion_limpia).first() + + + preferencia_txt = "General" + advalorem_txt = "0%" + fraccion_imprimir = fraccion_raw + + if fraccion_db: + # Si el valor en BD es None, "0", o vacío, dejarlo como "0%" o "EXENTO" + adv_db = fraccion_db.adv_impo + if adv_db and adv_db.strip() not in ["0", "0.0", "0.00", ""]: + advalorem_txt = adv_db if "%" in adv_db else f"{adv_db}%" + else: + advalorem_txt = "0%" + + fraccion_imprimir = fraccion_db.fraction or fraccion_raw + else: + + fraccion_imprimir = self._format_fraccion_fallback(fraccion_limpia) + + # Logic to determine values - Prioritize Specific Currency Columns + v_unitario = 0.0 + v_total = 0.0 + + if fin: + is_mxn = (factura_schema.moneda == 'MXN') + + # 1. Try Specific Currency Columns First + if is_mxn: + v_unitario = float(fin.unit_cost_commercial_mxn or 0.0) + v_total = float(fin.value_commercial_mxn or 0.0) + else: + v_unitario = float(fin.unit_cost_commercial_usd or 0.0) + v_total = float(fin.value_commercial_usd or 0.0) + + # 2. Fallback to Generic independently if Specific is 0 + if not v_unitario: + v_unitario = float(fin.commercial_unit_cost or 0.0) + + if not v_total: + v_total = float(fin.total_commercial_value or 0.0) + + # 3. Calculate from Quantity if still missing + cantidad = float(qty.quantity) if (qty and qty.quantity) else 0.0 + + if cantidad > 0: + if v_unitario > 0 and v_total == 0: + v_total = v_unitario * cantidad + elif v_total > 0 and v_unitario == 0: + v_unitario = v_total / cantidad + + partidas_list.append(PartidaSchema( + numero_parte=num_parte_final, + descripcion=desc_final, + fraccion=fraccion_imprimir, + origen=origen_final, + advalorem=advalorem_txt, + preferencia=preferencia_txt, + cantidad_importacion=self.formatear_numero(qty.quantity if qty else 0), + unidad_medida=qty.weight_unit if qty else "PZA", + cantidad_bultos=int(qty.package_quantity) if qty and qty.package_quantity else 0, + clave_bultos=(qty.package_key or "") if qty else "", + peso_neto=self.formatear_numero(qty.net_weight if qty else 0), + peso_bruto=self.formatear_numero(qty.gross_weight if qty else 0), + valor_costo_unitario=self.formatear_numero(v_unitario), + valor_total=self.formatear_numero(v_total) + )) + + totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + + return FacturaImportacionCompleta( + cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, factura=factura_schema, + partidas=partidas_list, totales=totales + ) + + except Exception as e: + print(f"Error Service A76: {e}") + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + cant = sum(p.cantidad_importacion for p in partidas) + valor = sum(p.valor_total for p in partidas) + peso_n = sum(p.peso_neto for p in partidas) + peso_b = sum(p.peso_bruto for p in partidas) + bultos = sum(p.cantidad_bultos for p in partidas) + claves = [p.clave_bultos for p in partidas if p.clave_bultos] + clave_comun = max(set(claves), key=claves.count) if claves else "" + if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" + tc = float(tipo_cambio) if tipo_cambio else 1.0 + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), + valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0) + ) + + def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None) -> Tuple[bytes, str, str]: + if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") + datos = self.obtener_datos(db, invoice_id, company_id, progress_callback) + + if progress_callback: progress_callback(80, "Renderizando plantilla...") + + # LOGO LOGIC + logo_b64 = None + try: + # Fetch company to get logo path + + comp_logo = db.query(Company).filter(Company.id == company_id).first() + if comp_logo and comp_logo.logo: + p = Path(comp_logo.logo) + + # Logic robusta de búsqueda (igual que en routes.py) + target_path = p + if not target_path.exists(): + # Intentar en la ruta estándar: app_data/logos/{id}/{nombre} + # Esto cubre el caso donde solo se guardó el nombre del archivo o la ruta absoluta cambió + fallback = Path(f"app_data/logos/{company_id}") / p.name + if fallback.exists(): + target_path = fallback + + if target_path.exists(): + with open(target_path, "rb") as image_file: + encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + # Detect MIME type loosely + mime = "image/png" + if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + logo_b64 = f"data:{mime};base64,{encoded_string}" + except Exception as e: + print(f"Error loading logo: {e}") + + context = { + 'cliente_proveedor': datos.cliente_proveedor.model_dump(), 'cliente_vendido': datos.cliente_vendido.model_dump(), + 'cliente_enviado': datos.cliente_enviado.model_dump(), 'factura': datos.factura.model_dump(), + 'partidas': [p.model_dump() for p in datos.partidas], 'totales': datos.totales.model_dump(), + 'logo_b64': logo_b64 + } + html_content = self.template.render(**context) + nombre = f"Factura_{datos.factura.numero}.{formato}" + if formato == "html": return html_content.encode('utf-8'), nombre, "text/html" + + if progress_callback: progress_callback(90, "Generando PDF final...") + options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} + pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) + + if progress_callback: progress_callback(100, "Completado") + return pdf, nombre, "application/pdf" \ No newline at end of file diff --git a/backend/api/v1/modules/a76/reports/importacion/facturas/usa/service.py b/backend/api/v1/modules/a76/reports/importacion/facturas/usa/service.py new file mode 100644 index 00000000..d5ec1d10 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/facturas/usa/service.py @@ -0,0 +1,444 @@ +import shutil +import base64 +import pdfkit +from pathlib import Path +from decimal import Decimal +from typing import Tuple, List, Callable, Optional + +from jinja2 import Environment, FileSystemLoader, select_autoescape +from fastapi import HTTPException +from sqlalchemy.orm import Session + +# --- MODELOS --- +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics +from api.v1.modules.a76.items.line_financials.models import LineFinancial +from api.v1.modules.a76.items.line_quantities.models import LineQuantity +from api.v1.modules.a76.items.line_items.models import LineItem +from api.v1.modules.a76.clients_and_providers.models import ( + ClientProvider, ClientProviderAddress, ClientProviderPrograms +) +from api.v1.modules.a76.parts.models import Part +from api.v1.modules.a76.pedmientos.models import Pedimentos +from api.v1.modules.a76.general_catalogs.company.models import Company +from api.v1.modules.a76.customs_brokers.models import CustomsBroker +from api.v1.modules.a76.items.models import Item + +# --- TRANSPORTATION MODELS --- +from api.v1.modules.a76.transportation.transporters.models import Transporter +from api.v1.modules.a76.transportation.vehicles.models import Vehicle +from api.v1.modules.a76.transportation.trailers.models import Trailer +from api.v1.modules.a76.transportation.drivers.models import Driver + +# --- MODELO DE FRACCIONES --- +from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction + +# --- SCHEMAS --- +# Reuse schemas from neighbor package as they fit the same data structure +from ..mex.schemas import ( + ClienteSchema, PartidaSchema, TotalesSchema, + FacturaSchema, FacturaImportacionCompleta +) + +class FacturaImportacionUsaService: + def __init__(self): + self.template_dir = Path(__file__).parent.parent / "templates" + self.jinja_env = Environment( + loader=FileSystemLoader(self.template_dir), + autoescape=select_autoescape(['html', 'xml']) + ) + self.template = self.jinja_env.get_template('factura_usa_ver.html') + + def _get_document_title(self, invoice_type: str, is_american: bool = True) -> str: + """ + Determina el título del documento basado en el tipo de factura. + + Args: + invoice_type: Tipo de factura (TEM, DEF, MEX, CR) + is_american: Si es factura americana (True) o mexicana (False) + + Returns: + Título formateado para la factura + """ + # Mapeo para facturas mexicanas + mexican_titles = { + "MEX": "Factura Importación Compras Mexicanas", + "DEF": "Importación Definitiva", + "TEM": "Importación Temporal", + "CR": "Importación de Cambio de Régimen", + } + + # Mapeo para facturas americanas + american_titles = { + "MEX": "Mexican Purchases Import Invoice", + "DEF": "Definitive Importation", + "TEM": "Temporary Importation", + "CR": "Regime Change Importation", + } + + # Seleccionar el mapa correcto + titles = american_titles if is_american else mexican_titles + + # Obtener el título (normalizar a mayúsculas) + invoice_type_upper = invoice_type.upper() if invoice_type else "" + title = titles.get(invoice_type_upper, "") + + # Fallback a genéricos si no se encuentra + if not title: + return "Commercial Invoice" if is_american else "Factura de Importación" + + return title + + def _get_wkhtmltopdf_config(self): + path = shutil.which("wkhtmltopdf") or "/usr/local/bin/wkhtmltopdf" + if not Path(path).exists(): + raise RuntimeError("wkhtmltopdf no encontrado.") + return pdfkit.configuration(wkhtmltopdf=path) + + def formatear_numero(self, valor, decimales: int = 2): + if valor is None: return 0.0 + try: + return round(float(valor), decimales) + except: return 0.0 + + def _format_fraccion_fallback(self, fraccion_raw: str) -> str: + if not fraccion_raw or len(fraccion_raw) < 8: + return fraccion_raw + return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" + + def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() + if not main: + return ClienteSchema(header=rol, nombre="Unknown", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="USA") + + addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() + prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + + return ClienteSchema( + header=rol, + nombre=(main.name or main.short_name) or "N/A", + direccion=(addr.streets or "") if addr else "", + num_exterior=(addr.exterior_number or "") if addr else "", + num_interior=(addr.interior_number or "") if addr else "", + colonia=(addr.neighborhood or "") if addr else "", + codigo_postal=(addr.postal_code or "") if addr else "", + ciudad=(addr.city or "") if addr else "", + estado=(addr.state or "") if addr else "", + pais=(addr.country or "USA") if addr else "USA", + tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", + reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( + prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + ), + cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" + ) + + def obtener_datos(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None, currency_code: str = 'ORIGINAL') -> FacturaImportacionCompleta: + try: + if progress_callback: progress_callback(10, "Searching invoice...") + header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() + if not header: raise HTTPException(status_code=404, detail="Invoice not found") + + compliance = header.compliance_mx + logistics = header.logistics if header.logistics else None + financials = header.financials if header.financials else None + if progress_callback: progress_callback(20, "Fetching entry data...") + pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id + pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None + + if progress_callback: progress_callback(30, "Fetching client and supplier...") + proveedor_id = compliance.provider_id if compliance else None + cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Supplier:") if proveedor_id else ClienteSchema(header="Supplier", nombre="Unassigned", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + + nombre_agente = "" + if compliance and compliance.customs_broker_id: + broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() + if broker: nombre_agente = broker.name + + company = db.query(Company).filter(Company.id == header.company_id).first() + # Datos Default (Company/Importer) + cliente_default = ClienteSchema( + header="Importer / Consignee:", + nombre=getattr(company, 'name', "Local Company"), + direccion="FISCAL ADDRESS", + num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", + tax_id=getattr(company, 'rfc', ""), + programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + ) + + # Left Side Logic (Sold To) + cliente_vendido = cliente_default + if compliance and compliance.sold_to_id: + # Force English header for American Invoice + clean_header = "Sold To:" + # raw_header = compliance.sold_to_header or "SOLD_TO" + # clean_header = raw_header.replace("_", " ").title() + ":" + cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) + + # Right Side Logic (Shipped To) + cliente_enviado = cliente_default + if compliance and compliance.shipped_to_id: + # Force English header for American Invoice + clean_header_shipped = "Shipped To:" + # raw_header_shipped = compliance.shipped_to_header or "SHIPPED_TO" + # clean_header_shipped = raw_header_shipped.replace("_", " ").title() + ":" + + # Fetch client data + cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) + + remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" + acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + + patente_val = "" + if pedimento and pedimento.license: + patente_val = pedimento.license + elif 'broker' in locals() and broker and broker.license: + patente_val = broker.license + + + # --- Transport Data Fetching --- + transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + num_transporte_val = (logistics.trailer_num or "") if logistics else "" + + # Init values + placas_val = (logistics.license_plate or "") if logistics else "" # Plates + placas_remolque_val = "" + transportista_val = (logistics.carrier_id or "") if logistics else "" + caat_val = "" + scac_val = "" + licencia_cond_val = "" + + if logistics: + # 1. Transporter (CAAT / SCAC) + if logistics.carrier_id: + transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + if transporter_obj: + caat_val = transporter_obj.caat_code or "" + scac_val = transporter_obj.transport_code or "" # Mapping transport_code to SCAC + transportista_val = transporter_obj.name or logistics.carrier_id + + # 2. Vehicle (Plates) + if logistics.transport_id: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + elif logistics.vehicle_num: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + + # 3. Trailer + if logistics.trailer_num: + trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + if trl_obj: + placas_remolque_val = trl_obj.plate_number or "" + + # 4. Driver (License) + if logistics.carrier_id and logistics.driver_name: + drv_obj = db.query(Driver).filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name + ).first() + if drv_obj: + licencia_cond_val = drv_obj.license_number or "" + + # Determine Currency + moneda_final = getattr(header, 'currency', "USD") or "USD" + if currency_code == 'MXN': + moneda_final = 'MXN' + elif currency_code == 'USD': + moneda_final = 'USD' + + factura_schema = FacturaSchema( + numero=header.invoice_number or "N/A", + titulo_documento=self._get_document_title(header.invoice_type or "", is_american=True), + fecha=str(header.invoice_date) if header.invoice_date else "", + tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), + moneda=moneda_final, + incoterm=(logistics.incoterm or "") if logistics else "", + observaciones=header.observation_es or header.observation_en or "", + pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + clave_pedimento=pedimento.pedimento_code if pedimento else "", + regimen=header.document_type or "", + patente=patente_val, + agente_aduanal=nombre_agente, + transporte=transporte_txt, + num_transporte=num_transporte_val, + placas=placas_val, + placas_remolque=placas_remolque_val, + transportista=transportista_val, + caat=caat_val, + scac=scac_val, + licencia_conductor=licencia_cond_val, + aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + precinto=(logistics.seal_number or "") if logistics else "", + destino=(logistics.destination_goods or "") if logistics else "", + remesa=remesa_valor, acuse_electronico=acuse_valor + ) + + if progress_callback: progress_callback(50, "Processing items...") + lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter(Item.invoice_id == header.id).all() + partidas_list = [] + + for line in lines: + qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() + fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() + part_master = db.query(Part).filter(Part.id == line.part_number).first() + + desc_final = "N/D" + num_parte_final = str(line.part_number or "N/A") + fraccion_raw = "" + origen_final = "MEX" + + if part_master: + # Prefer English description if available, else Spanish + desc_final = part_master.description_english or part_master.description_spanish or "No Desc." + num_parte_final = part_master.part_number + # Prefer US Fraction (HTS) if available + fraccion_raw = part_master.us_fraction if part_master.us_fraction else "" + + if part_master.fa_data and part_master.fa_data.origin_country: + origen_final = part_master.fa_data.origin_country + + + # FRACTION LOGIC: Use US Fraction (us_fraction) if available, otherwise blank + fraccion_imprimir = "" + + # Check part master US fraction + if part_master and part_master.us_fraction: + fraccion_imprimir = part_master.us_fraction.strip() + + # Optional: Format if needed, but raw is usually fine for US HTS + # If valid US fraction logic requires looking up in DB, we could add that here. + # For now, per requirement: "Si no tiene, pues de queda en blanco" + + # Default "General" and "0%" if no specific logic for US duties yet + preferencia_txt = "General" + advalorem_txt = "0%" + + # Prioritize USD for American Invoice logic if available? + # Sticking to same logic as Mex for now but could prioritize USD columns. + # Actually, duplicate logic from mex service for now to ensure consistency. + + v_unitario = 0.0 + v_total = 0.0 + + if fin: + is_mxn = (factura_schema.moneda == 'MXN') + + if is_mxn: + v_unitario = float(fin.unit_cost_commercial_mxn or 0.0) + v_total = float(fin.value_commercial_mxn or 0.0) + else: + v_unitario = float(fin.unit_cost_commercial_usd or 0.0) + v_total = float(fin.value_commercial_usd or 0.0) + + if not v_unitario: + v_unitario = float(fin.commercial_unit_cost or 0.0) + + if not v_total: + v_total = float(fin.total_commercial_value or 0.0) + + cantidad = float(qty.quantity) if (qty and qty.quantity) else 0.0 + + if cantidad > 0: + if v_unitario > 0 and v_total == 0: + v_total = v_unitario * cantidad + elif v_total > 0 and v_unitario == 0: + v_unitario = v_total / cantidad + + # UOM Mapping for English context + uom_raw = qty.weight_unit if qty else "PCS" + if uom_raw == "PZA": uom_raw = "PCS" + + partidas_list.append(PartidaSchema( + numero_parte=num_parte_final, + descripcion=desc_final, + fraccion=fraccion_imprimir, + origen=origen_final, + advalorem=advalorem_txt, + preferencia=preferencia_txt, + cantidad_importacion=self.formatear_numero(qty.quantity if qty else 0), + unidad_medida=uom_raw, + cantidad_bultos=int(qty.package_quantity) if qty and qty.package_quantity else 0, + clave_bultos=(qty.package_key or "") if qty else "", + peso_neto=self.formatear_numero(qty.net_weight if qty else 0), + peso_bruto=self.formatear_numero(qty.gross_weight if qty else 0), + valor_costo_unitario=self.formatear_numero(v_unitario), + valor_total=self.formatear_numero(v_total) + )) + + totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + + return FacturaImportacionCompleta( + cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, factura=factura_schema, + partidas=partidas_list, totales=totales + ) + + except Exception as e: + print(f"Error Service A76 USA: {e}") + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + cant = sum(p.cantidad_importacion for p in partidas) + valor = sum(p.valor_total for p in partidas) + peso_n = sum(p.peso_neto for p in partidas) + peso_b = sum(p.peso_bruto for p in partidas) + bultos = sum(p.cantidad_bultos for p in partidas) + claves = [p.clave_bultos for p in partidas if p.clave_bultos] + clave_comun = max(set(claves), key=claves.count) if claves else "" + # if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" + # Don't pluralize strictly in English without logic, kept simple. + + tc = float(tipo_cambio) if tipo_cambio else 1.0 + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), + valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0) + ) + + def generar_factura_completa(self, db: Session, invoice_id: int, company_id: int, formato: str = "pdf", progress_callback: Optional[Callable] = None, currency_code: str = 'ORIGINAL') -> Tuple[bytes, str, str]: + if progress_callback: progress_callback(5, "Starting report service...") + datos = self.obtener_datos(db, invoice_id, company_id, progress_callback, currency_code) + + if progress_callback: progress_callback(80, "Rendering template...") + + # LOGO LOGIC + logo_b64 = None + try: + comp_logo = db.query(Company).filter(Company.id == company_id).first() + if comp_logo and comp_logo.logo: + p = Path(comp_logo.logo) + target_path = p + if not target_path.exists(): + fallback = Path(f"app_data/logos/{company_id}") / p.name + if fallback.exists(): + target_path = fallback + + if target_path.exists(): + with open(target_path, "rb") as image_file: + encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + mime = "image/png" + if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + logo_b64 = f"data:{mime};base64,{encoded_string}" + except Exception as e: + print(f"Error loading logo: {e}") + + context = { + 'cliente_proveedor': datos.cliente_proveedor.model_dump(), 'cliente_vendido': datos.cliente_vendido.model_dump(), + 'cliente_enviado': datos.cliente_enviado.model_dump(), 'factura': datos.factura.model_dump(), + 'partidas': [p.model_dump() for p in datos.partidas], 'totales': datos.totales.model_dump(), + 'logo_b64': logo_b64 + } + html_content = self.template.render(**context) + nombre = f"Commercial_Invoice_{datos.factura.numero}.{formato}" + if formato == "html": return html_content.encode('utf-8'), nombre, "text/html" + + if progress_callback: progress_callback(90, "Generating PDF...") + options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} + pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) + + if progress_callback: progress_callback(100, "Completed") + return pdf, nombre, "application/pdf" diff --git a/backend/api/v1/modules/a76/reports/importacion/packing_list/routes.py b/backend/api/v1/modules/a76/reports/importacion/packing_list/routes.py new file mode 100644 index 00000000..54c4dacf --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/packing_list/routes.py @@ -0,0 +1,49 @@ +from typing import Dict, Any +from fastapi import APIRouter, Depends, Query, Response, HTTPException +from sqlalchemy.orm import Session +from core.database import get_core_db +from core.security import get_current_user, validate_access_to_resource +from .service import PackingListService + +router = APIRouter() +service = PackingListService() + +from celery.result import AsyncResult +from core.celery_app import celery_app +from .task import generar_packing_list_async + +@router.get("/tasks/{task_id}") +async def get_task_status( + task_id: str, + current_user: Dict[str, Any] = Depends(get_current_user), + db: Session = Depends(get_core_db) +): + task_result = AsyncResult(task_id, app=celery_app) + + response = { + "task_id": task_id, + "state": task_result.state, + "result": None, + "info": None + } + + if task_result.state == 'FAILURE': + response["result"] = str(task_result.result) + elif task_result.state == 'SUCCESS': + response["result"] = task_result.result + elif task_result.state == 'PROCESSING': + response["info"] = task_result.info + + return response + +@router.post("/{invoice_id}/download-async") +async def trigger_download_packing_list( + invoice_id: int, + company_id: int = Query(..., description="ID de la empresa"), + current_user: Dict[str, Any] = Depends(get_current_user), + db: Session = Depends(get_core_db) +): + validate_access_to_resource(db, company_id, current_user) + + task = generar_packing_list_async.delay(invoice_id, company_id) + return {"task_id": task.id, "message": "Generación iniciada"} diff --git a/backend/api/v1/modules/a76/reports/importacion/packing_list/schemas.py b/backend/api/v1/modules/a76/reports/importacion/packing_list/schemas.py new file mode 100644 index 00000000..fcaaae40 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/packing_list/schemas.py @@ -0,0 +1,93 @@ +from typing import List, Optional, Union, Any +from pydantic import BaseModel, field_validator + +class ClienteSchema(BaseModel): + header: str + nombre: str + direccion: Optional[str] = "" + num_exterior: Optional[str] = "" + num_interior: Optional[str] = "" + colonia: Optional[str] = "" + codigo_postal: Optional[str] = "" + ciudad: Optional[str] = "" + estado: Optional[str] = "" + pais: Optional[str] = "" + tax_id: str + programa: Optional[str] = "" + autorizacion: Optional[str] = "" + prosec: Optional[str] = "" + reg_emp: Optional[str] = "" + cert: Optional[str] = "" + + @field_validator('direccion', 'nombre', mode='before') + @classmethod + def prevent_none(cls, v): + return v or "" + +class FacturaSchema(BaseModel): + numero: str + fecha: str + tipo_cambio: Union[float, str] + moneda: str + pedimento: str = "" + clave_pedimento: str = "" + remesa: str = "" + acuse_electronico: str = "" + agente_aduanal: str = "" + patente: str = "" + precinto: str = "" + regimen: str = "" + transportista: str = "" + scac: str = "" + caat: str = "" + incoterm: str = "" + transporte: str = "" + num_transporte: str = "" + placas: str = "" + placas_remolque: str = "" + licencia_conductor: str = "" + aduana: str = "" + destino: str = "" + observaciones: str = "" + +class PartidaSchema(BaseModel): + numero_parte: str + descripcion: str + fraccion: str + fraccion_americana: Optional[str] = "" + origen: str + + advalorem:Optional[str] = "" + preferencia:Optional[str] = "" + + cantidad_importacion: Union[float, str] + unidad_medida: str + cantidad_bultos: int + clave_bultos: str + peso_neto: Union[float, str] + peso_bruto: Union[float, str] + peso_neto_lbs: Union[float, str] = 0.0 + peso_bruto_lbs: Union[float, str] = 0.0 + valor_costo_unitario: Union[float, str] = "" + valor_total: Union[float, str] = "" + +class TotalesSchema(BaseModel): + cantidad_total: Union[float, str] + bultos_total: int + clave_bultos: str = "" + peso_neto_total: Union[float, str] + peso_bruto_total: Union[float, str] + peso_neto_total_lbs: Union[float, str] = 0.0 + peso_bruto_total_lbs: Union[float, str] = 0.0 + valor_total_total: Union[float, str] = "" + valor_total_dolares: Union[float, str] = "" + +class PackingListSchema(BaseModel): + cliente_proveedor: ClienteSchema + cliente_vendido: ClienteSchema + cliente_enviado: ClienteSchema + factura: FacturaSchema + partidas: List[PartidaSchema] + totales: TotalesSchema + logo_b64: Optional[str] = None + diff --git a/backend/api/v1/modules/a76/reports/importacion/packing_list/service.py b/backend/api/v1/modules/a76/reports/importacion/packing_list/service.py new file mode 100644 index 00000000..a6163592 --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/packing_list/service.py @@ -0,0 +1,401 @@ +import shutil +import base64 +import pdfkit +from pathlib import Path +from decimal import Decimal +from typing import Tuple, List, Callable, Optional + +from jinja2 import Environment, FileSystemLoader, select_autoescape +from fastapi import HTTPException +from pydantic import ValidationError +from sqlalchemy.orm import Session + +# --- MODELOS --- +from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics +from api.v1.modules.a76.items.line_quantities.models import LineQuantity +from api.v1.modules.a76.items.line_items.models import LineItem +from api.v1.modules.a76.items.line_customs.models import LineCustom +from api.v1.modules.a76.clients_and_providers.models import ( + ClientProvider, ClientProviderAddress, ClientProviderPrograms +) +from api.v1.modules.a76.parts.models import Part +from api.v1.modules.a76.pedmientos.models import Pedimentos +from api.v1.modules.a76.general_catalogs.company.models import Company +from api.v1.modules.a76.customs_brokers.models import CustomsBroker +from api.v1.modules.a76.items.models import Item + +# --- TRANSPORTATION MODELS --- +from api.v1.modules.a76.transportation.transporters.models import Transporter +from api.v1.modules.a76.transportation.vehicles.models import Vehicle +from api.v1.modules.a76.transportation.trailers.models import Trailer +from api.v1.modules.a76.transportation.drivers.models import Driver + +# --- MODELO DE FRACCIONES --- +from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction + +# --- SCHEMAS --- +from .schemas import ( + ClienteSchema, PartidaSchema, TotalesSchema, + FacturaSchema, PackingListSchema +) + +class PackingListService: + def __init__(self): + self.template_dir = Path(__file__).parent / "templates" + self.jinja_env = Environment( + loader=FileSystemLoader(self.template_dir), + autoescape=select_autoescape(['html', 'xml']) + ) + self.template = self.jinja_env.get_template('packing_list.html') + + def _get_wkhtmltopdf_config(self): + # List of possible paths + paths = [ + shutil.which("wkhtmltopdf"), + "/usr/local/bin/wkhtmltopdf", + "/usr/bin/wkhtmltopdf", + "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe" + ] + + path = next((p for p in paths if p and Path(p).exists()), None) + + if not path: + if shutil.which("echo"): + print("WARNING: wkhtmltopdf not found, PDF generation will fail.") + raise RuntimeError(f"wkhtmltopdf binary not found. Searched in: {paths}") + + return pdfkit.configuration(wkhtmltopdf=path) + + def formatear_numero(self, valor, decimales: int = 2): + if valor is None: return 0.0 + try: + return round(float(valor), decimales) + except: return 0.0 + + def _format_fraccion_fallback(self, fraccion_raw: str) -> str: + if not fraccion_raw or len(fraccion_raw) < 8: + return fraccion_raw or "" + return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}" + + def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema: + main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first() + if not main: + return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX") + + addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first() + prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first() + + return ClienteSchema( + header=rol, + nombre=(main.name or main.short_name) or "S/N", + direccion=(addr.streets or "") if addr else "", + num_exterior=(addr.exterior_number or "") if addr else "", + num_interior=(addr.interior_number or "") if addr else "", + colonia=(addr.neighborhood or "") if addr else "", + codigo_postal=(addr.postal_code or "") if addr else "", + ciudad=(addr.city or "") if addr else "", + estado=(addr.state or "") if addr else "", + pais=(addr.country or "MEX") if addr else "MEX", + tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""), + programa="IMMEX" if (prog and prog.program) else "", + autorizacion=prog.program_number if prog else "", + prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "", + reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else ( + prog.certified_company_registry if (prog and prog.certified_company_registry) else "" + ), + cert=prog.is_certified_company if (prog and prog.is_certified_company) else "" + ) + + def get_packing_list_data(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> PackingListSchema: + try: + if progress_callback: progress_callback(10, "Buscando factura...") + header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first() + if not header: raise HTTPException(status_code=404, detail="Factura no encontrada") + + compliance = header.compliance_mx + logistics = header.logistics if header.logistics else None + financials = header.financials if header.financials else None + + if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...") + pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id + pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None + + if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...") + proveedor_id = compliance.provider_id if compliance else None + cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="") + + nombre_agente = "" + if compliance and compliance.customs_broker_id: + broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first() + if broker: nombre_agente = broker.name + + company = db.query(Company).filter(Company.id == header.company_id).first() + # Datos Default (Company/Importer) + cliente_default = ClienteSchema( + header="Importer / Consignee:", + nombre=getattr(company, 'name', "Empresa Local"), + direccion="DOMICILIO FISCAL", + num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX", + tax_id=getattr(company, 'rfc', ""), + programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "") + ) + + # Left Side Logic (Consignatario / Sold To) + cliente_vendido = cliente_default + if compliance and compliance.sold_to_id: + raw = (compliance.sold_to_header or "").upper() + if "CONSIGN" in raw: + clean_header = "Consignee / Consignatario:" + else: + clean_header = "Sold To / Vendido a:" + + cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header) + + # Right Side Logic (Enviado A / Shipped To) + cliente_enviado = cliente_default + if compliance and compliance.shipped_to_id: + clean_header_shipped = "Shipped To / Enviado a:" + cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped) + + remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else "" + acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A" + + patente_val = "" + if pedimento and pedimento.license: + patente_val = pedimento.license + elif 'broker' in locals() and broker and broker.license: + patente_val = broker.license + + # --- Transport Data Fetching --- + transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else "" + num_transporte_val = (logistics.trailer_num or "") if logistics else "" + + placas_val = (logistics.license_plate or "") if logistics else "" + placas_remolque_val = "" + transportista_val = (logistics.carrier_id or "") if logistics else "" + caat_val = "" + scac_val = "" + licencia_cond_val = "" + + if logistics: + # 1. Transporter (CAAT / SCAC) + if logistics.carrier_id: + transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first() + if transporter_obj: + caat_val = transporter_obj.caat_code or "" + scac_val = transporter_obj.transport_code or "" + transportista_val = transporter_obj.name or logistics.carrier_id + + # 2. Vehicle (Placas Tracto) + if logistics.transport_id: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + elif logistics.vehicle_num: + veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first() + if veh_obj: + placas_val = veh_obj.plate_number or placas_val + + # 3. Trailer (Placas Remolque) + if logistics.trailer_num: + trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first() + if trl_obj: + placas_remolque_val = trl_obj.plate_number or "" + + # 4. Driver (License) + if logistics.carrier_id and logistics.driver_name: + drv_obj = db.query(Driver).filter( + Driver.transporter_key == logistics.carrier_id, + Driver.driver_name == logistics.driver_name + ).first() + if drv_obj: + licencia_cond_val = drv_obj.license_number or "" + + factura_schema = FacturaSchema( + numero=header.invoice_number or "S/N", + fecha=str(header.invoice_date) if header.invoice_date else "", + tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0), + moneda=getattr(header, 'currency', "USD") or "USD", + incoterm=(logistics.incoterm or "") if logistics else "", + observaciones=header.observation_es or header.observation_en or "", + pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "", + clave_pedimento=pedimento.pedimento_code if pedimento else "", + regimen=header.document_type or "", + patente=patente_val, + agente_aduanal=nombre_agente, + transporte=transporte_txt, + num_transporte=num_transporte_val, + placas=placas_val, + placas_remolque=placas_remolque_val, + transportista=transportista_val, + caat=caat_val, + scac=scac_val, + licencia_conductor=licencia_cond_val, + aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""), + precinto=(logistics.seal_number or "") if logistics else "", + destino=(logistics.destination_goods or "") if logistics else "", + remesa=remesa_valor, acuse_electronico=acuse_valor + ) + + if progress_callback: progress_callback(50, "Procesando partidas...") + lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter(Item.invoice_id == header.id).all() + partidas_list = [] + + for line in lines: + qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first() + + # --- WEIGHT CALCULATION LOGIC --- + peso_neto_kg = 0.0 + peso_bruto_kg = 0.0 + peso_neto_lb = 0.0 + peso_bruto_lb = 0.0 + + if qty: + raw_net = float(qty.net_weight or 0) + raw_gross = float(qty.gross_weight or 0) + unit = (qty.weight_unit or "KG").upper() + + if unit == "LB" or unit == "LBS": + peso_neto_lb = raw_net + peso_bruto_lb = raw_gross + peso_neto_kg = raw_net / 2.20462 + peso_bruto_kg = raw_gross / 2.20462 + else: # Default KG + peso_neto_kg = raw_net + peso_bruto_kg = raw_gross + peso_neto_lb = raw_net * 2.20462 + peso_bruto_lb = raw_gross * 2.20462 + # -------------------------------- + + custom_obj = db.query(LineCustom).filter(LineCustom.item_line_id == line.id).first() + part_master = db.query(Part).filter(Part.id == line.part_number).first() + + desc_final = "S/D" + num_parte_final = str(line.part_number or "S/N") + fraccion_raw = "" + origen_final = "MEX" + uom_comercial = "PZA" # Default UOM + + if part_master: + desc_final = part_master.description_spanish or part_master.description_english or "Sin Desc." + num_parte_final = part_master.part_number + fraccion_raw = part_master.fraction if part_master.fraction else "" + # Commercial UOM from Part Master + uom_comercial = part_master.unit_of_measure or "PZA" + + if part_master.fa_data and part_master.fa_data.origin_country: + origen_final = part_master.fa_data.origin_country + + fraccion_limpia = fraccion_raw.replace(".", "").strip() + if fraccion_limpia: + fraccion_limpia = fraccion_limpia[:8].zfill(8) + + fraccion_db = db.query(TariffFraction).filter(TariffFraction.code == fraccion_limpia).first() + + fraccion_imprimir = fraccion_raw + if fraccion_db: + fraccion_imprimir = fraccion_db.fraction or fraccion_raw + else: + fraccion_imprimir = self._format_fraccion_fallback(fraccion_limpia) + + # FOR PACKING LIST: FINANCIALS ARE HIDDEN/EMPTY + v_unitario = "" + v_total = "" + + partidas_list.append(PartidaSchema( + numero_parte=num_parte_final, + descripcion=desc_final, + fraccion=fraccion_imprimir, + fraccion_americana=custom_obj.american_fraction if custom_obj and custom_obj.american_fraction else "", + origen=origen_final, + advalorem="", # Hidden + preferencia="", # Hidden + cantidad_importacion=qty.quantity if qty else 0, + unidad_medida=uom_comercial, # Commercial UOM (PCS, EA) + cantidad_bultos=int(qty.package_quantity) if qty and qty.package_quantity else 0, + clave_bultos=(qty.package_info.key if qty and qty.package_info else "") if qty else "", + peso_neto=self.formatear_numero(peso_neto_kg), + peso_bruto=self.formatear_numero(peso_bruto_kg), + peso_neto_lbs=self.formatear_numero(peso_neto_lb), + peso_bruto_lbs=self.formatear_numero(peso_bruto_lb), + valor_costo_unitario=v_unitario, # Hidden + valor_total=v_total # Hidden + )) + + totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio)) + + return PackingListSchema( + cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido, + cliente_enviado=cliente_enviado, factura=factura_schema, + partidas=partidas_list, totales=totales + ) + + except ValidationError as e: + print(f"Validation Error: {e.json()}") + raise HTTPException(status_code=500, detail=f"Schema Error: {e}") + except Exception as e: + print(f"Error Service A76: {e}") + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema: + cant = sum(float(p.cantidad_importacion) for p in partidas) + # Financial totals hidden + peso_n = sum(float(p.peso_neto) for p in partidas) + peso_b = sum(float(p.peso_bruto) for p in partidas) + peso_n_lbs = sum(float(p.peso_neto_lbs) for p in partidas) + peso_b_lbs = sum(float(p.peso_bruto_lbs) for p in partidas) + + bultos = sum(p.cantidad_bultos for p in partidas) + + claves = [p.clave_bultos for p in partidas if p.clave_bultos] + clave_comun = max(set(claves), key=claves.count) if claves else "" + if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S" + + return TotalesSchema( + cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun, + peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b), + peso_neto_total_lbs=self.formatear_numero(peso_n_lbs), peso_bruto_total_lbs=self.formatear_numero(peso_b_lbs), + valor_total_total="", valor_total_dolares="" + ) + + def generate_pdf(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> Tuple[bytes, str]: + if progress_callback: progress_callback(5, "Iniciando servicio de reporte...") + data = self.get_packing_list_data(db, invoice_id, company_id, progress_callback) + + if progress_callback: progress_callback(80, "Renderizando plantilla...") + + # LOGO LOGIC + logo_b64 = None + try: + comp_logo = db.query(Company).filter(Company.id == company_id).first() + if comp_logo and comp_logo.logo: + p = Path(comp_logo.logo) + target_path = p + if not target_path.exists(): + fallback = Path(f"app_data/logos/{company_id}") / p.name + if fallback.exists(): + target_path = fallback + + if target_path.exists(): + with open(target_path, "rb") as image_file: + encoded_string = base64.b64encode(image_file.read()).decode('utf-8') + mime = "image/png" + if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg" + logo_b64 = f"data:{mime};base64,{encoded_string}" + except Exception as e: + print(f"Error loading logo: {e}") + + data.logo_b64 = logo_b64 # Assign logo to schema + + context = data.model_dump() + html_content = self.template.render(**context) + + if progress_callback: progress_callback(90, "Generando PDF final...") + + options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None} + pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config()) + + if progress_callback: progress_callback(100, "Completado") + + filename = f"PackingList_{data.factura.numero}.pdf" + return pdf, filename diff --git a/backend/api/v1/modules/a76/reports/importacion/packing_list/task.py b/backend/api/v1/modules/a76/reports/importacion/packing_list/task.py new file mode 100644 index 00000000..bf55991b --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/packing_list/task.py @@ -0,0 +1,51 @@ +import base64 +from core.celery_app import celery_app +from core.database import CoreSessionLocal +from .service import PackingListService + +@celery_app.task(bind=True) +def generar_packing_list_async(self, invoice_id: int, company_id: int): + """ + Tarea asíncrona para generar el Packing List + """ + db = CoreSessionLocal() + try: + service = PackingListService() + + def update_progress(percent, message): + self.update_state( + state='PROCESSING', + meta={ + 'current': percent, + 'total': 100, + 'status': message + } + ) + + pdf_bytes, filename = service.generate_pdf(db, invoice_id, company_id, update_progress) + + # Codificar a base64 para enviar por JSON + pdf_b64 = base64.b64encode(pdf_bytes).decode('utf-8') + + return { + 'status': 'success', + 'file_name': filename, + 'content': pdf_b64, + 'media_type': 'application/pdf' + } + + except Exception as e: + print(f"Error en tarea Packing List: {e}") + import traceback + traceback.print_exc() + self.update_state( + state='FAILURE', + meta={ + 'exc_type': type(e).__name__, + 'exc_message': str(e), + 'custom': 'Error generating PDF' + } + ) + raise e + finally: + db.close() diff --git a/backend/api/v1/modules/a76/reports/importacion/packing_list/templates/packing_list.html b/backend/api/v1/modules/a76/reports/importacion/packing_list/templates/packing_list.html new file mode 100644 index 00000000..a82f2aaa --- /dev/null +++ b/backend/api/v1/modules/a76/reports/importacion/packing_list/templates/packing_list.html @@ -0,0 +1,519 @@ + + + + + + Packing List - {{ factura.numero }} + + + + +
+
+
+

PACKING LIST / LISTA DE EMPAQUE

+
+

+
+
+ + + + + + + + + + + +
+

PACKING LIST / LISTA DE EMPAQUE:

+
+

{{ factura.numero }}

+
+

MX CUSTOM BROKER / AGENTE ADUANAL MEXICANO:

+
+

{{ factura.agente_aduanal or '' }}

+
+
+
+
+
+ {% if logo_b64 %} +
+ +
+ {% endif %} +
+

{{ cliente_proveedor.header }}

+

{{ cliente_proveedor.nombre }}

+

{{ cliente_proveedor.direccion }} + {% if cliente_proveedor.num_exterior %} Ext: {{ cliente_proveedor.num_exterior }}{% endif %} + {% if cliente_proveedor.num_interior %} Int: {{ cliente_proveedor.num_interior }}{% endif %} +

+

{{ cliente_proveedor.colonia }} {% if cliente_proveedor.codigo_postal %} CP: {{ + cliente_proveedor.codigo_postal }}{% endif %}

+

{{ cliente_proveedor.ciudad }}, {{ cliente_proveedor.estado }}, {{ cliente_proveedor.pais }}

+

TAX ID: {{ cliente_proveedor.tax_id }} + {% if cliente_proveedor.programa and cliente_proveedor.programa != 'Ninguno' %} + {{ cliente_proveedor.programa }}: {{ cliente_proveedor.autorizacion }} + {% endif %} +

+


+
+
+ + +
+ +
+
+

{{ cliente_vendido.header }}

+

{{ cliente_vendido.nombre }}

+

{{ cliente_vendido.direccion }} + {% if cliente_vendido.num_exterior %} Ext: {{ cliente_vendido.num_exterior }}{% endif %} + {% if cliente_vendido.num_interior %} Int: {{ cliente_vendido.num_interior }}{% endif %} +

+

{{ cliente_vendido.colonia }} {% if cliente_vendido.codigo_postal %} CP: {{ + cliente_vendido.codigo_postal }}{% endif %}

+

{{ cliente_vendido.ciudad }}, {{ cliente_vendido.estado }}, {{ cliente_vendido.pais }} +

+

RFC: {{ cliente_vendido.tax_id }} + {% if cliente_vendido.programa and cliente_vendido.programa != 'Ninguno' %} + {{ cliente_vendido.programa }}: {{ cliente_vendido.autorizacion }} + {% endif %} +

+

+ {% if cliente_vendido.prosec %}PROSEC: {{ cliente_vendido.prosec }} {% endif %} + {% if cliente_vendido.reg_emp %}REG EMP: {{ cliente_vendido.reg_emp }} {% endif %} + {% if cliente_vendido.cert %}CERT: {{ cliente_vendido.cert }}{% endif %} +

+
+ +
+

{{ cliente_enviado.header }}

+

{{ cliente_enviado.nombre }}

+

{{ cliente_enviado.direccion }} + {% if cliente_enviado.num_exterior %} Ext: {{ cliente_enviado.num_exterior }}{% endif %} + {% if cliente_enviado.num_interior %} Int: {{ cliente_enviado.num_interior }}{% endif %} +

+

{{ cliente_enviado.colonia }} {% if cliente_enviado.codigo_postal %} CP: {{ + cliente_enviado.codigo_postal }}{% endif %}

+

{{ cliente_enviado.ciudad }}, {{ cliente_enviado.estado }}, {{ cliente_enviado.pais }} +

+

RFC: {{ cliente_enviado.tax_id }} + {% if cliente_enviado.programa and cliente_enviado.programa != 'Ninguno' %} + {{ cliente_enviado.programa }}: {{ cliente_enviado.autorizacion }} + {% endif %} +

+

+ {% if cliente_enviado.prosec %}PROSEC: {{ cliente_enviado.prosec }} {% endif %} + {% if cliente_enviado.reg_emp %}REG EMP: {{ cliente_enviado.reg_emp }} {% endif %} + {% if cliente_enviado.cert %}CERT: {{ cliente_enviado.cert }}{% endif %} +

+
+
+


+
+ + + + + + + + + + + + + + + + + + + + + + + + + + {% for partida in partidas %} + + + + + + + + + + + {% endfor %} + + + + + + + + + + + + + + + + + + + + +
+

Line / Línea

+
+

Part Number / Número de Parte

+

Description / Descripción

+
+

Quantity / Cantidad

+
+

Packing / Empaque

+
+

Weight / Peso (KGS)

+
+

Qty / Cant.

+
+

U.M.

+
+

Qty / Cant.

+
+

Type / Tipo

+
+

Net / Neto

+

(LBS / KGS)

+
+

Gross / Bruto

+

(LBS / KGS)

+
+

{{ loop.index }}

+
+

{{ partida.numero_parte }}

+

{{ partida.descripcion }} / {{ partida.fraccion_americana }} / {{ partida.origen }} +

+
+

{{ partida.cantidad_importacion }}

+
+

{{ partida.unidad_medida }}

+
+

+ {% if partida.cantidad_bultos != 0 %}{{ partida.cantidad_bultos }}{% endif %} +

+
+

+ {{ partida.clave_bultos }} +

+
+

{{ partida.peso_neto_lbs }}

+

{{ partida.peso_neto }}

+
+

{{ partida.peso_bruto_lbs }}

+

{{ partida.peso_bruto }}

+
+

+ Observaciones: + TOTALES +

+
+

{{ totales.cantidad_total }}

+
+

+ {% if totales.bultos_total != 0 %}{{ totales.bultos_total }}{% endif %} +

+
+

+ {{ totales.clave_bultos or '' }} +

+
+

{{ totales.peso_neto_total_lbs }} LBS

+

{{ totales.peso_neto_total }} KGS

+
+

{{ totales.peso_bruto_total_lbs }} LBS

+

{{ totales.peso_bruto_total }} KGS

+
+

{{ factura.observaciones }}

+
+

+

{{ cliente_proveedor.nombre }}

+


+
+


+
+ + + \ No newline at end of file diff --git a/backend/api/v1/modules/a76/router.py b/backend/api/v1/modules/a76/router.py index bc21783a..01c8c57d 100644 --- a/backend/api/v1/modules/a76/router.py +++ b/backend/api/v1/modules/a76/router.py @@ -51,7 +51,9 @@ from api.v1.modules.public.reference_data.material_types.routes import router as # --- NUEVO IMPORT PARA REPORTES DE FACTURAS --- from .reports.importacion.facturas.routes import router as invoices_reports_router from .reports.importacion.consolidados.routes import router as consolidated_reports_router -from .reports.movements.invoices.routes import router as invoice_movements_router +from .reports.importacion.packing_list.routes import router as packing_list_router +from .reports.exportacion.aviso_consolidado.routes import router as aviso_consolidado_export_router + # Router principal @@ -134,7 +136,13 @@ router.include_router( ) router.include_router( - invoice_movements_router, - prefix="/a76/reports/movements/invoices", - tags=["a76 / reports / movements"] + packing_list_router, + prefix="/a76/reports/importacion/packing-lists", + tags=["a76 / reports"] +) + +router.include_router( + aviso_consolidado_export_router, + prefix="/a76/reports/exportacion/aviso_consolidado", + tags=["a76 / reports"] ) \ No newline at end of file diff --git a/backend/api/v1/modules/public/reference_data/conftest.py b/backend/api/v1/modules/public/reference_data/conftest.py index 2b5b3377..58e30506 100644 --- a/backend/api/v1/modules/public/reference_data/conftest.py +++ b/backend/api/v1/modules/public/reference_data/conftest.py @@ -12,6 +12,9 @@ def access_token(): @pytest.fixture(scope="session") def client(): + from api.v1.modules.public.reference_data.countries.routes import router as countries_router + from api.v1.modules.public.reference_data.transport_types.routes import router as transport_types_router app = FastAPI() - app.include_router(router) + app.include_router(countries_router) + app.include_router(transport_types_router) return TestClient(app) diff --git a/backend/api/v1/modules/public/reference_data/countries/routes.py b/backend/api/v1/modules/public/reference_data/countries/routes.py index 4bd30d05..45d76eea 100644 --- a/backend/api/v1/modules/public/reference_data/countries/routes.py +++ b/backend/api/v1/modules/public/reference_data/countries/routes.py @@ -15,13 +15,26 @@ router = APIRouter(prefix="/countries") async def list_countries( page: int = Query(1, ge=1, description="Número de página"), page_size: int = Query(50, ge=1, le=100, description="Tamaño de página"), + search: str = Query(None, description="Término de búsqueda"), db: Session = Depends(get_core_db), ): """Endpoint público para obtener lista de países - no requiere autenticación""" skip = (page - 1) * page_size query = db.query(Country) - items = query.offset(skip).limit(page_size).all() + + if search: + search_filter = f"%{search}%" + query = query.filter( + (Country.m3_key.ilike(search_filter)) | + (Country.mex_key.ilike(search_filter)) | + (Country.ame_key.ilike(search_filter)) | + (Country.description_es.ilike(search_filter)) | + (Country.description_en.ilike(search_filter)) + ) + total = query.count() + items = query.offset(skip).limit(page_size).all() + return { "items": [CountryDTO.model_validate(obj) for obj in items], "total": total, diff --git a/backend/api/v1/modules/public/reference_data/countries/test_countries.py b/backend/api/v1/modules/public/reference_data/countries/test_countries.py index ab4da9f8..603217ac 100644 --- a/backend/api/v1/modules/public/reference_data/countries/test_countries.py +++ b/backend/api/v1/modules/public/reference_data/countries/test_countries.py @@ -9,13 +9,17 @@ client = TestClient(app) @pytest.mark.usefixtures("client", "access_token") -def test_list_countries(client, access_token): +def test_list_countries_with_search(client, access_token): headers = {"Authorization": f"Bearer {access_token}"} - response = client.get("/countries/", headers=headers) + # Search for a known country from seed, e.g., "Mexico" or "MEX" + response = client.get("/countries/?search=Mexico", headers=headers) assert response.status_code == 200 - assert "items" in response.json() - assert "page" in response.json() - assert "page_size" in response.json() + data = response.json() + assert "items" in data + # Depending on seed data, there should be at least one item if "Mexico" exists + if data["items"]: + for item in data["items"]: + assert "mexico" in item["description_es"].lower() or "mexico" in item["description_en"].lower() @pytest.mark.usefixtures("client", "access_token") diff --git a/backend/core/celery_app.py b/backend/core/celery_app.py index c118db31..3e41aa5f 100644 --- a/backend/core/celery_app.py +++ b/backend/core/celery_app.py @@ -10,7 +10,9 @@ celery_app = Celery( backend=valkey_url, include=[ "api.v1.modules.a76.reports.importacion.facturas.task", - "api.v1.modules.a76.reports.importacion.consolidados.task" + "api.v1.modules.a76.reports.importacion.consolidados.task", + "api.v1.modules.a76.reports.importacion.packing_list.task", + "api.v1.modules.a76.reports.exportacion.aviso_consolidado.task" ] # Ruta al módulo donde están las tareas ) diff --git a/backend/core/config.py b/backend/core/config.py index c27954eb..37c5d52f 100644 --- a/backend/core/config.py +++ b/backend/core/config.py @@ -42,8 +42,16 @@ class Settings(BaseSettings): # License LICENSE_CHECK_ENABLED: bool = True + # External APIs + SITAR_API_URL: str = "api.sitar.aduanasoft.com:880" + SITAR_API_USER: str = "" + SITAR_API_PASSWORD: str = "" + model_config = SettingsConfigDict( - env_file=".env", case_sensitive=True, extra="ignore", env_file_encoding="utf-8" + env_file=[".env", "../.env"], + case_sensitive=True, + extra="ignore", + env_file_encoding="utf-8", ) @property diff --git a/backend/core/error_handlers.py b/backend/core/error_handlers.py index 4fe62025..e1f7783a 100644 --- a/backend/core/error_handlers.py +++ b/backend/core/error_handlers.py @@ -7,6 +7,7 @@ from typing import Any, Dict from fastapi import Request, status from fastapi.responses import JSONResponse +from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from sqlalchemy.exc import IntegrityError, SQLAlchemyError @@ -37,7 +38,7 @@ async def base_exception_handler( return JSONResponse( status_code=exc.status_code, - content=exc.to_dict(), + content=jsonable_encoder(exc.to_dict()), ) diff --git a/backend/requirements.txt b/backend/requirements.txt index ff7a7cfa..c169f2ca 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -21,6 +21,7 @@ passlib[bcrypt]==1.7.4 httpx==0.28.1 requests==2.32.5 + # Utilities python-multipart==0.0.20 python-dotenv==1.1.1 @@ -46,4 +47,7 @@ pdfkit==1.0.0 # Desarrollo en seguno plano celery==5.3.6 redis==5.0.1 -flower==2.0.1 \ No newline at end of file +flower==2.0.1 + +# Barcode +pdf417gen==0.8.1 \ No newline at end of file diff --git a/debug_values.py b/debug_values.py deleted file mode 100644 index 337140ee..00000000 --- a/debug_values.py +++ /dev/null @@ -1,76 +0,0 @@ -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from api.v1.modules.a76.items.line_items.models import LineItem -from api.v1.modules.a76.items.line_quantities.models import LineQuantity -from api.v1.modules.a76.items.line_financials.models import LineFinancial -from api.v1.modules.a76.parts.models import Part -from api.v1.modules.a76.invoices.models import InvoiceHeader -from api.v1.modules.a76.pedmientos.models import Pedimentos - -# Setup DB (Adjust connection string if needed, checking environment assumption) -# Assuming local connection string or deriving from environment/config -# For this environment, I'll attempt a standard connection or reuse existing if possible. -# Since I cannot easily import 'db' from main app without setup, I will rely on standard raw SQL or simple ORM setup if I can import 'Session'. -# Using the imports available in the user's file. - -import sys -sys.path.append('/home/josmar/dev/anexo76/backend') - -from core.database import CoreSessionLocal - -# Manual Session creation -db = CoreSessionLocal() - -try: - # 1. Find the lines matching the description (Qty 1500 + HTS) - # The user said HTS: 2710190650 - # Qty: 1500 - - print("--- SEARCHING FOR LINES ---") - - # We look for lines with quantity 1500 first - candidates = db.query(LineItem).join(LineQuantity).filter( - LineQuantity.quantity == 1500 - ).all() - - found = False - for line in candidates: - part = db.query(Part).filter(Part.id == line.part_number).first() - fin = db.query(LineFinancial).filter(LineFinancial.item_line_id == line.id).first() - inv = db.query(InvoiceHeader).filter(InvoiceHeader.id == line.item.invoice_id).first() if line.item else None - - us_frac = part.us_fraction if part else "N/A" - - # Check fraction match (loose match) - if "2710190650" in us_frac.replace(".","").replace(" ",""): - found = True - print(f"\nMATCH FOUND: Line ID {line.id} - Invoice {inv.invoice_number if inv else 'N/A'}") - print(f"HTS: {us_frac}") - print(f"Qty: {1500}") - print(f"Inv Currency: {inv.financials.currency} / {inv.financials.currency_type} Rate: {inv.financials.exchange_rate}") - - print("\nFINANCIALS:") - if fin: - print(f" value_usd: {fin.value_usd}") - print(f" value_mxn: {fin.value_mxn}") - print(f" value_commercial_usd: {fin.value_commercial_usd}") - print(f" value_commercial_mxn: {fin.value_commercial_mxn}") - print(f" unit_cost_usd: {fin.unit_cost_usd}") - print(f" unit_cost_commercial_usd: {fin.unit_cost_commercial_usd}") - print(f" unit_cost_mxn: {fin.unit_cost_mxn}") - - # Check calculation hypothesis - val_usd = float(fin.value_usd or 0) - val_mxn = float(fin.value_mxn or 0) - rate = float(inv.financials.exchange_rate or 1) - - print(f"\n If using ValueMXN/Rate: {val_mxn} / {rate} = {val_mxn/rate}") - print(f" If using Max(MXN, USD): {max(val_mxn, val_usd)}") - else: - print(" No Financials found.") - - if not found: - print("No matching line (1500 qty, HTS 2710190650) found.") - -finally: - db.close() diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index eb05fe4c..4eabf108 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -159,6 +159,9 @@ services: - KEYCLOAK_CLIENT_ID=${KEYCLOAK_CLIENT_ID:-anexo76-backend} - KEYCLOAK_CLIENT_SECRET=${KEYCLOAK_CLIENT_SECRET:-dev-secret} - CORS_ORIGINS=${CORS_ORIGINS:-https://anexo76-dev.aduanasoft.com,http://localhost:3000} + - SITAR_API_URL=${SITAR_API_URL} + - SITAR_API_USER=${SITAR_API_USER} + - SITAR_API_PASSWORD=${SITAR_API_PASSWORD} ports: - "3467:8000" depends_on: @@ -166,7 +169,8 @@ services: condition: service_healthy keycloak: condition: service_healthy - volumes: + volumes: + - backend_uploads:/app/uploads - ./scripts/backend-entrypoint.sh:/entrypoint.sh:ro networks: - backend-net @@ -180,11 +184,13 @@ services: "-k", "uvicorn.workers.UvicornWorker", "-w", - "${WEB_CONCURRENCY:-4}", + "${WEB_CONCURRENCY:-1}", "-b", "0.0.0.0:8000", "--log-level", - "info" + "info", + "--forwarded-allow-ips", + "*" ] healthcheck: test: ["CMD-SHELL", "curl -f http://localhost:8000/api/health || exit 1"] @@ -204,6 +210,28 @@ services: reservations: memory: 256M + # celery + celery_worker: + image: dev.aduanasoft.com/anexo76/backend:latest + container_name: worker + command: celery -A core.celery_app worker --loglevel=info + environment: + - VALKEY_URL=redis://valkey:6379/0 + depends_on: + - backend + - valkey + networks: + - backend-net + + valkey: + image: valkey/valkey:7.2 + container_name: valkey + restart: always + ports: + - "6579:6379" + networks: + - backend-net + # Frontend - SvelteKit frontend: image: dev.aduanasoft.com/anexo76/frontend:latest @@ -262,6 +290,8 @@ volumes: driver: local backend_cache: driver: local + backend_uploads: + driver: local networks: backend-net: diff --git a/docker-compose.yml b/docker-compose.yml index c26575a5..041c1bdf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -175,6 +175,9 @@ services: - KEYCLOAK_CLIENT_ID=${KEYCLOAK_CLIENT_ID:-anexo76-backend} - KEYCLOAK_CLIENT_SECRET=${KEYCLOAK_CLIENT_SECRET:-dev-secret} - CORS_ORIGINS=${CORS_ORIGINS:-http://localhost:5173,http://localhost:3000} + - SITAR_API_URL=${SITAR_API_URL} + - SITAR_API_USER=${SITAR_API_USER} + - SITAR_API_PASSWORD=${SITAR_API_PASSWORD} ports: - "8000:8000" depends_on: @@ -185,6 +188,7 @@ services: volumes: - ./backend:/app - backend_cache:/app/__pycache__ + - backend_uploads:/app/uploads - ./scripts/backend-entrypoint.sh:/entrypoint.sh:ro networks: - backend-net @@ -265,7 +269,7 @@ services: # celery celery_worker: build: ./backend - container_name: a76_worker + container_name: worker command: celery -A core.celery_app worker --loglevel=info environment: - VALKEY_URL=redis://valkey:6379/0 @@ -277,7 +281,7 @@ services: valkey: image: valkey/valkey:7.2 - container_name: a76_valkey + container_name: valkey restart: always ports: - "6379:6379" @@ -295,6 +299,8 @@ volumes: driver: local backend_cache: driver: local + backend_uploads: + driver: local networks: backend-net: diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 541dac72..49d51d59 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -41,7 +41,7 @@ "valuation_methods": "Valuation Methods", "countries": "Countries", "ports": "Ports", - "unit_measures": "Units of Measure - General", + "unit_measures": "Units of Measure", "um_customs_mex": "Units of Measure - Mexican Customs", "um_customs_ame": "Units of Measure - American Customs", "um_ace": "Units of Measure - ACE", @@ -65,7 +65,7 @@ }, "goods": { "title": "Goods", - "classes": "Classes", + "classes": "Classes", "parts": "Parts" }, "pedimentos": { @@ -77,24 +77,29 @@ "customs_sections": "Customs Sections", "anexo_22_app_31": "Anexo 22 App 3" }, - "import_invoices":{ + "import_invoices": { "title": "Import Invoices", "temporary": "Temporary", "definitive": "Definitive", "mexican_purchases": "Mexican Purchases", - "regime_change": "Regime Change" + "regime_change": "Regime Change" }, "export_invoices": { "title": "Export Invoices", - "exportation": "Exportation", + "exportation": "Exportation", "repair": "Repair" }, "clients_and_providers": "Clients and Providers", "customs_brokers": "Customs Brokers", + "client_provider_type": { + "client_indicator": "C", + "provider_indicator": "P", + "both_indicator": "B" + }, "nav_user": { "profile": "Profile", "settings": "Settings", "logout": "Logout" } } -} +} \ No newline at end of file diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 9e2a85c5..48dcc061 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -1,33 +1,33 @@ { - "$schema": "https://inlang.com/schema/inlang-message-format", - "hello_world": "Hello, {name} from es!", - "sidebar": { - "reference_data": { - "title": "Catálogos Fijos", - "codes_pedimento_regimen": "Códigos de Pedimento y Régimen", - "containers": "Contenedores", - "countries": "Países", - "currency_types": "Tipos de moneda", - "customs_sections": "Secciones de aduanas", - "customs_warehouses": "Recintos", - "incoterms": "Incoterms", - "invoice_types": "Tipos de factura", - "material_types": "Tipos de material", - "payment_methods": "Métodos de pago", - "pedimento_codes": "Códigos de pedimento", - "pedimento_regimes": "Regímenes de pedimentos", - "sectors": "Sectores", - "states": "Estados", - "transportation_modes": "Métodos de transporte", - "transportation_types": "Tipos de transporte", - "valuation_methods": "Métodos de valoración", - "configuracion": "Configuración", - "general": "General", - "licencia": "Licencia", - "usuarios": "Usuarios", - "ayuda": "Ayuda" - }, - "general_catalogs": { + "$schema": "https://inlang.com/schema/inlang-message-format", + "hello_world": "Hello, {name} from es!", + "sidebar": { + "reference_data": { + "title": "Catálogos Fijos", + "codes_pedimento_regimen": "Códigos de Pedimento y Régimen", + "containers": "Contenedores", + "countries": "Países", + "currency_types": "Tipos de moneda", + "customs_sections": "Secciones de aduanas", + "customs_warehouses": "Recintos", + "incoterms": "Incoterms", + "invoice_types": "Tipos de factura", + "material_types": "Tipos de material", + "payment_methods": "Métodos de pago", + "pedimento_codes": "Códigos de pedimento", + "pedimento_regimes": "Regímenes de pedimentos", + "sectors": "Sectores", + "states": "Estados", + "transportation_modes": "Métodos de transporte", + "transportation_types": "Tipos de transporte", + "valuation_methods": "Métodos de valoración", + "configuracion": "Configuración", + "general": "General", + "licencia": "Licencia", + "usuarios": "Usuarios", + "ayuda": "Ayuda" + }, + "general_catalogs": { "title": "Catalogos Generales", "company_information": "Información de la empresa", "packages": "Bultos", @@ -41,7 +41,7 @@ "valuation_methods": "Metódos de valoración", "countries": "Países", "ports": "Puertos", - "unit_measures": "UM general", + "unit_measures": "Unidades de medida", "um_customs_mex": "UM Aduanas MX", "um_customs_ame": "UM Aduanas USA", "um_ace": "UM ACE", @@ -65,10 +65,10 @@ }, "goods": { "title": "Mercancías", - "classes": "Clases", + "classes": "Clases", "parts": "Partes" }, - "pedimentos": { + "pedimentos": { "title": "Pedimentos", "pedimento_management": "Gestión de Pedimentos", "pedimento_codes": "Claves de Pedimento", @@ -77,23 +77,28 @@ "customs_sections": "Secciones Aduaneras", "anexo_22_app_31": "Anexo 22 App 3" }, - "import_invoices":{ + "import_invoices": { "title": "Facturas de importación", "temporary": "Temporal", "definitive": "Definitiva", "mexican_purchases": "Compras mexicanas", - "regime_change": "Cambio de régimen" + "regime_change": "Cambio de régimen" }, "export_invoices": { "title": "Facturas de exportación", - "exportation": "Exportación", + "exportation": "Exportación", "repair": "Reparación" }, "clients_and_providers": "Clientes y Proveedores", "customs_brokers": "Agentes Aduanales", + "client_provider_type": { + "client_indicator": "C", + "provider_indicator": "P", + "both_indicator": "A" + }, "nav_user": { "profile": "Perfil", "settings": "Configuración" } - } + } } \ No newline at end of file diff --git a/frontend/src/app.css b/frontend/src/app.css index 8d9a66ab..6c344082 100644 --- a/frontend/src/app.css +++ b/frontend/src/app.css @@ -118,6 +118,6 @@ @apply border-border outline-ring/50; } body { - @apply bg-background text-foreground; + @apply bg-background text-foreground overflow-x-hidden; } } diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index f17d6fd5..fdf78609 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -315,27 +315,27 @@ export const api = { // Endpoints específicos auth: { login: (credentials: { username: string; password: string; tenant_slug: string }) => - api.post('/v1/auth/login', credentials), + api.post('/v1/auth/login/', credentials), refresh: (refreshToken: string) => - api.post('/v1/auth/refresh', { refresh_token: refreshToken }), - logout: (data: { refresh_token: string }) => api.post('/v1/auth/logout', data), - me: () => api.get('/v1/auth/me'), + api.post('/v1/auth/refresh/', { refresh_token: refreshToken }), + logout: (data: { refresh_token: string }) => api.post('/v1/auth/logout/', data), + me: () => api.get('/v1/auth/me/'), health: () => api.get('/health') }, tenants: { list: (page = 1, pageSize = 50) => - api.get(`/v1/tenants?page=${page}&page_size=${pageSize}`), - get: (id: number) => api.get(`/v1/tenants/${id}`), - create: (data: any) => api.post('/v1/tenants', data), - update: (id: number, data: any) => api.put(`/v1/tenants/${id}`, data) + api.get(`/v1/tenants/?page=${page}&page_size=${pageSize}`), + get: (id: number) => api.get(`/v1/tenants/${id}/`), + create: (data: any) => api.post('/v1/tenants/', data), + update: (id: number, data: any) => api.put(`/v1/tenants/${id}/`, data) }, licenses: { - get: (tenantId: number) => api.get(`/v1/licenses/tenant/${tenantId}`), - myLicense: () => api.get('/v1/licenses/my-license'), - usage: (tenantId: number) => api.get(`/v1/licenses/usage/${tenantId}`), - validate: (tenantId: number) => api.get(`/v1/licenses/validate/${tenantId}`) + get: (tenantId: number) => api.get(`/v1/licenses/tenant/${tenantId}/`), + myLicense: () => api.get('/v1/licenses/my-license/'), + usage: (tenantId: number) => api.get(`/v1/licenses/usage/${tenantId}/`), + validate: (tenantId: number) => api.get(`/v1/licenses/validate/${tenantId}/`) }, // Generic request for custom needs (like file uploads) diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/company.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/company.ts index 0c7fab48..ee507945 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/company.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/company.ts @@ -19,8 +19,7 @@ export interface Company { responsible_last_name: string | null; responsible_mother_last_name: string | null; responsible_rfc?: string | null; - position?: string | null; - logo?: string | null; + position?: string | null; has_express_line?: boolean; is_service_company?: boolean; order_format_type?: string | null; @@ -103,7 +102,7 @@ export async function getCompanies( page_size: pageSize.toString(), ...filters }); - return await api.get(`/v1/a76/company?${queryParams.toString()}`); + return await api.get(`/v1/a76/company/?${queryParams.toString()}`); } export async function getCompany(id: number): Promise> { @@ -111,7 +110,7 @@ export async function getCompany(id: number): Promise> { } export async function createCompany(data: CompanyCreate): Promise> { - return await api.post(`/v1/a76/company`, data); + return await api.post(`/v1/a76/company/`, data); } export async function updateCompany(id: number, data: CompanyUpdate): Promise> { @@ -119,7 +118,7 @@ export async function updateCompany(id: number, data: CompanyUpdate): Promise> { - return await api.delete(`/v1/a76/company/${id}`); + return await api.delete(`/v1/a76/company/${id}/`); } export async function uploadCompanyLogo(id: number, file: File): Promise> { diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/concepts.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/concepts.ts index 86a58061..6232e3ce 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/concepts.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/concepts.ts @@ -57,25 +57,25 @@ export async function getConcepts( ...filters }); - return await api.get(`/v1/a76/concepts?${params.toString()}`); + return await api.get(`/v1/a76/concepts/?${params.toString()}`); } export async function getConcept(id: number, companyId: number): Promise> { - return await api.get(`/v1/a76/concepts/${id}?company_id=${companyId}`); + return await api.get(`/v1/a76/concepts/${id}/?company_id=${companyId}`); } export async function createConcept(data: ConceptCreate, companyId: number): Promise> { - return await api.post(`/v1/a76/concepts?company_id=${companyId}`, data); + return await api.post(`/v1/a76/concepts/?company_id=${companyId}`, data); } export async function updateConcept(id: number, data: ConceptUpdate, companyId: number): Promise> { - return await api.put(`/v1/a76/concepts/${id}?company_id=${companyId}`, data); + return await api.put(`/v1/a76/concepts/${id}/?company_id=${companyId}`, data); } export async function deleteConcept(id: number, companyId: number): Promise> { - return await api.delete(`/v1/a76/concepts/${id}?company_id=${companyId}`); + return await api.delete(`/v1/a76/concepts/${id}/?company_id=${companyId}`); } \ No newline at end of file diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/customs-broker-concepts.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/customs-broker-concepts.ts index ae54fce5..2d53c469 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/customs-broker-concepts.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/customs-broker-concepts.ts @@ -43,21 +43,21 @@ export async function getCustomsBrokerConcepts( ...filters }); - return await api.get(`/v1/a76/customs-broker-concepts?${params.toString()}`); + return await api.get(`/v1/a76/customs-broker-concepts/?${params.toString()}`); } export async function getCustomsBrokerConcept(id: number, companyId: number): Promise> { - return await api.get(`/v1/a76/customs-broker-concepts/${id}?company_id=${companyId}`); + return await api.get(`/v1/a76/customs-broker-concepts/${id}/?company_id=${companyId}`); } export async function createCustomsBrokerConcept(data: CustomsBrokerConceptCreate, companyId: number): Promise> { - return await api.post(`/v1/a76/customs-broker-concepts?company_id=${companyId}`, data); + return await api.post(`/v1/a76/customs-broker-concepts/?company_id=${companyId}`, data); } export async function updateCustomsBrokerConcept(id: number, data: CustomsBrokerConceptUpdate, companyId: number): Promise> { - return await api.put(`/v1/a76/customs-broker-concepts/${id}?company_id=${companyId}`, data); + return await api.put(`/v1/a76/customs-broker-concepts/${id}/?company_id=${companyId}`, data); } export async function deleteCustomsBrokerConcept(id: number, companyId: number): Promise> { - return await api.delete(`/v1/a76/customs-broker-concepts/${id}?company_id=${companyId}`); + return await api.delete(`/v1/a76/customs-broker-concepts/${id}/?company_id=${companyId}`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/doda.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/doda.ts index d9cc41ac..e6ae28dc 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/doda.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/doda.ts @@ -178,7 +178,7 @@ export async function getDodas( if (companyId) { params.append('company_id', companyId.toString()); } - const response = await api.get(`/v1/a76/doda?${params.toString()}`); + const response = await api.get(`/v1/a76/doda/?${params.toString()}`); return response.data; } @@ -187,20 +187,20 @@ export async function getDoda(id: number, companyId?: number): Promise { if (companyId) { params.append('company_id', companyId.toString()); } - const response = await api.get(`/v1/a76/doda/${id}?${params.toString()}`); + const response = await api.get(`/v1/a76/doda/${id}/?${params.toString()}`); return response.data; } export async function createDoda(data: DodaCreate, companyId: number): Promise { - const response = await api.post(`/v1/a76/doda?company_id=${companyId}`, data); + const response = await api.post(`/v1/a76/doda/?company_id=${companyId}`, data); return response.data; } export async function updateDoda(id: number, data: DodaUpdate, companyId: number): Promise { - const response = await api.put(`/v1/a76/doda/${id}?company_id=${companyId}`, data); + const response = await api.put(`/v1/a76/doda/${id}/?company_id=${companyId}`, data); return response.data; } export async function deleteDoda(id: number, companyId: number): Promise { - await api.delete(`/v1/a76/doda/${id}?company_id=${companyId}`); + await api.delete(`/v1/a76/doda/${id}/?company_id=${companyId}`); } \ No newline at end of file diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/exchange-rate.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/exchange-rate.ts index b8b94a40..0ef3e8a5 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/exchange-rate.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/exchange-rate.ts @@ -37,10 +37,12 @@ export interface ExchangeRateFilters { page_size?: number; } +import type { ApiResponse } from '$lib/api'; + export async function getExchangeRates( companyId: number, filters?: ExchangeRateFilters -): Promise { +): Promise> { const params = new URLSearchParams({ company_id: companyId.toString() }); if (filters) { @@ -57,7 +59,7 @@ export async function getExchangeRates( export async function getExchangeRate( exchangeRateId: number, companyId: number -): Promise { +): Promise> { const params = new URLSearchParams({ company_id: companyId.toString() }); return api.get(`/v1/a76/exchange-rate/${exchangeRateId}?${params.toString()}`); } @@ -65,7 +67,7 @@ export async function getExchangeRate( export async function createExchangeRate( data: ExchangeRateCreate, companyId: number -): Promise { +): Promise> { const params = new URLSearchParams({ company_id: companyId.toString() }); return api.post(`/v1/a76/exchange-rate/?${params.toString()}`, data); } @@ -74,10 +76,10 @@ export async function updateExchangeRate( exchangeRateId: number, data: ExchangeRateUpdate, companyId: number -): Promise { +): Promise> { const params = new URLSearchParams({ company_id: companyId.toString() }); return api.put( - `/v1/a76/exchange-rate/${exchangeRateId}?${params.toString()}`, + `/v1/a76/exchange-rate/${exchangeRateId}/?${params.toString()}`, data ); } @@ -85,7 +87,17 @@ export async function updateExchangeRate( export async function deleteExchangeRate( exchangeRateId: number, companyId: number -): Promise { +): Promise> { const params = new URLSearchParams({ company_id: companyId.toString() }); return api.delete(`/v1/a76/exchange-rate/${exchangeRateId}?${params.toString()}`); } + +export interface DofResponse { + success: boolean; + message?: string; + value?: number | null; +} + +export async function getDofExchangeRate(date: string): Promise> { + return api.get(`/v1/a76/exchange-rate/dof-search?date=${date}`); +} diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/locations.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/locations.ts index e07612b3..c0994ade 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/locations.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/locations.ts @@ -50,7 +50,7 @@ export async function getLocation( companyId: number ): Promise { const params = new URLSearchParams({ company_id: companyId.toString() }); - return api.get(`/v1/a76/ports/${locationId}?${params.toString()}`); + return api.get(`/v1/a76/ports/${locationId}/?${params.toString()}`); } export async function createLocation( @@ -74,7 +74,7 @@ export async function updateLocation( ): Promise { const params = new URLSearchParams({ company_id: companyId.toString() }); return api.put( - `/v1/a76/ports/${locationId}?${params.toString()}`, + `/v1/a76/ports/${locationId}/?${params.toString()}`, { location_description: data.location_description } @@ -86,5 +86,5 @@ export async function deleteLocation( companyId: number ): Promise { const params = new URLSearchParams({ company_id: companyId.toString() }); - return api.delete(`/v1/a76/ports/${locationId}?${params.toString()}`); + return api.delete(`/v1/a76/ports/${locationId}/?${params.toString()}`); } \ No newline at end of file diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/packages.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/packages.ts index 13a9783a..57bdf74c 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/packages.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/packages.ts @@ -52,19 +52,19 @@ export async function getPackages( ...filters }); - return await api.get(`/v1/a76/packages?${params.toString()}`); + return await api.get(`/v1/a76/packages/?${params.toString()}`); } export async function getPackage(id: number, companyId: number): Promise> { - return await api.get(`/v1/a76/packages/${id}?company_id=${companyId}`); + return await api.get(`/v1/a76/packages/${id}/?company_id=${companyId}`); } export async function createPackage( data: PackageCreate, companyId: number ): Promise> { - return await api.post(`/v1/a76/packages?company_id=${companyId}`, data); + return await api.post(`/v1/a76/packages/?company_id=${companyId}`, data); } @@ -73,9 +73,9 @@ export async function updatePackage( data: PackageUpdate, companyId: number ): Promise> { - return await api.put(`/v1/a76/packages/${id}?company_id=${companyId}`, data); + return await api.put(`/v1/a76/packages/${id}/?company_id=${companyId}`, data); } export async function deletePackage(id: number, companyId: number): Promise> { - return await api.delete(`/v1/a76/packages/${id}?company_id=${companyId}`); + return await api.delete(`/v1/a76/packages/${id}/?company_id=${companyId}`); } \ No newline at end of file diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/ports.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/ports.ts index 0234bcf0..8ec0d7b9 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/ports.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/ports.ts @@ -58,17 +58,17 @@ export async function getPorts( queryParams.append('company_id', companyId.toString()); } - return await api.get(`/v1/a76/ports?${queryParams.toString()}`); + return await api.get(`/v1/a76/ports/?${queryParams.toString()}`); } export async function createPort(data: PortCreate, companyId: number): Promise> { - return await api.post(`/v1/a76/ports?company_id=${companyId}`, data); + return await api.post(`/v1/a76/ports/?company_id=${companyId}`, data); } export async function updatePort(id: number, data: PortUpdate, companyId: number): Promise> { - return await api.put(`/v1/a76/ports/${id}?company_id=${companyId}`, data); + return await api.put(`/v1/a76/ports/${id}/?company_id=${companyId}`, data); } export async function deletePort(id: number, companyId: number): Promise> { - return await api.delete(`/v1/a76/ports/${id}?company_id=${companyId}`); + return await api.delete(`/v1/a76/ports/${id}/?company_id=${companyId}`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/seal.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/seal.ts index e0d848d9..b0f3676f 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/seal.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/seal.ts @@ -44,7 +44,7 @@ export async function getSeals( if (filters?.page_size) params.append('page_size', filters.page_size.toString()); if (filters?.seal) params.append('seal', filters.seal); - const response = await api.get(`/v1/a76/seals?${params.toString()}`); + const response = await api.get(`/v1/a76/seals/?${params.toString()}`); return response; } @@ -56,7 +56,7 @@ export async function getSeal( id: number, companyId: number ): Promise<{ data: Seal; status: number }> { - const response = await api.get(`/v1/a76/seals/${id}?company_id=${companyId}`); + const response = await api.get(`/v1/a76/seals/${id}/?company_id=${companyId}`); return response; } @@ -67,7 +67,7 @@ export async function createSeal( data: SealCreateRequest, companyId: number ): Promise<{ data: Seal; status: number }> { - const response = await api.post(`/v1/a76/seals?company_id=${companyId}`, data); + const response = await api.post(`/v1/a76/seals/?company_id=${companyId}`, data); return response; } @@ -79,7 +79,7 @@ export async function updateSeal( data: SealUpdateRequest, companyId: number ): Promise<{ data: Seal; status: number }> { - const response = await api.put(`/v1/a76/seals/${id}?company_id=${companyId}`, data); + const response = await api.put(`/v1/a76/seals/${id}/?company_id=${companyId}`, data); return response; } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-ace.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-ace.ts index 779996ac..60fc2f42 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-ace.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-ace.ts @@ -43,33 +43,33 @@ export async function getUMACE( page_size: pageSize.toString(), ...filters }); - return await api.get(`/a76/units-of-measure/ace?${queryParams.toString()}`); + return await api.get(`/a76/units-of-measure/ace/?${queryParams.toString()}`); } /** * Obtiene una unidad de medida por ID */ export async function getUMACEById(id: number): Promise> { - return await api.get(`/a76/units-of-measure/ace/${id}`); + return await api.get(`/a76/units-of-measure/ace/${id}/`); } /** * Crea una nueva unidad de medida */ export async function createUMACE(data: UMACECreate): Promise> { - return await api.post('/a76/units-of-measure/ace', data); + return await api.post('/a76/units-of-measure/ace/', data); } /** * Actualiza una unidad de medida */ export async function updateUMACE(id: number, data: UMACEUpdate): Promise> { - return await api.put(`/a76/units-of-measure/ace/${id}`, data); + return await api.put(`/a76/units-of-measure/ace/${id}/`, data); } /** * Elimina una unidad de medida */ export async function deleteUMACE(id: number): Promise> { - return await api.delete(`/a76/units-of-measure/ace/${id}`); + return await api.delete(`/a76/units-of-measure/ace/${id}/`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-ame.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-ame.ts index cc1e2569..98efe7dd 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-ame.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-ame.ts @@ -43,33 +43,33 @@ export async function getUMCustomsAme( page_size: pageSize.toString(), ...filters }); - return await api.get(`/a76/units-of-measure/american?${queryParams.toString()}`); + return await api.get(`/a76/units-of-measure/american/?${queryParams.toString()}`); } /** * Obtiene una unidad de medida por ID */ export async function getUMCustomsAmeById(id: number): Promise> { - return await api.get(`/a76/units-of-measure/american/${id}`); + return await api.get(`/a76/units-of-measure/american/${id}/`); } /** * Crea una nueva unidad de medida */ export async function createUMCustomsAme(data: UMCustomsAmeCreate): Promise> { - return await api.post('/a76/units-of-measure/american', data); + return await api.post('/a76/units-of-measure/american/', data); } /** * Actualiza una unidad de medida */ export async function updateUMCustomsAme(id: number, data: UMCustomsAmeUpdate): Promise> { - return await api.put(`/a76/units-of-measure/american/${id}`, data); + return await api.put(`/a76/units-of-measure/american/${id}/`, data); } /** * Elimina una unidad de medida */ export async function deleteUMCustomsAme(id: number): Promise> { - return await api.delete(`/a76/units-of-measure/american/${id}`); + return await api.delete(`/a76/units-of-measure/american/${id}/`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-mex.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-mex.ts index 857a77f2..2eef1908 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-mex.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-customs-mex.ts @@ -43,33 +43,33 @@ export async function getUMCustomsMex( page_size: pageSize.toString(), ...filters }); - return await api.get(`/a76/units-of-measure/customs?${queryParams.toString()}`); + return await api.get(`/a76/units-of-measure/customs/?${queryParams.toString()}`); } /** * Obtiene una unidad de medida por ID */ export async function getUMCustomsMexById(id: number): Promise> { - return await api.get(`/a76/units-of-measure/customs/${id}`); + return await api.get(`/a76/units-of-measure/customs/${id}/`); } /** * Crea una nueva unidad de medida */ export async function createUMCustomsMex(data: UMCustomsMexCreate): Promise> { - return await api.post('/a76/units-of-measure/customs', data); + return await api.post('/a76/units-of-measure/customs/', data); } /** * Actualiza una unidad de medida */ export async function updateUMCustomsMex(id: number, data: UMCustomsMexUpdate): Promise> { - return await api.put(`/a76/units-of-measure/customs/${id}`, data); + return await api.put(`/a76/units-of-measure/customs/${id}/`, data); } /** * Elimina una unidad de medida */ export async function deleteUMCustomsMex(id: number): Promise> { - return await api.delete(`/a76/units-of-measure/customs/${id}`); + return await api.delete(`/a76/units-of-measure/customs/${id}/`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-oma.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-oma.ts index 40708461..eb58c53c 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/um-oma.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/um-oma.ts @@ -43,33 +43,33 @@ export async function getUMOMA( page_size: pageSize.toString(), ...filters }); - return await api.get(`/a76/units-of-measure/oma?${queryParams.toString()}`); + return await api.get(`/a76/units-of-measure/oma/?${queryParams.toString()}`); } /** * Obtiene una unidad de medida por ID */ export async function getUMOMAById(id: number): Promise> { - return await api.get(`/a76/units-of-measure/oma/${id}`); + return await api.get(`/a76/units-of-measure/oma/${id}/`); } /** * Crea una nueva unidad de medida */ export async function createUMOMA(data: UMOMACreate): Promise> { - return await api.post('/a76/units-of-measure/oma', data); + return await api.post('/a76/units-of-measure/oma/', data); } /** * Actualiza una unidad de medida */ export async function updateUMOMA(id: number, data: UMOMAUpdate): Promise> { - return await api.put(`/a76/units-of-measure/oma/${id}`, data); + return await api.put(`/a76/units-of-measure/oma/${id}/`, data); } /** * Elimina una unidad de medida */ export async function deleteUMOMA(id: number): Promise> { - return await api.delete(`/a76/units-of-measure/oma/${id}`); + return await api.delete(`/a76/units-of-measure/oma/${id}/`); } diff --git a/frontend/src/lib/api/dashboard/a76/general_catalogs/units-of-measure.ts b/frontend/src/lib/api/dashboard/a76/general_catalogs/units-of-measure.ts index f680bae3..eb8a2807 100644 --- a/frontend/src/lib/api/dashboard/a76/general_catalogs/units-of-measure.ts +++ b/frontend/src/lib/api/dashboard/a76/general_catalogs/units-of-measure.ts @@ -183,7 +183,7 @@ export interface UnitOfMeasureGeneralUpdate { } export interface UnitOfMeasureGeneralListResponse { - items: UnitOfMeasureGeneral[]; + items: UnitOfMeasureGeneral[]; total: number; page: number; page_size: number; @@ -214,7 +214,7 @@ export async function updateUnitOfMeasureGeneral(id: number, data: UnitOfMeasure } export async function deleteUnitOfMeasureGeneral(id: number, companyId: number): Promise> { - return await api.delete(`/v1/a76/units-of-measure/general/${id}/?company_id=${companyId}`); + return await api.delete(`/v1/a76/units-of-measure/general/${id}?company_id=${companyId}`); } // --- Customs --- @@ -295,7 +295,7 @@ export interface UnitOfMeasureListResponse { export async function getUnitsOfMeasure( page: number = 1, - pageSize: number = 50, + pageSize: number = 1000, companyId: number, filters: Record = {} ): Promise> { diff --git a/frontend/src/lib/api/dashboard/a76/items.ts b/frontend/src/lib/api/dashboard/a76/items.ts index 60cec7d3..353ddcfa 100644 --- a/frontend/src/lib/api/dashboard/a76/items.ts +++ b/frontend/src/lib/api/dashboard/a76/items.ts @@ -125,8 +125,8 @@ export interface LineItem { line_number: number; // Identification - part_number_id?: string; - component_part_number_id?: string; + part_number?: string; + component_part_number?: string; class_id?: number; identifier?: string; diff --git a/frontend/src/lib/api/dashboard/a76/pedimento-dates.ts b/frontend/src/lib/api/dashboard/a76/pedimento-dates.ts index 1cbe8ef4..6a716b0c 100644 --- a/frontend/src/lib/api/dashboard/a76/pedimento-dates.ts +++ b/frontend/src/lib/api/dashboard/a76/pedimento-dates.ts @@ -48,14 +48,14 @@ export interface UpdatePedimentoDatesData { export const pedimentoDatesApi = { get: (pedimentoId: number) => - api.get(`/v1/a76/pedimentos/${pedimentoId}/dates`), + api.get(`/v1/a76/pedimentos/${pedimentoId}/dates/`), create: (pedimentoId: number, data: CreatePedimentoDatesData) => - api.post(`/v1/a76/pedimentos/${pedimentoId}/dates`, data), + api.post(`/v1/a76/pedimentos/${pedimentoId}/dates/`, data), update: (pedimentoId: number, data: UpdatePedimentoDatesData) => - api.put(`/v1/a76/pedimentos/${pedimentoId}/dates`, data), + api.put(`/v1/a76/pedimentos/${pedimentoId}/dates/`, data), delete: (pedimentoId: number) => - api.delete(`/v1/a76/pedimentos/${pedimentoId}/dates`) + api.delete(`/v1/a76/pedimentos/${pedimentoId}/dates/`) }; diff --git a/frontend/src/lib/api/dashboard/a76/pedimento-payments.ts b/frontend/src/lib/api/dashboard/a76/pedimento-payments.ts index ac5bfa08..ac615167 100644 --- a/frontend/src/lib/api/dashboard/a76/pedimento-payments.ts +++ b/frontend/src/lib/api/dashboard/a76/pedimento-payments.ts @@ -51,14 +51,14 @@ export interface UpdatePedimentoPaymentsData { export const pedimentoPaymentsApi = { get: (pedimentoId: number) => - api.get(`/v1/a76/pedimentos/${pedimentoId}/payments`), + api.get(`/v1/a76/pedimentos/${pedimentoId}/payments/`), create: (pedimentoId: number, data: CreatePedimentoPaymentsData) => - api.post(`/v1/a76/pedimentos/${pedimentoId}/payments`, data), + api.post(`/v1/a76/pedimentos/${pedimentoId}/payments/`, data), update: (pedimentoId: number, data: UpdatePedimentoPaymentsData) => - api.put(`/v1/a76/pedimentos/${pedimentoId}/payments`, data), + api.put(`/v1/a76/pedimentos/${pedimentoId}/payments/`, data), delete: (pedimentoId: number) => - api.delete(`/v1/a76/pedimentos/${pedimentoId}/payments`) + api.delete(`/v1/a76/pedimentos/${pedimentoId}/payments/`) }; diff --git a/frontend/src/lib/api/dashboard/a76/pedimento-transport.ts b/frontend/src/lib/api/dashboard/a76/pedimento-transport.ts index b5f7d424..e91054a2 100644 --- a/frontend/src/lib/api/dashboard/a76/pedimento-transport.ts +++ b/frontend/src/lib/api/dashboard/a76/pedimento-transport.ts @@ -30,14 +30,14 @@ export interface UpdatePedimentoTransportMeansData { export const pedimentoTransportApi = { get: (pedimentoId: number) => - api.get(`/v1/a76/pedimentos/${pedimentoId}/transport-means`), + api.get(`/v1/a76/pedimentos/${pedimentoId}/transport-means/`), create: (pedimentoId: number, data: CreatePedimentoTransportMeansData) => - api.post(`/v1/a76/pedimentos/${pedimentoId}/transport-means`, data), + api.post(`/v1/a76/pedimentos/${pedimentoId}/transport-means/`, data), update: (pedimentoId: number, data: UpdatePedimentoTransportMeansData) => - api.put(`/v1/a76/pedimentos/${pedimentoId}/transport-means`, data), + api.put(`/v1/a76/pedimentos/${pedimentoId}/transport-means/`, data), delete: (pedimentoId: number) => - api.delete(`/v1/a76/pedimentos/${pedimentoId}/transport-means`) + api.delete(`/v1/a76/pedimentos/${pedimentoId}/transport-means/`) }; diff --git a/frontend/src/lib/api/dashboard/a76/pedimento-validation.ts b/frontend/src/lib/api/dashboard/a76/pedimento-validation.ts index 8d78de9c..077d13df 100644 --- a/frontend/src/lib/api/dashboard/a76/pedimento-validation.ts +++ b/frontend/src/lib/api/dashboard/a76/pedimento-validation.ts @@ -42,14 +42,14 @@ export interface UpdatePedimentoValidationData { export const pedimentoValidationApi = { get: (pedimentoId: number) => - api.get(`/v1/a76/pedimentos/${pedimentoId}/validation`), + api.get(`/v1/a76/pedimentos/${pedimentoId}/validation/`), create: (pedimentoId: number, data: CreatePedimentoValidationData) => - api.post(`/v1/a76/pedimentos/${pedimentoId}/validation`, data), + api.post(`/v1/a76/pedimentos/${pedimentoId}/validation/`, data), update: (pedimentoId: number, data: UpdatePedimentoValidationData) => - api.put(`/v1/a76/pedimentos/${pedimentoId}/validation`, data), + api.put(`/v1/a76/pedimentos/${pedimentoId}/validation/`, data), delete: (pedimentoId: number) => - api.delete(`/v1/a76/pedimentos/${pedimentoId}/validation`) + api.delete(`/v1/a76/pedimentos/${pedimentoId}/validation/`) }; diff --git a/frontend/src/lib/api/dashboard/a76/reports/reports-aviso-consolidado.ts b/frontend/src/lib/api/dashboard/a76/reports/reports-aviso-consolidado.ts new file mode 100644 index 00000000..363b1daf --- /dev/null +++ b/frontend/src/lib/api/dashboard/a76/reports/reports-aviso-consolidado.ts @@ -0,0 +1,35 @@ + +const BASE_URL = import.meta.env.VITE_API_URL || ''; + +export const avisoConsolidadoReportsApi = { + + triggerPdfGeneration: async (invoiceId: number, companyId: number) => { + const params = new URLSearchParams({ company_id: companyId.toString() }); + const endpoint = `${BASE_URL}/v1/a76/reports/exportacion/aviso_consolidado/${invoiceId}/download-async?${params.toString()}`; + + const token = localStorage.getItem('access_token'); + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json' + } + }); + + if (!response.ok) throw new Error('Error al iniciar la generación del Aviso Consolidado'); + return await response.json(); + }, + + getTaskStatus: async (taskId: string) => { + const endpoint = `${BASE_URL}/v1/a76/reports/exportacion/aviso_consolidado/tasks/${taskId}`; + + const token = localStorage.getItem('access_token'); + const response = await fetch(endpoint, { + method: 'GET', + headers: { 'Authorization': `Bearer ${token}` } + }); + + if (!response.ok) throw new Error('Error al consultar estado del Aviso Consolidado'); + return await response.json(); + } +}; diff --git a/frontend/src/lib/api/dashboard/a76/reports/reports-invoices.ts b/frontend/src/lib/api/dashboard/a76/reports/reports-invoices.ts index 33c619f7..7041c3a6 100644 --- a/frontend/src/lib/api/dashboard/a76/reports/reports-invoices.ts +++ b/frontend/src/lib/api/dashboard/a76/reports/reports-invoices.ts @@ -1,15 +1,22 @@ -const BASE_URL = import.meta.env.VITE_API_URL || ''; +const BASE_URL = import.meta.env.VITE_API_URL || ''; +const BASE_URL = import.meta.env.VITE_API_URL || ''; export const invoicesReportsApi = { - - triggerPdfGeneration: async (invoiceId: number, companyId: number) => { - const params = new URLSearchParams({ company_id: companyId.toString() }); + + triggerPdfGeneration: async (invoiceId: number, companyId: number, invoiceType: string = 'mexican', currency: string = 'ORIGINAL') => { + const params = new URLSearchParams({ + company_id: companyId.toString(), + invoice_type: invoiceType, + currency_code: currency + }); const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/${invoiceId}/download-async?${params.toString()}`; - + + const token = localStorage.getItem('access_token'); const response = await fetch(endpoint, { - method: 'POST', + method: 'POST', + method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' @@ -17,12 +24,15 @@ export const invoicesReportsApi = { }); if (!response.ok) throw new Error('Error al iniciar la generación'); - return await response.json(); + return await response.json(); + return await response.json(); }, getTaskStatus: async (taskId: string) => { - const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/tasks/${taskId}`; - + const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/tasks/${taskId}`; + + const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/tasks/${taskId}`; + const token = localStorage.getItem('access_token'); const response = await fetch(endpoint, { method: 'GET', @@ -31,5 +41,35 @@ export const invoicesReportsApi = { if (!response.ok) throw new Error('Error al consultar estado'); return await response.json(); + }, + + triggerPackingListGeneration: async (invoiceId: number, companyId: number) => { + const params = new URLSearchParams({ company_id: companyId.toString() }); + const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/${invoiceId}/download-async?${params.toString()}`; + + const token = localStorage.getItem('access_token'); + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json' + } + }); + + if (!response.ok) throw new Error('Error al iniciar la generación de Packing List'); + return await response.json(); + }, + + getPackingListTaskStatus: async (taskId: string) => { + const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/tasks/${taskId}`; + + const token = localStorage.getItem('access_token'); + const response = await fetch(endpoint, { + method: 'GET', + headers: { 'Authorization': `Bearer ${token}` } + }); + + if (!response.ok) throw new Error('Error al consultar estado de Packing List'); + return await response.json(); } }; \ No newline at end of file diff --git a/frontend/src/lib/api/dashboard/admin/permissions.ts b/frontend/src/lib/api/dashboard/admin/permissions.ts index db085c94..e6d2ef06 100644 --- a/frontend/src/lib/api/dashboard/admin/permissions.ts +++ b/frontend/src/lib/api/dashboard/admin/permissions.ts @@ -57,7 +57,7 @@ export const permissionsAPI = { if (params?.action) queryParams.set('action', params.action); if (params?.search) queryParams.set('search', params.search); const query = queryParams.toString(); - const response = await api.get(`/v1/core/permissions${query ? '?' + query : ''}`); + const response = await api.get(`/v1/core/permissions/${query ? '?' + query : ''}`); return response.data; }, @@ -65,7 +65,7 @@ export const permissionsAPI = { * Obtener un permiso por ID */ async getById(id: number): Promise { - const response = await api.get(`/v1/core/permissions/${id}`); + const response = await api.get(`/v1/core/permissions/${id}/`); return response.data; }, @@ -73,7 +73,7 @@ export const permissionsAPI = { * Crear un nuevo permiso */ async create(data: CreatePermissionData): Promise { - const response = await api.post('/v1/core/permissions', data); + const response = await api.post('/v1/core/permissions/', data); return response.data; }, @@ -81,7 +81,7 @@ export const permissionsAPI = { * Actualizar un permiso */ async update(id: number, data: UpdatePermissionData): Promise { - const response = await api.put(`/v1/core/permissions/${id}`, data); + const response = await api.put(`/v1/core/permissions/${id}/`, data); return response.data; }, @@ -89,14 +89,14 @@ export const permissionsAPI = { * Eliminar un permiso */ async delete(id: number): Promise { - await api.delete(`/v1/core/permissions/${id}`); + await api.delete(`/v1/core/permissions/${id}/`); }, /** * Obtener módulos únicos */ async getModules(): Promise { - const response = await api.get('/v1/core/permissions/modules'); + const response = await api.get('/v1/core/permissions/modules/'); return response.data; }, @@ -104,7 +104,7 @@ export const permissionsAPI = { * Obtener acciones únicas */ async getActions(): Promise { - const response = await api.get('/v1/core/permissions/actions'); + const response = await api.get('/v1/core/permissions/actions/'); return response.data; } }; diff --git a/frontend/src/lib/api/dashboard/refrence_data/countries.ts b/frontend/src/lib/api/dashboard/refrence_data/countries.ts index f17eab64..09ed1927 100644 --- a/frontend/src/lib/api/dashboard/refrence_data/countries.ts +++ b/frontend/src/lib/api/dashboard/refrence_data/countries.ts @@ -5,34 +5,34 @@ import { api } from '$lib/api'; export interface Country { - m3_key: string; - mex_key: string; - ame_key: string; - description_es: string; - description_en: string; + m3_key: string; + mex_key: string; + ame_key: string; + description_es: string; + description_en: string; } export interface CountryListResponse { - items: Country[]; - total: number; - page: number; - page_size: number; + items: Country[]; + total: number; + page: number; + page_size: number; } export interface CreateCountryData { - m3_key: string; - mex_key: string; - ame_key: string; - description_es: string; - description_en: string; + m3_key: string; + mex_key: string; + ame_key: string; + description_es: string; + description_en: string; } export interface UpdateCountryData { - m3_key?: string; - mex_key?: string; - ame_key?: string; - description_es?: string; - description_en?: string; + m3_key?: string; + mex_key?: string; + ame_key?: string; + description_es?: string; + description_en?: string; } /** @@ -43,18 +43,21 @@ export const countriesApi = { * Lista todos los países con paginación * @param page - Número de página (por defecto 1) * @param pageSize - Tamaño de página (por defecto 50) + * @param search - Término de búsqueda (opcional) */ - list: (page = 1, pageSize = 50) => - api.get( - // CORREGIDO: Añadido '/' antes del '?' - `/v1/public/refrence_data/countries/?page=${page}&page_size=${pageSize}` - ), + list: (page = 1, pageSize = 50, search?: string) => { + let url = `/v1/public/refrence_data/countries/?page=${page}&page_size=${pageSize}`; + if (search) { + url += `&search=${encodeURIComponent(search)}`; + } + return api.get(url); + }, /** * Obtiene un país por su clave M3 * @param m3_key - Clave M3 del país */ - get: (m3_key: string) => + get: (m3_key: string) => // CORREGIDO: Añadido '/' al final api.get(`/v1/public/refrence_data/countries/${m3_key}/`), @@ -79,7 +82,7 @@ export const countriesApi = { * Elimina un país * @param m3_key - Clave M3 del país a eliminar */ - delete: (m3_key: string) => + delete: (m3_key: string) => // CORREGIDO: Añadido '/' después de la clave api.delete(`/v1/public/refrence_data/countries/${m3_key}/`) }; \ No newline at end of file diff --git a/frontend/src/lib/components/dashboard/exchange_rate/create-edit-dialog.svelte b/frontend/src/lib/components/dashboard/exchange_rate/create-edit-dialog.svelte index 34c61657..f85eec38 100644 --- a/frontend/src/lib/components/dashboard/exchange_rate/create-edit-dialog.svelte +++ b/frontend/src/lib/components/dashboard/exchange_rate/create-edit-dialog.svelte @@ -1,27 +1,41 @@ + + diff --git a/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/general/data-table-actions.svelte b/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/general/data-table-actions.svelte index a84164f4..96ce74e0 100644 --- a/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/general/data-table-actions.svelte +++ b/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/general/data-table-actions.svelte @@ -2,6 +2,7 @@ import { Button } from '$lib/components/ui/button'; import * as DropdownMenu from '$lib/components/ui/dropdown-menu'; import { MoreHorizontal, Pencil, Trash2 } from 'lucide-svelte'; + import { toast } from 'svelte-sonner'; import CreateEditDialog from './create-edit-dialog.svelte'; import type { UnitOfMeasureGeneral } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure'; import { deleteUnitOfMeasureGeneral } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure'; @@ -25,6 +26,7 @@ const response = await deleteUnitOfMeasureGeneral(unit.id, activeCompanyId); if (response.error) { + toast.error(response.error); } else if (response.status === 204 || response.status === 200) { onSuccess?.(); } diff --git a/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/main/data-table.svelte b/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/main/data-table.svelte new file mode 100644 index 00000000..77c412d8 --- /dev/null +++ b/frontend/src/lib/components/dashboard/general_catalogs/units_of_measure/main/data-table.svelte @@ -0,0 +1,107 @@ + + +
+ + + {#each table.getHeaderGroups() as headerGroup (headerGroup.id)} + + {#each headerGroup.headers as header (header.id)} + + {#if !header.isPlaceholder} + + {/if} + + {/each} + + {/each} + + + {#each table.getRowModel().rows as row (row.id)} + + {#each row.getVisibleCells() as cell (cell.id)} + + + + {/each} + + {:else} + + + No hay resultados. + + + {/each} + + +
+ + +
+
+ Total: {totalItems} registros +
+
+ + +
+
diff --git a/frontend/src/lib/components/dashboard/goods/modales/country-selector-dialog.svelte b/frontend/src/lib/components/dashboard/goods/modales/country-selector-dialog.svelte index 27943e6b..e6d1f81d 100644 --- a/frontend/src/lib/components/dashboard/goods/modales/country-selector-dialog.svelte +++ b/frontend/src/lib/components/dashboard/goods/modales/country-selector-dialog.svelte @@ -19,80 +19,109 @@ // --- ESTADO --- let items = $state([]); let loading = $state(false); + let loadingMore = $state(false); let searchTerm = $state(""); - let loaded = $state(false); + let previousSearchTerm = ""; + let page = $state(1); + let pageSize = 50; + let hasMore = $state(true); + let totalItems = $state(0); + let observer: IntersectionObserver | null = null; + let bottomSentinel: HTMLElement | null = $state(null); + let searchTimeout: any; + let isInitialized = false; - // Filtro local - let filteredItems = $derived( - items.filter(i => - (i.m3_key || "").toLowerCase().includes(searchTerm.toLowerCase()) || - (i.mex_key || "").toLowerCase().includes(searchTerm.toLowerCase()) || - (i.description_es || "").toLowerCase().includes(searchTerm.toLowerCase()) || - (i.description_en || "").toLowerCase().includes(searchTerm.toLowerCase()) - ) - ); - - // Cargar datos al abrir + // Cargar datos iniciales al abrir $effect(() => { - console.log("CountrySelectorDialog: open changed", open); - if (open) { - loadCountries(); + if (open && !isInitialized) { + isInitialized = true; + previousSearchTerm = searchTerm; + resetAndLoad(); + } else if (!open) { + isInitialized = false; } }); - async function loadCountries() { - loading = true; - console.log("CountrySelectorDialog: loading countries..."); - try { - // FIX: Reducir tamaño de página para evitar timeouts y manejo de errores - const response = await countriesApi.list(1, 100); - console.log("Respuesta países FULL:", response); + // Manejar búsqueda con debouncing - solo cuando cambia el término + $effect(() => { + const term = searchTerm; + + // Solo resetear si el término cambió y ya estamos inicializados + if (isInitialized && term !== previousSearchTerm) { + if (searchTimeout) clearTimeout(searchTimeout); + searchTimeout = setTimeout(() => { + previousSearchTerm = term; + resetAndLoad(); + }, 500); + } + }); + // Configurar IntersectionObserver para infinite scroll + $effect(() => { + if (bottomSentinel && hasMore && !loading && !loadingMore && open) { + if (observer) observer.disconnect(); + + observer = new IntersectionObserver((entries) => { + if (entries[0].isIntersecting && hasMore && !loading && !loadingMore) { + loadMore(); + } + }, { threshold: 0.1 }); + + observer.observe(bottomSentinel); + } + + return () => { + if (observer) observer.disconnect(); + }; + }); + + async function resetAndLoad() { + page = 1; + items = []; + hasMore = true; + await loadCountries(true); + } + + async function loadMore() { + if (!hasMore || loading || loadingMore) return; + page += 1; + await loadCountries(false); + } + + async function loadCountries(isInitial: boolean) { + if (isInitial) { + loading = true; + } else { + loadingMore = true; + } + + try { + const response = await countriesApi.list(page, pageSize, searchTerm); + if (response.error) { - console.error("Error API:", response.error); - toast.error(`Error al cargar países: ${response.error}`); + toast.error(`Error: ${response.error}`); + hasMore = false; return; } + + const newItems = response.data?.items || []; + totalItems = response.data?.total || 0; - // Caso 1: Estructura esperada { data: { items: [...] } } - if (response.data?.items && Array.isArray(response.data.items)) { - items = response.data.items; - loaded = true; - } - // Caso 2: El backend devuelve el array directamente en data { data: [...] } - else if (Array.isArray(response.data)) { - items = response.data; - loaded = true; + if (isInitial) { + items = newItems; + } else { + items = [...items, ...newItems]; } - // Caso 3: La respuesta en sí es el array (poco probable con el wrapper actual pero posible si algo falla antes) - else if (Array.isArray(response)) { - items = response; - loaded = true; - } - // Caso 4: data es el objeto paginado pero sin la propiedad items correcta o vacía - else if (response.data && typeof response.data === 'object') { - // Intentar buscar alguna propiedad que sea array - const possibleArray = Object.values(response.data).find(val => Array.isArray(val)); - if (possibleArray) { - items = possibleArray as Country[]; - loaded = true; - } else { - console.warn("Estructura de datos no reconocida en countriesApi.list:", response.data); - toast.error("Formato de datos de países no reconocido"); - } - } - else { - console.warn("No se encontraron países o formato incorrecto:", response); - toast.error("No se encontraron países"); - } - - console.log(`Países cargados: ${items.length}`); + + hasMore = items.length < totalItems && newItems.length > 0; } catch (e: any) { - console.error("Error cargando países (excepción):", e); - toast.error(`Excepción al cargar países: ${e.message || e}`); + console.error("Error loading countries:", e); + toast.error("Error al conectar con el servidor"); + hasMore = false; } finally { loading = false; + loadingMore = false; } } @@ -103,11 +132,11 @@ - + Seleccionar País - Seleccione el país de origen del catálogo. + Seleccione el país de origen del catálogo. Escrolea para ver más. @@ -122,12 +151,12 @@
- {#if loading} + {#if loading && items.length === 0}

Cargando catálogo...

- {:else if filteredItems.length === 0} + {:else if items.length === 0}

No se encontraron países.

@@ -143,7 +172,7 @@ - {#each filteredItems as item} + {#each items as item} handleSelect(item)} @@ -172,12 +201,19 @@ {/each} + + +
+ {#if loadingMore} + + {/if} +
{/if}
- {filteredItems.length} registros encontrados + {items.length} de {totalItems} registros
diff --git a/frontend/src/lib/components/dashboard/goods/modales/unit-measure-dialog.svelte b/frontend/src/lib/components/dashboard/goods/modales/unit-measure-dialog.svelte index 2520f8b6..43f7e76b 100644 --- a/frontend/src/lib/components/dashboard/goods/modales/unit-measure-dialog.svelte +++ b/frontend/src/lib/components/dashboard/goods/modales/unit-measure-dialog.svelte @@ -16,15 +16,27 @@ } = $props(); let items = $state([]); + let allItems = $state([]); // Store full dataset let loading = $state(false); let searchTerm = $state(""); - let page = $state(1); - let totalPages = $state(1); - let searchTimeout: NodeJS.Timeout; + + // Derived state for filtering + $effect(() => { + if (!searchTerm) { + items = allItems; + } else { + const lowerTerm = searchTerm.toLowerCase(); + items = allItems.filter(item => + item.code.toLowerCase().includes(lowerTerm) || + (item.description && item.description.toLowerCase().includes(lowerTerm)) || + (item.description_en && item.description_en.toLowerCase().includes(lowerTerm)) + ); + } + }); // Cargar datos al abrir $effect(() => { - if (open && companyStore.activeCompany) { + if (open && companyStore.activeCompany && allItems.length === 0) { loadData(); } }); @@ -34,17 +46,12 @@ loading = true; try { - const filters = searchTerm ? { code: searchTerm } : {}; - // Nota: Si tu backend soporta búsqueda por descripción, úsalo aquí. - // Por ahora asumo búsqueda por 'code' o 'description' según tu filtro backend. - - const response = await getUnitsOfMeasure(page, 10, companyStore.activeCompany.id, { - q: searchTerm // Asumiendo que tu backend tiene un filtro genérico 'q' o usa 'code'/'description' - }); + // Fetch everything once using the high limit + const response = await getUnitsOfMeasure(1, 1000, companyStore.activeCompany.id, {}); if (response.data) { - items = response.data.items; - totalPages = response.data.pages; + allItems = response.data.items; + items = allItems; // Initialize view } } catch (error) { console.error("Error cargando unidades:", error); @@ -56,32 +63,13 @@ function handleSearch(e: Event) { const value = (e.target as HTMLInputElement).value; searchTerm = value; - page = 1; - - clearTimeout(searchTimeout); - searchTimeout = setTimeout(() => { - loadData(); - }, 500); + // No network call needed, $effect handles filtering } function handleSelect(item: UnitOfMeasure) { onSelect(item); open = false; } - - function nextPage() { - if (page < totalPages) { - page++; - loadData(); - } - } - - function prevPage() { - if (page > 1) { - page--; - loadData(); - } - } @@ -104,7 +92,7 @@ /> -
+
{#if loading}
@@ -146,27 +134,9 @@
- -
- Página {page} de {totalPages} -
- - -
+ +
+ Mostrando {items.length} registros
diff --git a/frontend/src/lib/components/dashboard/goods/parts/partForm.svelte b/frontend/src/lib/components/dashboard/goods/parts/partForm.svelte index 5991f15e..2555cf86 100644 --- a/frontend/src/lib/components/dashboard/goods/parts/partForm.svelte +++ b/frontend/src/lib/components/dashboard/goods/parts/partForm.svelte @@ -76,7 +76,7 @@ description_english: '', part_class: '', material_type: '', - unit_of_measure: 'PZ', + unit_of_measure: '', unit_weight: 0, weight_type: 'KG', unit_cost: 0, @@ -124,7 +124,7 @@ part_class: d.part_class || '', material_type: d.inv_data?.material_type || '', origin_country: d.fa_data?.origin_country || 'MEX', - unit_of_measure: d.unit_of_measure || 'PZ', + unit_of_measure: d.unit_of_measure || '', fraction: d.fraction || '', us_fraction: d.us_fraction || '', unit_weight: Number(d.unit_weight) || 0, @@ -232,7 +232,7 @@ const activeCompanyId = companyStore.activeCompany?.id; if (!activeCompanyId) { error = 'No hay una compañía activa seleccionada'; return; } if (!formData.client_id) { error = 'Debe seleccionar un Cliente'; return; } - if (!formData.part_number.trim()) { error = 'Número de Parte requerido'; return; } + if (!formData.unit_of_measure) { error = 'Debe seleccionar una Unidad de Medida'; return; } loading = true; try { @@ -272,7 +272,7 @@ } catch (e: any) { console.error("Submit Error:", e); error = e.message || 'Error al guardar'; - toast.error(error); + toast.error(error!); } finally { loading = false; } } @@ -299,7 +299,7 @@ {#if error}
- ⚠️ {error} + ⚠️ {error!}
{/if} @@ -360,7 +360,7 @@
- showUOMModal = true} class="pl-9 cursor-pointer font-mono" placeholder="PZ"/> + showUOMModal = true} class="pl-9 cursor-pointer font-mono" placeholder="Seleccione..."/>
@@ -540,7 +540,7 @@
- +
diff --git a/frontend/src/lib/components/dashboard/invoices/create-edit-dialog.svelte b/frontend/src/lib/components/dashboard/invoices/create-edit-dialog.svelte index 4e0eef19..c7037523 100644 --- a/frontend/src/lib/components/dashboard/invoices/create-edit-dialog.svelte +++ b/frontend/src/lib/components/dashboard/invoices/create-edit-dialog.svelte @@ -5,9 +5,11 @@ import { Label } from "$lib/components/ui/label"; import * as Select from "$lib/components/ui/select"; import { invoicesApi, type Invoice, type CreateInvoiceData, type UpdateInvoiceData } from "$lib/api/dashboard/a76/invoices"; + import { getExchangeRates } from "$lib/api/dashboard/a76/general_catalogs/exchange-rate"; import { companyStore } from "$lib/stores/company.svelte"; import { LoaderCircle } from 'lucide-svelte'; import * as Tabs from "$lib/components/ui/tabs"; + import ExchangeRateDialog from "$lib/components/dashboard/exchange_rate/create-edit-dialog.svelte"; let { open = $bindable(false), @@ -72,6 +74,9 @@ let loading = $state(false); let error = $state(null); + let showExchangeRateDialog = $state(false); + let missingExchangeRateDate = $state(""); + // Actualizar formData cuando item cambia $effect(() => { if (item) { @@ -181,6 +186,15 @@ error = null; try { + // Verificar tipo de cambio antes de guardar + if (formData.invoice_date) { + const rateExists = await checkExchangeRate(formData.invoice_date); + if (!rateExists) { + loading = false; + return; + } + } + let response; if (isEditing && item) { const payload: UpdateInvoiceData = { @@ -287,11 +301,37 @@ window.location.reload(); }, 1500); } else { + // Convertir el error a string para buscar mensajes específicos (maneja objetos/arrays de DRF) + const errorStr = typeof response.error === 'string' + ? response.error + : JSON.stringify(response.error); + + if (errorStr.includes('No existe un Tipo de Cambio registrado') || errorStr.includes('financials.exchange_rate')) { + // Interceptar error de tipo de cambio + console.log("Interceptor: Exchange rate missing error caught (Invoice)."); + error = null; + + const dateMatch = errorStr.match(/(\d{4}-\d{2}-\d{2})/); + missingExchangeRateDate = dateMatch ? dateMatch[0] : (formData.invoice_date || ""); + + showExchangeRateDialog = true; + return; + } + error = response.error; } return; } + // Check exchange rate BEFORE calling API to avoid 400 error + if (formData.invoice_date) { + const rateExists = await checkExchangeRate(formData.invoice_date); + if (!rateExists) { + loading = false; + return; + } + } + // Éxito open = false; if (onSuccess) { @@ -305,6 +345,33 @@ } } + async function checkExchangeRate(date: string): Promise { + if (!date || !companyStore.activeCompany?.id) return true; + + try { + const response = await getExchangeRates(companyStore.activeCompany.id, { + date: date, + page_size: 1 + }); + + // api.get returns { data: ..., status: ... } and types now reflect that + const items = response.data?.items || []; + + // Verificar estrictamente que haya items + if (items.length === 0) { + missingExchangeRateDate = date; + showExchangeRateDialog = true; + return false; + } + return true; + } catch (error) { + console.error('Error checking exchange rate:', error); + missingExchangeRateDate = date; + showExchangeRateDialog = true; + return false; + } + } + function handleOpenChange(newOpen: boolean) { if (!newOpen) { resetForm(); @@ -679,3 +746,10 @@ + + {/* Optional: maybe refresh something or just let user continue */}} +/> diff --git a/frontend/src/lib/components/dashboard/invoices/download-invoice-button.svelte b/frontend/src/lib/components/dashboard/invoices/download-invoice-button.svelte index a04b550b..e70c4149 100644 --- a/frontend/src/lib/components/dashboard/invoices/download-invoice-button.svelte +++ b/frontend/src/lib/components/dashboard/invoices/download-invoice-button.svelte @@ -1,90 +1,23 @@ + + console.log('Download not implemented in this context')} +/> diff --git a/frontend/src/lib/components/dashboard/invoices/edit/general-tab-form.svelte b/frontend/src/lib/components/dashboard/invoices/edit/general-tab-form.svelte index c7875be8..f9c18642 100644 --- a/frontend/src/lib/components/dashboard/invoices/edit/general-tab-form.svelte +++ b/frontend/src/lib/components/dashboard/invoices/edit/general-tab-form.svelte @@ -8,6 +8,12 @@ import type { CustomsBroker } from '$lib/api/dashboard/a76/customs-brokers'; import type { ClientProvider } from '$lib/api/dashboard/a76/clients-providers'; + interface CodePedimentoRegimen { + regimen_code: string; + type_code: string; + [key: string]: any; + } + let { invoice, formData = $bindable(), @@ -22,6 +28,7 @@ customsSections = [], codePedimentoRegimens = [], operationType = undefined, + defaultOperationType = undefined, exchangeRate = undefined }: { invoice: Invoice | null; @@ -37,8 +44,8 @@ drivers?: any[]; trailers?: any[]; customsSections?: any[]; - codePedimentoRegimens?: any[]; - defaultOperationType?: string | null; + codePedimentoRegimens?: CodePedimentoRegimen[]; + defaultOperationType?: string | number | null; defaultInvoiceType?: string | null; operationType?: number | null; exchangeRate?: number | null; @@ -176,25 +183,55 @@ ] ); - // Combinar clientes y proveedores para shipped_to - const allClientsProviders = [...clients, ...providers]; - - // Filtrar regímenes por tipo de operación (1='E' exp, 2='I' imp) y obtener valores únicos - const filteredRegimens = $derived.by(() => { - const typeCode = operationType === 1 ? 'E' : operationType === 2 ? 'I' : null; - const filtered = codePedimentoRegimens.filter(r => r.type_code === typeCode); - - // Obtener solo regímenes únicos por regimen_code + // Combinar clientes y proveedores para shipped_to, evitando duplicados de tipo "both" + const allClientsProviders = $derived.by(() => { const uniqueMap = new Map(); - filtered.forEach(r => { - if (r.regimen_code && !uniqueMap.has(r.regimen_code)) { - uniqueMap.set(r.regimen_code, r); + + // Agregar todos los clientes + clients.forEach(c => { + uniqueMap.set(c.id, { ...c, type: c.client_or_provider }); + }); + + // Agregar proveedores solo si no existen (evita duplicados de "both") + providers.forEach(p => { + if (!uniqueMap.has(p.id)) { + uniqueMap.set(p.id, { ...p, type: p.client_or_provider }); } }); return Array.from(uniqueMap.values()); }); + // Determinar tipo de código basado en operationType prop, defaultOperationType o invoice.operation_type + const typeCode = $derived( + operationType === 1 ? 'E' + : operationType === 2 ? 'I' + : defaultOperationType === 1 ? 'E' + : defaultOperationType === 2 ? 'I' + : defaultOperationType === 'exp' ? 'E' + : defaultOperationType === 'imp' ? 'I' + : invoice?.operation_type === 'exp' ? 'E' + : invoice?.operation_type === 'imp' ? 'I' + : null + ); + + // Filtrar regímenes por tipo de operación (1='E' exp, 2='I' imp) y obtener valores únicos + const filteredRegimens = $derived( + !codePedimentoRegimens || codePedimentoRegimens.length === 0 || !typeCode + ? [] + : Array.from( + codePedimentoRegimens + .filter(r => r.type_code === typeCode) + .reduce((map, r) => { + if (r.regimen_code && !map.has(r.regimen_code)) { + map.set(r.regimen_code, r); + } + return map; + }, new Map()) + .values() + ) + ); + // Efecto: Limpiar régimen si no existe en los regímenes filtrados al cambiar operation_type $effect(() => { if (formData.document_type && filteredRegimens.length > 0) { @@ -263,9 +300,11 @@ > - {formData.provider_id - ? providers.find(p => p.id === formData.provider_id)?.name || 'Selecciona...' - : 'Selecciona...'} + {#if formData.provider_id} + {providers.find(p => p.id === formData.provider_id)?.name || 'Selecciona...'} + {:else} + Selecciona... + {/if} @@ -309,9 +348,11 @@ > - {formData.sold_to_id - ? clients.find(c => c.id === formData.sold_to_id)?.name || 'Selecciona...' - : 'Selecciona...'} + {#if formData.sold_to_id} + {clients.find(c => c.id === formData.sold_to_id)?.name || 'Selecciona...'} + {:else} + Selecciona... + {/if} @@ -355,15 +396,17 @@ > - {formData.shipped_to_id - ? allClientsProviders.find(cp => cp.id === formData.shipped_to_id)?.name || 'Selecciona...' - : 'Selecciona...'} + {#if formData.shipped_to_id} + {allClientsProviders.find(cp => cp.id === formData.shipped_to_id)?.name || 'Selecciona...'} + {:else} + Selecciona... + {/if} {#each allClientsProviders as cp} - {cp.name} ({cp.type === 'client' ? 'C' : 'P'}) + {cp.name} {/each} diff --git a/frontend/src/lib/components/dashboard/invoices/edit/invoice-top-fields.svelte b/frontend/src/lib/components/dashboard/invoices/edit/invoice-top-fields.svelte index 47743eef..e3549f05 100644 --- a/frontend/src/lib/components/dashboard/invoices/edit/invoice-top-fields.svelte +++ b/frontend/src/lib/components/dashboard/invoices/edit/invoice-top-fields.svelte @@ -46,6 +46,16 @@ } }); + // Efecto para actualizar operation_type cuando cambia defaultOperationType + $effect(() => { + if (formData && defaultOperationType !== undefined && defaultOperationType !== null) { + // Si operation_type está vacío, null, o undefined, actualizarlo con defaultOperationType + if (!formData.operation_type) { + formData.operation_type = defaultOperationType; + } + } + }); + if (!formData) { let operationType: string | null = null; if (invoice?.operation_type) { @@ -69,6 +79,11 @@ clave_pedimento: '', regimen_pedimento: '', }; + } else { + // Si formData ya existe pero operation_type está vacío, usar defaultOperationType + if (!formData.operation_type && defaultOperationType !== undefined && defaultOperationType !== null) { + formData.operation_type = defaultOperationType; + } } diff --git a/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-configuration.svelte b/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-configuration.svelte index 34333daa..e71c6096 100644 --- a/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-configuration.svelte +++ b/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-configuration.svelte @@ -2,6 +2,9 @@ import * as RadioGroup from '$lib/components/ui/radio-group'; import { Input } from '$lib/components/ui/input'; import { Label } from '$lib/components/ui/label'; + import { Button } from '$lib/components/ui/button'; + import { Folder } from 'lucide-svelte'; + import PartNumberDialog from './part-number-dialog.svelte'; import type { LineItem, LineDescriptions } from '$lib/api/dashboard/a76/items'; let { @@ -12,6 +15,8 @@ descriptions: LineDescriptions; } = $props(); + let showPartDialog = $state(false); + // Initialize fa_data for fixed asset system if (!lineItem.fa_data) { lineItem.fa_data = {}; @@ -29,8 +34,18 @@ if (!lineItem.fa_data) lineItem.fa_data = {}; lineItem.fa_data.contains_subitems = val === 'si'; } + + function handlePartSelect(part: any) { + lineItem.part_number_id = part.id; + // Store part number for display + (lineItem as any).part_number = part.part_number; + (lineItem as any).part_description_es = part.description_spanish; + (lineItem as any).part_description_en = part.description_english; + } + +
@@ -72,11 +87,32 @@
- +
- + (showPartDialog = true)} + /> +
-

ID de número de parte existente en catálogo

+ {#if (lineItem as any).part_description_es} +

{(lineItem as any).part_description_es}

+ {/if} + {#if lineItem.part_number_id} +

ID: {lineItem.part_number_id}

+ {/if}
diff --git a/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-sheet-fa.svelte b/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-sheet-fa.svelte index a091ac75..5bf87a1c 100644 --- a/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-sheet-fa.svelte +++ b/frontend/src/lib/components/dashboard/invoices/edit/items/fa/item-sheet-fa.svelte @@ -23,6 +23,7 @@ editingItem = $bindable(), invoice, onSave, + onCancel, isSaving = false }: { open: boolean; @@ -30,6 +31,7 @@ editingItem: Partial; invoice: Invoice | null; onSave: () => void; + onCancel?: () => void; isSaving?: boolean; } = $props(); @@ -55,7 +57,7 @@

-
@@ -164,7 +166,7 @@
-
- {#if (lineItem as any).class_code} -

Código: {(lineItem as any).class_code}

+ {#if (lineItem as any).class_description} +

{(lineItem as any).class_description}

+ {/if} + {#if lineItem.class_id} +

ID: {lineItem.class_id}

{/if}
@@ -95,7 +165,15 @@
- + (showUnitDialog = true)} + />
+ {#if (lineItem as any).unit_description} +

{(lineItem as any).unit_description}

+ {/if}
@@ -117,9 +198,16 @@
- +
- + (showFractionDialog = true)} + />
+ {#if (customs as any).fraction_description} +

{(customs as any).fraction_description}

+ {/if}
- +
- + (showCountryDialog = true)} + />
+ {#if (customs as any).origin_country_name} +

{(customs as any).origin_country_name}

+ {/if}
+
+
+ +
+ {#if isSearching} +
+ +
+ {:else} + + + + Número de Parte + Descripción (ES) + Descripción (EN) + Clase + + + + + {#if displayedParts.length === 0} + + + No se encontraron números de parte + + + {:else} + {#each displayedParts as part} + handleSelect(part)}> + {part.part_number} + {part.description_spanish || '-'} + {part.description_english || '-'} + {part.part_class || '-'} + + + + + {/each} + {/if} + + + {/if} +
+ + +

+ Mostrando {displayedParts.length} de {filteredParts.length} resultados +

+
+ + diff --git a/frontend/src/lib/components/dashboard/invoices/edit/items/inv/item-sheet-inv.svelte b/frontend/src/lib/components/dashboard/invoices/edit/items/inv/item-sheet-inv.svelte index 4b697771..237fd70e 100644 --- a/frontend/src/lib/components/dashboard/invoices/edit/items/inv/item-sheet-inv.svelte +++ b/frontend/src/lib/components/dashboard/invoices/edit/items/inv/item-sheet-inv.svelte @@ -14,6 +14,7 @@ editingItem = $bindable(), invoice, onSave, + onCancel, isSaving = false }: { open: boolean; @@ -21,6 +22,7 @@ editingItem: Partial; invoice: Invoice | null; onSave: () => void; + onCancel?: () => void; isSaving?: boolean; } = $props(); @@ -258,7 +260,7 @@ - + {/each} +
+
+ +
+ +
+ +
+ {#each uomOptions as option} + + {/each} +
+
+ + +
+ +
+ {#each weightOptions as option} + + {/each} +
+
+
+ +
+ + + + + + +
diff --git a/frontend/src/lib/components/dashboard/invoices/pdf-progress-dialog.svelte b/frontend/src/lib/components/dashboard/invoices/pdf-progress-dialog.svelte index 36fc7e38..685c34a4 100644 --- a/frontend/src/lib/components/dashboard/invoices/pdf-progress-dialog.svelte +++ b/frontend/src/lib/components/dashboard/invoices/pdf-progress-dialog.svelte @@ -63,9 +63,12 @@ } else if (response.state === 'FAILURE') { hasError = true; - statusMessage = "Error al generar el PDF"; + // Intenta mostrar el mensaje de error real si viene en 'result' + const errMsg = response.result ? String(response.result) : "Error desconocido"; + statusMessage = `Error: ${errMsg}`; stopPolling(); - toast.error("Falló la generación del PDF"); + toast.error(`Falló la generación: ${errMsg}`); + console.error("Task failed with result:", response); } } catch (error) { console.error("Error polling task status:", error); diff --git a/frontend/src/lib/components/dashboard/pedimentos/columns.ts b/frontend/src/lib/components/dashboard/pedimentos/columns.ts index 2bdfbe51..69341969 100644 --- a/frontend/src/lib/components/dashboard/pedimentos/columns.ts +++ b/frontend/src/lib/components/dashboard/pedimentos/columns.ts @@ -1,9 +1,15 @@ import type { ColumnDef } from "@tanstack/table-core"; import { renderComponent, renderSnippet } from "$lib/components/ui/data-table/index.js"; import { createRawSnippet } from "svelte"; -import DataTableActions from "./data-table-actions.svelte"; import type { Pedimento } from "$lib/api/dashboard/a76/pedimentos"; +// Extender el tipo ColumnMeta para incluir className +declare module "@tanstack/table-core" { + interface ColumnMeta { + className?: string; + } +} + /** * Formatea un número como moneda */ @@ -86,6 +92,33 @@ function getStatusColor(status?: string | null): string { export function createColumns(onSuccess?: () => void): ColumnDef[] { return [ + { + id: "select", + header: ({ table }) => { + return renderSnippet( + createRawSnippet(() => ({ + render: () => `
` + })) + ); + }, + cell: ({ row }) => { + const isSelected = row.getIsSelected(); + + const checkboxSnippet = createRawSnippet<[{ selected: boolean }]>((getProps) => { + const { selected } = getProps(); + return { + render: () => `
+ +
` + }; + }); + + return renderSnippet(checkboxSnippet, { selected: isSelected }); + }, + size: 40, + enableSorting: false, + enableHiding: false + }, { accessorKey: "id", header: "ID", @@ -120,6 +153,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_type", header: "Tipo", + meta: { className: "hidden md:table-cell" }, cell: ({ row }) => { const typeSnippet = createRawSnippet<[{ type?: string | null }]>((getType) => { const { type } = getType(); @@ -134,6 +168,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_code", header: "Clave", + meta: { className: "hidden lg:table-cell" }, cell: ({ row }) => { const codeSnippet = createRawSnippet<[{ code?: string | null }]>((getCode) => { const { code } = getCode(); @@ -148,6 +183,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "regime", header: "Régimen", + meta: { className: "hidden lg:table-cell" }, cell: ({ row }) => { const regimeSnippet = createRawSnippet<[{ regime?: string | null }]>((getRegime) => { const { regime } = getRegime(); @@ -162,6 +198,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_dates.start_date", header: "Fecha Inicio", + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => { const { date } = getDate(); @@ -176,6 +213,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_dates.end_date", header: "Fecha Final", + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => { const { date } = getDate(); @@ -190,6 +228,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_dates.payment_date", header: "Fecha de Pago", + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => { const { date } = getDate(); @@ -201,37 +240,10 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { return renderSnippet(dateSnippet, { date: formatDate(row.original.pedimento_dates?.payment_date) }); } }, - { - accessorKey: "pedimento_config_update_rectification.pediment_rectifed_18", - header: "Pedimento 18", - cell: ({ row }) => { - const ped18Snippet = createRawSnippet<[{ value?: string | null }]>((getValue) => { - const { value } = getValue(); - return { - render: () => - `
${value || '-'}
` - }; - }); - return renderSnippet(ped18Snippet, { value: row.original.pedimento_config_update_rectification?.pediment_rectifed_18 }); - } - }, - { - accessorKey: "pedimento_config_update_rectification.r1", - header: "Pedimento R1", - cell: ({ row }) => { - const r1Snippet = createRawSnippet<[{ value?: string | null }]>((getValue) => { - const { value } = getValue(); - return { - render: () => - `
${value || '-'}
` - }; - }); - return renderSnippet(r1Snippet, { value: row.original.pedimento_config_update_rectification?.r1 }); - } - }, { accessorKey: "pedimento_validation.electronic_signature", header: "Acuse Electrónico", + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const ackSnippet = createRawSnippet<[{ value?: string | null }]>((getValue) => { const { value } = getValue(); @@ -249,6 +261,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "pedimento_payments.total_contributions", header: "¿Se pagó el impuesto?", + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const paidSnippet = createRawSnippet<[{ value?: string | null }]>((getValue) => { const { value } = getValue(); @@ -266,6 +279,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "client_id", header: "Cliente", + meta: { className: "hidden md:table-cell" }, cell: ({ row }) => { const clientSnippet = createRawSnippet<[{ clientId?: number | null }]>((getClient) => { const { clientId } = getClient(); @@ -309,6 +323,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { }); return renderSnippet(headerSnippet, {}); }, + meta: { className: "hidden lg:table-cell" }, cell: ({ row }) => { const valueSnippet = createRawSnippet<[{ value: string }]>((getValue) => { const { value } = getValue(); @@ -330,6 +345,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { }); return renderSnippet(headerSnippet, {}); }, + meta: { className: "hidden xl:table-cell" }, cell: ({ row }) => { const priceSnippet = createRawSnippet<[{ price: string }]>((getPrice) => { const { price } = getPrice(); @@ -351,6 +367,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { }); return renderSnippet(headerSnippet, {}); }, + meta: { className: "hidden lg:table-cell" }, cell: ({ row }) => { const weightSnippet = createRawSnippet<[{ weight: string }]>((getWeight) => { const { weight } = getWeight(); @@ -365,6 +382,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { { accessorKey: "created_at", header: "Fecha de Creación", + meta: { className: "hidden 2xl:table-cell" }, cell: ({ row }) => { const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => { const { date } = getDate(); @@ -375,13 +393,8 @@ export function createColumns(onSuccess?: () => void): ColumnDef[] { }); return renderSnippet(dateSnippet, { date: formatDate(row.original.created_at) }); } - }, - { - id: "actions", - cell: ({ row }) => { - return renderComponent(DataTableActions, { item: row.original, onSuccess }); - } } + // Columna de acciones eliminada - ahora usamos botones en el footer ]; } diff --git a/frontend/src/lib/components/dashboard/pedimentos/data-table.svelte b/frontend/src/lib/components/dashboard/pedimentos/data-table.svelte index 4c448e3d..8f4bfe0d 100644 --- a/frontend/src/lib/components/dashboard/pedimentos/data-table.svelte +++ b/frontend/src/lib/components/dashboard/pedimentos/data-table.svelte @@ -2,10 +2,13 @@ import { onMount } from 'svelte'; import { type ColumnDef, - getCoreRowModel + getCoreRowModel, + type RowSelectionState } from "@tanstack/table-core"; import { createSvelteTable, FlexRender } from "$lib/components/ui/data-table/index.js"; import * as Table from "$lib/components/ui/table/index.js"; + import { Button } from "$lib/components/ui/button"; + import { Edit } from "lucide-svelte"; type DataTableProps = { columns: ColumnDef[]; @@ -13,6 +16,8 @@ loading: boolean; hasMore: boolean; loadMore: () => void; + selectedId?: number | null; + onRowClick?: (row: TData) => void; }; let { @@ -20,7 +25,9 @@ columns, loading, hasMore, - loadMore + loadMore, + selectedId = null, + onRowClick }: DataTableProps = $props(); const table = createSvelteTable({ @@ -28,12 +35,28 @@ return data; }, columns, - getCoreRowModel: getCoreRowModel() + getCoreRowModel: getCoreRowModel(), + getRowId: (row: any) => row.id?.toString(), + state: { + get rowSelection() { + return selectedId ? { [selectedId]: true } : {}; + } + }, + enableRowSelection: true, + enableMultiRowSelection: false }); let scrollContainer = $state(); let loadingTrigger = $state(); + // Función para manejar doble clic en una fila + function handleRowDoubleClick(row: any) { + const pedimento = row.original; + if (pedimento?.id) { + window.location.href = `/dashboard/pedimentos/edit/${pedimento.id}`; + } + } + // Intersection Observer para detectar cuando el usuario llega al final onMount(() => { const observer = new IntersectionObserver( @@ -60,13 +83,13 @@
-
- - +
+ + {#each table.getHeaderGroups() as headerGroup (headerGroup.id)} {#each headerGroup.headers as header (header.id)} - + {#if !header.isPlaceholder} {#each table.getRowModel().rows as row (row.id)} - + { + if (onRowClick) { + onRowClick(row.original); + } + }} + ondblclick={() => handleRowDoubleClick(row)} + class="cursor-pointer hover:bg-muted/50 transition-colors {row.getIsSelected() ? 'bg-primary/10' : ''}" + > {#each row.getVisibleCells() as cell (cell.id)} - + r.regimen_code).filter((code): code is string => code !== null))) @@ -314,6 +319,32 @@ { value: 'adicional', label: 'Adicional' }, { value: 'decrementable', label: 'Decrementable' } ]; + + export async function checkPaymentDateRate(date: string): Promise { + if (!date || !companyStore.activeCompany?.id) return true; + + try { + const rate = await getExchangeRateByDate(date, companyStore.activeCompany.id); + if (!rate) { + // Abrir modal preventivamente + missingExchangeRateDate = date; + showExchangeRateDialog = true; + return false; + } + return true; + } catch (error) { + console.error('Error checking payment date rate:', error); + // Si hay error de red, asumimos que falta para forzar reintento/captura segura + missingExchangeRateDate = date; + showExchangeRateDialog = true; + return false; + } + } + + export function openExchangeRateDialog(date: string) { + missingExchangeRateDate = date; + showExchangeRateDialog = true; + } @@ -1159,3 +1190,10 @@
+ + {/* Optional: maybe refresh something or just let user continue */}} +/> diff --git a/frontend/src/lib/components/sidebar/modules.ts b/frontend/src/lib/components/sidebar/modules.ts index 17421dc6..7e3fae47 100644 --- a/frontend/src/lib/components/sidebar/modules.ts +++ b/frontend/src/lib/components/sidebar/modules.ts @@ -297,7 +297,7 @@ export function getSidebarData(): SidebarData { { title: m["sidebar.goods.classes"](), url: "/dashboard/goods/fixed-asset-classes", - }, + }, { title: m["sidebar.goods.parts"](), url: "/dashboard/goods/parts", @@ -370,7 +370,7 @@ export function getSidebarData(): SidebarData { { title: m["sidebar.export_invoices.repair"](), url: "/dashboard/invoices?operation_type=exp&invoice_type=REPAR", - }, + }, ], }, { diff --git a/frontend/src/lib/components/sidebar/team-switcher.svelte b/frontend/src/lib/components/sidebar/team-switcher.svelte index c61c8a3d..088b02df 100644 --- a/frontend/src/lib/components/sidebar/team-switcher.svelte +++ b/frontend/src/lib/components/sidebar/team-switcher.svelte @@ -10,10 +10,10 @@ const sidebar = useSidebar(); - // Derivar la URL del logo + // Derivar la URL del logo usando el endpoint específico let activeCompanyLogoUrl = $derived( companyStore.activeCompany?.logo - ? getBackendAssetUrl(companyStore.activeCompany.logo) + ? getBackendAssetUrl(`v1/a76/company/${companyStore.activeCompany.id}/logo/image?t=${new Date().getTime()}`) : null ); @@ -89,7 +89,7 @@
{#if company.logo} {company.name} diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.svelte new file mode 100644 index 00000000..7ac64712 --- /dev/null +++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.svelte @@ -0,0 +1,7 @@ + + + diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte new file mode 100644 index 00000000..9b14b3ec --- /dev/null +++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-sub.svelte @@ -0,0 +1,7 @@ + + + diff --git a/frontend/src/lib/components/ui/dropdown-menu/index.ts b/frontend/src/lib/components/ui/dropdown-menu/index.ts index 1cf9f701..9ac1bdd1 100644 --- a/frontend/src/lib/components/ui/dropdown-menu/index.ts +++ b/frontend/src/lib/components/ui/dropdown-menu/index.ts @@ -1,4 +1,4 @@ -import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui"; +// import { DropdownMenu as DropdownMenuPrimitive } from "bits-ui"; import CheckboxItem from "./dropdown-menu-checkbox-item.svelte"; import Content from "./dropdown-menu-content.svelte"; import Group from "./dropdown-menu-group.svelte"; @@ -12,8 +12,8 @@ import Trigger from "./dropdown-menu-trigger.svelte"; import SubContent from "./dropdown-menu-sub-content.svelte"; import SubTrigger from "./dropdown-menu-sub-trigger.svelte"; import GroupHeading from "./dropdown-menu-group-heading.svelte"; -const Sub = DropdownMenuPrimitive.Sub; -const Root = DropdownMenuPrimitive.Root; +import Sub from "./dropdown-menu-sub.svelte"; +import Root from "./dropdown-menu-root.svelte"; export { CheckboxItem, diff --git a/frontend/src/lib/stores/company.svelte.ts b/frontend/src/lib/stores/company.svelte.ts index b3da0f1f..9f04bcdb 100644 --- a/frontend/src/lib/stores/company.svelte.ts +++ b/frontend/src/lib/stores/company.svelte.ts @@ -144,6 +144,30 @@ class CompanyStore { } } + /** + * Actualiza los datos de une empresa en el store localmente + * Útil para reflejar cambios inmediatos (ej: cambio de logo) sin recargar + */ + updateCompany(id: number, data: Partial) { + // 1. Actualizar en la lista + const index = this._companies.findIndex(c => c.id === id); + if (index !== -1) { + this._companies[index] = { ...this._companies[index], ...data }; + + // 2. Si es la activa, actualizar también + if (this._activeCompany?.id === id) { + this._activeCompany = { ...this._activeCompany, ...data }; + // Actualizar persistencia si es necesario + if (typeof window !== 'undefined') { + // Disparar evento para notificar cambios a componentes que no usan el store reactivo directo (si los hay) + window.dispatchEvent(new CustomEvent('companyChanged', { + detail: { companyId: id } + })); + } + } + } + } + /** * Restaura la compañía activa desde localStorage */ diff --git a/frontend/src/routes/api-sveltekit/classes/[id]/+server.ts b/frontend/src/routes/api-sveltekit/classes/[id]/+server.ts new file mode 100644 index 00000000..d8de375c --- /dev/null +++ b/frontend/src/routes/api-sveltekit/classes/[id]/+server.ts @@ -0,0 +1,87 @@ +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = async ({ cookies, url, params }) => { + const token = cookies.get('access_token'); + const { id } = params; + + // Obtener company_id de la cookie o query params + const companyId = cookies.get('active_company_id') || url.searchParams.get('company_id'); + + if (!companyId) { + return new Response( + JSON.stringify({ error: 'No company selected' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + // Configurar la URL de la API usando las variables de entorno + let apiUrl = process.env.INTERNAL_API_URL; + if (!apiUrl) { + apiUrl = process.env.VITE_API_URL; + // Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR) + apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend'); + } + + // Normalizar la URL + const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`; + + try { + const fetchUrl = `${baseUrl}v1/a76/classes/${id}?company_id=${companyId}`; + console.log('Fetching class from:', fetchUrl); + + const response = await fetch( + fetchUrl, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + } + } + ); + + if (!response.ok) { + const errorText = await response.text(); + console.error('Error response from backend:', errorText); + return new Response( + JSON.stringify({ + error: 'Failed to fetch class', + details: errorText + }), + { + status: response.status, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + const data = await response.json(); + return new Response(JSON.stringify(data), { + status: 200, + headers: { + 'Content-Type': 'application/json' + } + }); + } catch (error) { + console.error('Error in class API route:', error); + return new Response( + JSON.stringify({ + error: 'Internal server error', + message: error instanceof Error ? error.message : 'Unknown error' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } +}; diff --git a/frontend/src/routes/api-sveltekit/parts/+server.ts b/frontend/src/routes/api-sveltekit/parts/+server.ts new file mode 100644 index 00000000..1c1cae0e --- /dev/null +++ b/frontend/src/routes/api-sveltekit/parts/+server.ts @@ -0,0 +1,91 @@ +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = async ({ cookies, url }) => { + const token = cookies.get('access_token'); + + // Obtener company_id de la cookie + const companyId = cookies.get('active_company_id'); + + if (!companyId) { + return new Response( + JSON.stringify({ error: 'No company selected' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + // Configurar la URL de la API usando las variables de entorno + let apiUrl = process.env.INTERNAL_API_URL; + if (!apiUrl) { + apiUrl = process.env.VITE_API_URL; + // Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR) + apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend'); + } + + // Normalizar la URL + const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`; + + // Get query parameters and add company_id + const searchParams = new URLSearchParams(url.search); + searchParams.set('company_id', companyId); + const queryString = searchParams.toString(); + + try { + const fetchUrl = `${baseUrl}v1/a76/parts?${queryString}`; + console.log('Fetching parts from:', fetchUrl); + + const response = await fetch( + fetchUrl, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + } + } + ); + + if (!response.ok) { + const errorText = await response.text(); + console.error('Error response from backend:', errorText); + return new Response( + JSON.stringify({ + error: 'Failed to fetch parts', + details: errorText + }), + { + status: response.status, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + const data = await response.json(); + return new Response(JSON.stringify(data), { + status: 200, + headers: { + 'Content-Type': 'application/json' + } + }); + } catch (error) { + console.error('Error in parts API route:', error); + return new Response( + JSON.stringify({ + error: 'Internal server error', + message: error instanceof Error ? error.message : 'Unknown error' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } +}; diff --git a/frontend/src/routes/api-sveltekit/parts/[id]/+server.ts b/frontend/src/routes/api-sveltekit/parts/[id]/+server.ts new file mode 100644 index 00000000..ba82f40d --- /dev/null +++ b/frontend/src/routes/api-sveltekit/parts/[id]/+server.ts @@ -0,0 +1,87 @@ +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = async ({ cookies, url, params }) => { + const token = cookies.get('access_token'); + const { id } = params; + + // Obtener company_id de la cookie o query params + const companyId = cookies.get('active_company_id') || url.searchParams.get('company_id'); + + if (!companyId) { + return new Response( + JSON.stringify({ error: 'No company selected' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + // Configurar la URL de la API usando las variables de entorno + let apiUrl = process.env.INTERNAL_API_URL; + if (!apiUrl) { + apiUrl = process.env.VITE_API_URL; + // Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR) + apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend'); + } + + // Normalizar la URL + const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`; + + try { + const fetchUrl = `${baseUrl}v1/a76/parts/${id}?company_id=${companyId}`; + console.log('Fetching part from:', fetchUrl); + + const response = await fetch( + fetchUrl, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + } + } + ); + + if (!response.ok) { + const errorText = await response.text(); + console.error('Error response from backend:', errorText); + return new Response( + JSON.stringify({ + error: 'Failed to fetch part', + details: errorText + }), + { + status: response.status, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + const data = await response.json(); + return new Response(JSON.stringify(data), { + status: 200, + headers: { + 'Content-Type': 'application/json' + } + }); + } catch (error) { + console.error('Error in part API route:', error); + return new Response( + JSON.stringify({ + error: 'Internal server error', + message: error instanceof Error ? error.message : 'Unknown error' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } +}; diff --git a/frontend/src/routes/api-sveltekit/units-of-measure/[id]/+server.ts b/frontend/src/routes/api-sveltekit/units-of-measure/[id]/+server.ts new file mode 100644 index 00000000..110e12c4 --- /dev/null +++ b/frontend/src/routes/api-sveltekit/units-of-measure/[id]/+server.ts @@ -0,0 +1,87 @@ +import type { RequestHandler } from './$types'; + +export const GET: RequestHandler = async ({ cookies, params, url }) => { + const token = cookies.get('access_token'); + const { id } = params; + + // Obtener company_id de la cookie o query params + const companyId = cookies.get('active_company_id') || url.searchParams.get('company_id'); + + if (!companyId) { + return new Response( + JSON.stringify({ error: 'No company selected' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + // Configurar la URL de la API usando las variables de entorno + let apiUrl = process.env.INTERNAL_API_URL; + if (!apiUrl) { + apiUrl = process.env.VITE_API_URL; + // Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR) + apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend'); + } + + // Normalizar la URL + const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`; + + try { + const fetchUrl = `${baseUrl}v1/a76/units-of-measure/${id}?company_id=${companyId}`; + console.log('Fetching unit of measure from:', fetchUrl); + + const response = await fetch( + fetchUrl, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + } + } + ); + + if (!response.ok) { + const errorText = await response.text(); + console.error('Error response from backend:', errorText); + return new Response( + JSON.stringify({ + error: 'Failed to fetch unit of measure', + details: errorText + }), + { + status: response.status, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } + + const data = await response.json(); + return new Response(JSON.stringify(data), { + status: 200, + headers: { + 'Content-Type': 'application/json' + } + }); + } catch (error) { + console.error('Error in unit of measure API route:', error); + return new Response( + JSON.stringify({ + error: 'Internal server error', + message: error instanceof Error ? error.message : 'Unknown error' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json' + } + } + ); + } +}; diff --git a/frontend/src/routes/dashboard/+layout.svelte b/frontend/src/routes/dashboard/+layout.svelte index 13ca79ea..0a9c990f 100644 --- a/frontend/src/routes/dashboard/+layout.svelte +++ b/frontend/src/routes/dashboard/+layout.svelte @@ -7,6 +7,7 @@ import { Separator } from "$lib/components/ui/separator/index.js"; import * as Sidebar from "$lib/components/ui/sidebar/index.js"; import { companyStore } from "$lib/stores/company.svelte"; + import ExchangeRateGuard from "$lib/components/dashboard/exchange_rate/exchange-rate-guard.svelte"; let { data, children }: { data: LayoutData; children: any } = $props(); @@ -33,7 +34,7 @@ - +
@@ -55,9 +56,11 @@ -->
-
+
{@render children?.()}
+ + diff --git a/frontend/src/routes/dashboard/general_catalogs/company_information/edit/[[id]]/+page.svelte b/frontend/src/routes/dashboard/general_catalogs/company_information/edit/[[id]]/+page.svelte index 136f81ff..290ce649 100644 --- a/frontend/src/routes/dashboard/general_catalogs/company_information/edit/[[id]]/+page.svelte +++ b/frontend/src/routes/dashboard/general_catalogs/company_information/edit/[[id]]/+page.svelte @@ -14,6 +14,7 @@ uploadCompanyLogo, type Company } from '$lib/api/dashboard/a76/general_catalogs/company'; + import { companyStore } from '$lib/stores/company.svelte'; import { getBackendAssetUrl } from '$lib/utils'; import { ArrowLeft, LoaderCircle, Save, Upload, X, Building2, FileText, User, Settings } from 'lucide-svelte'; @@ -25,15 +26,18 @@ let loading = $state(false); let uploading = $state(false); let error = $state(null); + let activeTab = $state('general'); + let logoFile = $state(null); let logoPreview = $state(null); let currentLogo = $state(null); let uploadingLogo = $state(false); - let activeTab = $state('general'); - + // URL completa del logo derivada let currentLogoUrl = $derived( - logoPreview || getBackendAssetUrl(currentLogo) || '' + logoPreview + ? logoPreview + : (currentLogo ? getBackendAssetUrl(`v1/a76/company/${id}/logo/image?t=${new Date().getTime()}`) : '') ); // 2. Estado Inicial (Reset) @@ -104,7 +108,15 @@ is_service_company: item.is_service_company || false, order_format_type: item.order_format_type || '', ctpat_svi: item.ctpat_svi || '', - trusted_exporter_number: item.trusted_exporter_number || '' + trusted_exporter_number: item.trusted_exporter_number || '', + logo: item.logo || '', + previous_code: item.previous_code || 0, + client_name: item.client_name || '', + subassembly_mode: item.subassembly_mode || '', + broker_company: item.broker_company || '', + inter_db_name: item.inter_db_name || '', + prevalidator_key: item.prevalidator_key || '', + seventh_amendment: item.seventh_amendment || false }; // Guardar la URL del logo actual si existe if (item.logo) { @@ -118,6 +130,9 @@ } } + + const clean = (value: any) => (typeof value === 'string' ? value.trim() || null : value); + function handleLogoChange(event: Event) { const target = event.target as HTMLInputElement; const file = target.files?.[0]; @@ -170,6 +185,9 @@ currentLogo = response.data.logo_path; logoFile = null; logoPreview = null; + + // Actualizar el store reactivamente + companyStore.updateCompany(companyId, { logo: response.data.logo_path }); } } catch (e: any) { error = `Error al subir el logo: ${e.message}`; @@ -178,33 +196,6 @@ } } - const clean = (value: any) => (typeof value === 'string' ? value.trim() || null : value); - - async function handleFileSelect(e: Event) { - const input = e.target as HTMLInputElement; - if (!input.files || input.files.length === 0) return; - - const file = input.files[0]; - if (!isEdit) { - alert("Primero debes guardar la empresa antes de subir un logo."); - return; - } - - uploading = true; - try { - const res = await uploadCompanyLogo(Number(id), file); - if (res.data) { - formData.logo = res.data.path; - } else if (res.error) { - alert("Error al subir imagen: " + res.error); - } - } catch (err) { - alert("Error al intentar subir la imagen"); - } finally { - uploading = false; - } - } - async function handleSubmit() { error = null; loading = true; @@ -222,6 +213,7 @@ main_activity: clean(formData.main_activity), program: clean(formData.program), program_number: clean(formData.program_number), + prosec: Number(formData.prosec) || 0, prosec_authorization: clean(formData.prosec_authorization), responsible_name: clean(formData.responsible_name), responsible_last_name: clean(formData.responsible_last_name), @@ -239,7 +231,10 @@ broker_company: clean(formData.broker_company), inter_db_name: clean(formData.inter_db_name), prevalidator_key: clean(formData.prevalidator_key), - seventh_amendment: formData.seventh_amendment + seventh_amendment: formData.seventh_amendment, + // Ensure optional booleans are passed correctly or default to false/null if needed + has_express_line: formData.has_express_line, + is_service_company: formData.is_service_company }; const response = isEdit @@ -285,6 +280,8 @@
+ +
@@ -344,36 +341,9 @@
-
-
- -
- - {#if isEdit} -
- - -
- {/if} -
-

Sube una imagen para obtener su ruta local.

-
-
- - -
+
+ +
diff --git a/frontend/src/routes/dashboard/general_catalogs/units_of_measure/general/+page.svelte b/frontend/src/routes/dashboard/general_catalogs/units_of_measure/general/+page.svelte index f8b53600..bae27c42 100644 --- a/frontend/src/routes/dashboard/general_catalogs/units_of_measure/general/+page.svelte +++ b/frontend/src/routes/dashboard/general_catalogs/units_of_measure/general/+page.svelte @@ -44,7 +44,7 @@
-

Unidades de Medida Generales

+

Unidades de Medida

Catálogo general de unidades de medida

diff --git a/frontend/src/routes/dashboard/invoices/+page.svelte b/frontend/src/routes/dashboard/invoices/+page.svelte index 06086755..b20b25f1 100644 --- a/frontend/src/routes/dashboard/invoices/+page.svelte +++ b/frontend/src/routes/dashboard/invoices/+page.svelte @@ -1,5 +1,7 @@
@@ -625,15 +699,37 @@ Desactualizar - + + + + +
+ + + + + + {#if selectedInvoice && companyStore.activeCompany} + + {/if}
\ No newline at end of file diff --git a/frontend/src/routes/dashboard/invoices/edit/[id]/+page.server.ts b/frontend/src/routes/dashboard/invoices/edit/[id]/+page.server.ts index 2ec29c64..78a4d101 100644 --- a/frontend/src/routes/dashboard/invoices/edit/[id]/+page.server.ts +++ b/frontend/src/routes/dashboard/invoices/edit/[id]/+page.server.ts @@ -20,13 +20,10 @@ export const load: PageServerLoad = async ({ params, cookies, fetch, url }) => { const operationTypeParam = url.searchParams.get('operation_type'); const invoiceTypeParam = url.searchParams.get('invoice_type'); - // Parsear operation_type de forma segura - let parsedOperationType: number | null = null; - if (operationTypeParam) { - const parsed = parseInt(operationTypeParam, 10); - if (!isNaN(parsed)) { - parsedOperationType = parsed; - } + // Validar que operation_type sea 'exp' o 'imp' + let parsedOperationType: string | null = null; + if (operationTypeParam && (operationTypeParam === 'exp' || operationTypeParam === 'imp')) { + parsedOperationType = operationTypeParam; } // Cargar datos de referencia necesarios diff --git a/frontend/src/routes/dashboard/invoices/edit/[id]/+page.svelte b/frontend/src/routes/dashboard/invoices/edit/[id]/+page.svelte index 62065835..9567cb94 100644 --- a/frontend/src/routes/dashboard/invoices/edit/[id]/+page.svelte +++ b/frontend/src/routes/dashboard/invoices/edit/[id]/+page.svelte @@ -1,7 +1,8 @@