393 lines
13 KiB
Python
393 lines
13 KiB
Python
"""
|
|
Provenance Validation Service v1
|
|
|
|
Service for validating procurement provenance chain read-only.
|
|
|
|
Validates:
|
|
- Resource → Project
|
|
- Resource → Invoice → Purchase → Project
|
|
- Resource → Specification → Project
|
|
- Module existence
|
|
- Nullable Specification handling
|
|
"""
|
|
from typing import Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models import Resource, Project, Invoice, Purchase, Specification, Module, SpecificationItem
|
|
from app.services.exceptions import (
|
|
ResourceAllocationError,
|
|
ValidationError,
|
|
)
|
|
|
|
|
|
class ProvenanceValidationError(ResourceAllocationError):
|
|
"""Base exception for provenance validation errors"""
|
|
pass
|
|
|
|
|
|
class ResourceNotFoundError(ProvenanceValidationError):
|
|
"""Resource не существует"""
|
|
pass
|
|
|
|
|
|
class ProjectNotFoundError(ProvenanceValidationError):
|
|
"""Project не существует"""
|
|
pass
|
|
|
|
|
|
class InvoiceNotFoundError(ProvenanceValidationError):
|
|
"""Invoice не существует"""
|
|
pass
|
|
|
|
|
|
class PurchaseNotFoundError(ProvenanceValidationError):
|
|
"""Purchase не существует (цепочка нарушена)"""
|
|
pass
|
|
|
|
|
|
class SpecificationNotFoundError(ProvenanceValidationError):
|
|
"""Specification не существует"""
|
|
pass
|
|
|
|
|
|
class ProjectMismatchError(ProvenanceValidationError):
|
|
"""Resource и Invoice/Specification относятся к разным Projects"""
|
|
pass
|
|
|
|
|
|
class ModuleNotFoundError(ProvenanceValidationError):
|
|
"""Module не существует"""
|
|
pass
|
|
|
|
|
|
class BrokenProvenanceChainError(ProvenanceValidationError):
|
|
"""Нарушена целостность provenance цепочки"""
|
|
pass
|
|
|
|
|
|
class ProvenanceValidationService:
|
|
"""Service для валидации procurement provenance chain (read-only)"""
|
|
|
|
def __init__(self, db: Session):
|
|
"""
|
|
Initialize service with database session.
|
|
|
|
Args:
|
|
db: SQLAlchemy database session
|
|
"""
|
|
self.db = db
|
|
|
|
def validate_resource_provenance(self, resource_id: int) -> None:
|
|
"""
|
|
Validate the complete provenance chain of a Resource.
|
|
|
|
This is a READ-ONLY validation that checks:
|
|
1. Resource exists and belongs to a Project
|
|
2. Resource → Invoice → Purchase → Project match
|
|
3. Resource → Specification → Project match (if specified)
|
|
4. Module exists
|
|
5. All intermediate entities exist
|
|
|
|
Args:
|
|
resource_id: ID of the Resource to validate
|
|
|
|
Raises:
|
|
ResourceNotFoundError: Resource не существует
|
|
ProjectNotFoundError: Project не существует
|
|
InvoiceNotFoundError: Invoice не существует
|
|
PurchaseNotFoundError: Purchase не существует (цепочка нарушена)
|
|
SpecificationNotFoundError: Specification не существует
|
|
ProjectMismatchError: Resource, Invoice, Specification относятся к разным Projects
|
|
ModuleNotFoundError: Module не существует
|
|
BrokenProvenanceChainError: Нарушена целостность цепочки
|
|
"""
|
|
# 1. Validate Resource exists
|
|
resource = self._get_resource(resource_id)
|
|
|
|
# 2. Validate Resource → Project
|
|
project = self._validate_resource_project(resource)
|
|
|
|
# 3. Validate Resource → Module
|
|
self._validate_resource_module(resource)
|
|
|
|
# 4. Validate Resource → Invoice → Purchase → Project
|
|
self._validate_invoice_chain(resource, project)
|
|
|
|
# 5. Validate Resource → Specification (if specified)
|
|
if resource.specification_id is not None:
|
|
self._validate_specification_chain(resource, project)
|
|
|
|
# All validations passed
|
|
pass
|
|
|
|
def _get_resource(self, resource_id: int) -> Resource:
|
|
"""
|
|
Get Resource by ID.
|
|
|
|
Args:
|
|
resource_id: Resource ID
|
|
|
|
Returns:
|
|
Resource object
|
|
|
|
Raises:
|
|
ResourceNotFoundError: Resource не существует
|
|
"""
|
|
resource = self.db.query(Resource).filter(
|
|
Resource.id == resource_id
|
|
).first()
|
|
|
|
if not resource:
|
|
raise ResourceNotFoundError(f"Resource {resource_id} not found")
|
|
|
|
return resource
|
|
|
|
def _validate_resource_project(self, resource: Resource) -> Project:
|
|
"""
|
|
Validate that Resource belongs to an existing Project.
|
|
|
|
Args:
|
|
resource: Resource object
|
|
|
|
Returns:
|
|
Project object
|
|
|
|
Raises:
|
|
ProjectNotFoundError: Project не существует
|
|
BrokenProvenanceChainError: Проект не найден
|
|
"""
|
|
project = self.db.query(Project).filter(
|
|
Project.id == resource.project_id
|
|
).first()
|
|
|
|
if not project:
|
|
raise BrokenProvenanceChainError(
|
|
f"Resource {resource.id} references non-existent Project {resource.project_id}"
|
|
)
|
|
|
|
return project
|
|
|
|
def _validate_resource_module(self, resource: Resource) -> Module:
|
|
"""
|
|
Validate that Resource references an existing Module.
|
|
|
|
Args:
|
|
resource: Resource object
|
|
|
|
Returns:
|
|
Module object
|
|
|
|
Raises:
|
|
ModuleNotFoundError: Module не существует
|
|
"""
|
|
module = self.db.query(Module).filter(
|
|
Module.id == resource.module_id
|
|
).first()
|
|
|
|
if not module:
|
|
raise ModuleNotFoundError(
|
|
f"Resource {resource.id} references non-existent Module {resource.module_id}"
|
|
)
|
|
|
|
return module
|
|
|
|
def _validate_invoice_chain(self, resource: Resource, project: Project) -> None:
|
|
"""
|
|
Validate Resource → Invoice → Purchase → Project chain.
|
|
|
|
Args:
|
|
resource: Resource object
|
|
project: Project object (already validated)
|
|
|
|
Raises:
|
|
InvoiceNotFoundError: Invoice не существует
|
|
PurchaseNotFoundError: Purchase не существует
|
|
ProjectMismatchError: Invoice относится к другому Project
|
|
BrokenProvenanceChainError: Цепочка нарушена
|
|
"""
|
|
if resource.invoice_id is None:
|
|
# Invoice is optional, validation passes
|
|
return
|
|
|
|
# Get Invoice
|
|
invoice = self.db.query(Invoice).filter(
|
|
Invoice.id == resource.invoice_id
|
|
).first()
|
|
|
|
if not invoice:
|
|
raise InvoiceNotFoundError(
|
|
f"Resource {resource.id} references non-existent Invoice {resource.invoice_id}"
|
|
)
|
|
|
|
# Get Purchase from Invoice
|
|
purchase = self.db.query(Purchase).filter(
|
|
Purchase.id == invoice.purchase_id
|
|
).first()
|
|
|
|
if not purchase:
|
|
raise PurchaseNotFoundError(
|
|
f"Invoice {resource.invoice_id} references non-existent Purchase {invoice.purchase_id}"
|
|
)
|
|
|
|
# Verify Invoice belongs to the same Project as Resource
|
|
if purchase.project_id != project.id:
|
|
raise ProjectMismatchError(
|
|
f"Resource {resource.id} (Project {project.id}) references "
|
|
f"Invoice {resource.invoice_id} which belongs to Project {purchase.project_id}"
|
|
)
|
|
|
|
# Check that Purchase is valid (optional additional check)
|
|
if not purchase.purchase_number or not purchase.project_id:
|
|
raise BrokenProvenanceChainError(
|
|
f"Purchase {purchase.id} is incomplete or corrupted"
|
|
)
|
|
|
|
def _validate_specification_chain(self, resource: Resource, project: Project) -> Specification:
|
|
"""
|
|
Validate Resource → Specification → Project chain.
|
|
|
|
Args:
|
|
resource: Resource object
|
|
project: Project object (already validated)
|
|
|
|
Returns:
|
|
Specification object
|
|
|
|
Raises:
|
|
SpecificationNotFoundError: Specification не существует
|
|
ProjectMismatchError: Specification относится к другому Project
|
|
BrokenProvenanceChainError: Цепочка нарушена
|
|
"""
|
|
# Get Specification
|
|
specification = self.db.query(Specification).filter(
|
|
Specification.id == resource.specification_id
|
|
).first()
|
|
|
|
if not specification:
|
|
raise SpecificationNotFoundError(
|
|
f"Resource {resource.id} references non-existent Specification {resource.specification_id}"
|
|
)
|
|
|
|
# Verify Specification belongs to the same Project as Resource
|
|
if specification.project_id != project.id:
|
|
raise ProjectMismatchError(
|
|
f"Resource {resource.id} (Project {project.id}) references "
|
|
f"Specification {resource.specification_id} which belongs to Project {specification.project_id}"
|
|
)
|
|
|
|
return specification
|
|
|
|
def validate_resource_exists(self, resource_id: int) -> bool:
|
|
"""
|
|
Check if a Resource exists (without full validation).
|
|
|
|
Args:
|
|
resource_id: Resource ID
|
|
|
|
Returns:
|
|
True if Resource exists, False otherwise
|
|
"""
|
|
resource = self.db.query(Resource).filter(
|
|
Resource.id == resource_id
|
|
).first()
|
|
|
|
return resource is not None
|
|
|
|
def get_provenance_chain(self, resource_id: int) -> Optional[dict]:
|
|
"""
|
|
Get the complete provenance chain for a Resource (read-only query).
|
|
|
|
Args:
|
|
resource_id: Resource ID
|
|
|
|
Returns:
|
|
Dictionary with provenance chain data, or None if Resource not found
|
|
"""
|
|
resource = self.db.query(Resource).filter(
|
|
Resource.id == resource_id
|
|
).first()
|
|
|
|
if not resource:
|
|
return None
|
|
|
|
chain = {
|
|
'resource': {
|
|
'id': resource.id,
|
|
'project_id': resource.project_id,
|
|
'module_id': resource.module_id,
|
|
'quantity': resource.quantity,
|
|
'invoice_id': resource.invoice_id,
|
|
'specification_id': resource.specification_id,
|
|
},
|
|
'project': None,
|
|
'invoice': None,
|
|
'purchase': None,
|
|
'specification': None,
|
|
'module': None,
|
|
}
|
|
|
|
# Get Project
|
|
project = self.db.query(Project).filter(
|
|
Project.id == resource.project_id
|
|
).first()
|
|
|
|
if project:
|
|
chain['project'] = {
|
|
'id': project.id,
|
|
'name': project.name,
|
|
}
|
|
|
|
# Get Invoice
|
|
if resource.invoice_id:
|
|
invoice = self.db.query(Invoice).filter(
|
|
Invoice.id == resource.invoice_id
|
|
).first()
|
|
|
|
if invoice:
|
|
chain['invoice'] = {
|
|
'id': invoice.id,
|
|
'invoice_number': invoice.invoice_number,
|
|
'invoice_date': str(invoice.invoice_date) if invoice.invoice_date else None,
|
|
}
|
|
|
|
# Get Purchase from Invoice
|
|
purchase = self.db.query(Purchase).filter(
|
|
Purchase.id == invoice.purchase_id
|
|
).first()
|
|
|
|
if purchase:
|
|
chain['purchase'] = {
|
|
'id': purchase.id,
|
|
'purchase_number': purchase.purchase_number,
|
|
'purchase_date': str(purchase.purchase_date) if purchase.purchase_date else None,
|
|
'project_id': purchase.project_id,
|
|
}
|
|
|
|
# Get Specification
|
|
if resource.specification_id:
|
|
specification = self.db.query(Specification).filter(
|
|
Specification.id == resource.specification_id
|
|
).first()
|
|
|
|
if specification:
|
|
chain['specification'] = {
|
|
'id': specification.id,
|
|
'specification_number': specification.specification_number,
|
|
'specification_date': str(specification.specification_date) if specification.specification_date else None,
|
|
'project_id': specification.project_id,
|
|
}
|
|
|
|
# Get Module
|
|
module = self.db.query(Module).filter(
|
|
Module.id == resource.module_id
|
|
).first()
|
|
|
|
if module:
|
|
chain['module'] = {
|
|
'id': module.id,
|
|
'name': module.name,
|
|
}
|
|
|
|
return chain
|