""" Resource Receipt Service v1 Service for receiving purchased resources into the project's general pool. Receives Resource from Invoice/Specification provenance. """ from decimal import Decimal from typing import Optional from sqlalchemy.orm import Session from app.models import Resource, Project, Module, Invoice, Specification, Purchase from app.services.resource_receipt_service_exceptions import ( ProjectNotFoundError, ModuleNotFoundError, InvoiceNotFoundError, SpecificationNotFoundError, SpecificationProjectMismatchError, InvoiceProjectMismatchError, ValidationError ) class ResourceReceiptService: """Сервис приёма приобретённого ресурса в общий пул проекта.""" def __init__(self, db: Session): """ Initialize service with database session. Args: db: SQLAlchemy database session """ self.db = db def receive_resource( self, project_id: int, module_id: int, quantity: int | Decimal, invoice_id: int, specification_id: Optional[int] = None ) -> Resource: """ Create Resource from invoice/specification provenance. Creates a new Resource record in the project's general pool. All provenance fields are preserved: - project - module - quantity - invoice - specification (optional) Args: project_id: ID of the Project module_id: ID of the Module quantity: Quantity of resources (must be > 0) invoice_id: ID of the Invoice specification_id: Optional ID of the Specification Returns: Created Resource object Raises: ProjectNotFoundError: Project не существует ModuleNotFoundError: Module не существует InvoiceNotFoundError: Invoice не существует SpecificationNotFoundError: Specification не существует SpecificationProjectMismatchError: Specification другого Project InvoiceProjectMismatchError: Invoice другого Project ValidationError: quantity ≤ 0 """ # Validate quantity first if not self._validate_quantity(quantity): raise ValidationError("Quantity must be greater than 0") # Check Project exists project = self.db.query(Project).filter( Project.id == project_id ).first() if not project: raise ProjectNotFoundError(f"Project {project_id} not found") # Check Module exists module = self.db.query(Module).filter( Module.id == module_id ).first() if not module: raise ModuleNotFoundError(f"Module {module_id} not found") # Check Invoice exists invoice = self.db.query(Invoice).filter( Invoice.id == invoice_id ).first() if not invoice: raise InvoiceNotFoundError(f"Invoice {invoice_id} not found") # Verify Invoice belongs to the same Project # Invoice → Purchase → Project purchase = self.db.query(Purchase).filter( Purchase.id == invoice.purchase_id ).first() if not purchase: raise InvoiceProjectMismatchError( f"Invoice {invoice_id} has invalid Purchase reference" ) if purchase.project_id != project_id: raise InvoiceProjectMismatchError( f"Invoice {invoice_id} belongs to Project {purchase.project_id}, " f"not {project_id}" ) # Check Specification if provided spec = None if specification_id is not None: spec = self.db.query(Specification).filter( Specification.id == specification_id ).first() if not spec: raise SpecificationNotFoundError( f"Specification {specification_id} not found" ) # Verify Specification belongs to the same Project if spec.project_id != project_id: raise SpecificationProjectMismatchError( f"Specification {specification_id} belongs to Project " f"{spec.project_id}, not {project_id}" ) # Create Resource resource = Resource( project_id=project_id, module_id=module_id, quantity=quantity, invoice_id=invoice_id, specification_id=specification_id, invoice_number=invoice.invoice_number, invoice_date=invoice.invoice_date ) self.db.add(resource) self.db.flush() return resource def _validate_quantity(self, quantity: int | Decimal) -> bool: """ Validate quantity > 0. Args: quantity: Quantity to validate Returns: True if quantity > 0, False otherwise """ if isinstance(quantity, Decimal): return quantity > 0 return quantity > 0 def get_resource_by_id(self, resource_id: int) -> Optional[Resource]: """ Get Resource by ID. Args: resource_id: Resource ID Returns: Resource or None """ return self.db.query(Resource).filter( Resource.id == resource_id ).first() def get_all_resources_for_project(self, project_id: int) -> list[Resource]: """ Get all Resources for a Project. Args: project_id: Project ID Returns: List of Resource objects """ return self.db.query(Resource).filter( Resource.project_id == project_id ).all() def get_remaining_quantity(self, resource_id: int) -> int: """ Calculate remaining quantity after allocations. Args: resource_id: Resource ID Returns: Remaining quantity """ from sqlalchemy import func from app.models import ResourceAllocation allocated = self.db.query( func.sum(ResourceAllocation.quantity) ).filter( ResourceAllocation.resource_id == resource_id ).scalar() or 0 resource = self.db.query(Resource).filter( Resource.id == resource_id ).first() if not resource: raise ValueError(f"Resource {resource_id} not found") return resource.quantity - allocated