Initial commit

This commit is contained in:
Alex
2026-10-07 19:57:07 +00:00
commit 6e6035c789
131 changed files with 23101 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
"""
Empty __init__.py for services package
"""
Binary file not shown.
Binary file not shown.
+58
View File
@@ -0,0 +1,58 @@
"""
Service exceptions for resource allocation
"""
class ResourceAllocationError(Exception):
"""Base exception for resource allocation errors"""
pass
class ResourceNotFoundError(ResourceAllocationError):
"""Resource not found"""
pass
class SystemNotFoundError(ResourceAllocationError):
"""System not found"""
pass
class GuardianNotFoundError(ResourceAllocationError):
"""Guardian not found"""
pass
class AllocationError(ResourceAllocationError):
"""Allocation failed"""
pass
class ValidationError(ResourceAllocationError):
"""Validation failed"""
pass
class InsufficientBalanceError(ResourceAllocationError):
"""Not enough remaining balance"""
pass
class CoreInCommonError(ResourceAllocationError):
"""Cannot allocate Core to Common part"""
pass
class InvalidGuardianError(ResourceAllocationError):
"""Guardian doesn't belong to specified System"""
pass
class ProjectMismatchError(ResourceAllocationError):
"""Resource and System belong to different Projects"""
pass
class CoreAlreadyExistsError(ResourceAllocationError):
"""Cannot create second Core for same Guardian"""
pass
+55
View File
@@ -0,0 +1,55 @@
"""
Pool resource service for handling resource operations
"""
from sqlalchemy.orm import Session
from app.models import PoolResource, PoolReceipt, PoolAllocation
from typing import Optional
class PoolResourceService:
def __init__(self, db: Session):
self.db = db
def get_current_balance(self, pool_resource_id: int) -> int:
"""Calculate current balance from receipts and allocations"""
# Get all receipts for this resource
receipts = self.db.query(PoolReceipt).filter(
PoolReceipt.pool_resource_id == pool_resource_id
).all()
# Get all allocations for this resource
allocations = self.db.query(PoolAllocation).filter(
PoolAllocation.pool_resource_id == pool_resource_id
).all()
# Calculate total receipt quantity
total_receipts = sum(r.quantity for r in receipts)
# Calculate total allocation quantity
total_allocations = sum(a.quantity for a in allocations)
# Return balance
return total_receipts - total_allocations
def can_allocate(self, pool_resource_id: int, quantity: int) -> bool:
"""Check if allocation of specified quantity is possible"""
current_balance = self.get_current_balance(pool_resource_id)
return quantity <= current_balance
def allocate_resource(self, pool_resource_id: int, quantity: int,
description: Optional[str] = None) -> bool:
"""Allocate resource to a pool"""
# Check if allocation is possible
if not self.can_allocate(pool_resource_id, quantity):
return False
# Create allocation record
allocation = PoolAllocation(
pool_resource_id=pool_resource_id,
quantity=quantity,
description=description
)
self.db.add(allocation)
self.db.commit()
self.db.refresh(allocation)
return True
+456
View File
@@ -0,0 +1,456 @@
"""
Procurement Flow Service v1
Service for receiving resources from procurement (Invoice/Purchase).
Implements comprehensive validation checks before creating Resource.
Key validations:
- Invoice/Purchase provenance chain
- Module-level ordered vs received checks
- Specification-level fulfillment checks
- Transactional atomicity
"""
from typing import Optional
from decimal import Decimal
from sqlalchemy.orm import Session
from sqlalchemy import select, func, and_
from app.models import (
Resource, Project, Module, Invoice, Purchase, PurchaseItem,
PurchaseSpecification, Specification, SpecificationItem
)
from app.services.procurement_flow_service_exceptions import (
ProcurementFlowError,
InvoiceNotFoundError,
PurchaseNotFoundError,
SpecificationNotFoundError,
ModuleNotFoundError,
ProjectNotFoundError,
ProjectMismatchError,
SpecificationNotLinkedToPurchaseError,
ModuleNotInPurchaseError,
OrderedQuantityExceededError,
SpecificationItemNotFoundError,
SpecificationQuantityExceededError,
InvalidQuantityError,
IntegrityError
)
class ProcurementFlowService:
"""
Service для приема ресурса (Resource) из закупки.
Все проверки выполняются атомарно в рамках одной транзакции.
"""
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:
"""
Receive resource from procurement.
Atomic operation that validates and creates Resource.
Validations:
1. Invoice exists
2. Invoice belongs to Purchase
3. Purchase belongs to same Project
4. Module exists
5. quantity > 0
6. Module present in PurchaseItem
7. ordered vs received by Module
8. If Specification provided:
- exists
- belongs to same Project
- linked to Purchase via PurchaseSpecification
- SpecificationItem exists for Module
- received_for_spec + new_quantity <= SpecificationItem.quantity
Args:
project_id: ID of the Project
module_id: ID of the Module
quantity: Quantity to receive (must be > 0)
invoice_id: ID of the Invoice
specification_id: Optional ID of Specification
Returns:
Created Resource object
Raises:
InvoiceNotFoundError: Invoice не существует
PurchaseNotFoundError: Purchase не существует
ProjectNotFoundError: Project не существует
SpecificationNotFoundError: Specification не существует
ModuleNotFoundError: Module не существует
ProjectMismatchError: Purchase/Specification другого Project
SpecificationNotLinkedToPurchaseError: Specification не связана с Purchase
ModuleNotInPurchaseError: Module отсутствует в PurchaseItem
OrderedQuantityExceededError: Превышено ordered quantity
SpecificationItemNotFoundError: SpecificationItem отсутствует
SpecificationQuantityExceededError: Превышено quantity Specification
InvalidQuantityError: quantity ≤ 0
IntegrityError: Ошибка БД (транзакция откатана)
"""
# 1. Validate quantity first
if not self._validate_quantity(quantity):
raise InvalidQuantityError("Quantity must be greater than 0")
# 2. 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")
# 3. 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")
# 4. 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")
# 5. Get Purchase from Invoice
purchase = self.db.query(Purchase).filter(
Purchase.id == invoice.purchase_id
).first()
if not purchase:
raise PurchaseNotFoundError(
f"Purchase not found for Invoice {invoice_id}"
)
# 6. Verify Purchase belongs to same Project
if purchase.project_id != project_id:
raise ProjectMismatchError(
f"Purchase {purchase.id} belongs to Project {purchase.project_id}, "
f"not {project_id}"
)
# 7. Check Module in PurchaseItem
purchase_item = self._get_purchase_item(
purchase_id=purchase.id,
module_id=module_id
)
if not purchase_item:
raise ModuleNotInPurchaseError(
f"Module {module_id} not found in PurchaseItem for Purchase {purchase.id}"
)
# 8. Check ordered vs received by Module
self._check_ordered_vs_received(
purchase_id=purchase.id,
module_id=module_id,
new_quantity=quantity
)
# 9. Check Specification if provided
if specification_id is not None:
self._check_specification_provenance(
project_id=project_id,
specification_id=specification_id,
purchase_id=purchase.id
)
# 10. Check SpecificationItem exists and quantity
self._check_specification_fulfillment(
specification_id=specification_id,
module_id=module_id,
new_quantity=quantity
)
# 11. Create Resource (within transaction)
try:
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,
description=f"Received from Purchase {purchase.purchase_number}"
)
self.db.add(resource)
self.db.flush()
self.db.commit()
self.db.refresh(resource)
return resource
except IntegrityError as e:
self.db.rollback()
raise IntegrityError(f"Database integrity error: {e}")
def _validate_quantity(self, quantity: int | Decimal) -> bool:
"""Validate quantity > 0."""
if isinstance(quantity, Decimal):
return quantity > 0
return quantity > 0
def _get_purchase_item(self, purchase_id: int, module_id: int) -> Optional[PurchaseItem]:
"""
Get PurchaseItem for specific Purchase and Module.
Args:
purchase_id: Purchase ID
module_id: Module ID
Returns:
PurchaseItem or None
"""
return self.db.query(PurchaseItem).filter(
PurchaseItem.purchase_id == purchase_id,
PurchaseItem.module_id == module_id
).first()
def _check_ordered_vs_received(
self,
purchase_id: int,
module_id: int,
new_quantity: int | Decimal
) -> None:
"""
Check that received + new_quantity <= ordered for Module.
Args:
purchase_id: Purchase ID
module_id: Module ID
new_quantity: Quantity to receive
Raises:
OrderedQuantityExceededError: Превышено ordered quantity
"""
# Get PurchaseItem.quantity (ordered)
purchase_item = self._get_purchase_item(purchase_id, module_id)
if not purchase_item:
# Should not happen (checked before), but safe fallback
raise ModuleNotInPurchaseError(
f"Module {module_id} not found in Purchase {purchase_id}"
)
ordered = purchase_item.quantity
# Sum received for this Module from this Purchase
# Resource → Invoice → Purchase
received = self.db.query(
func.sum(Resource.quantity)
).join(
Invoice, Resource.invoice_id == Invoice.id
).filter(
Invoice.purchase_id == purchase_id,
Resource.module_id == module_id
).scalar() or 0
if received + new_quantity > ordered:
raise OrderedQuantityExceededError(
f"Cannot receive {new_quantity}: would exceed ordered quantity "
f"({ordered}). Already received: {received}."
)
def _check_specification_provenance(
self,
project_id: int,
specification_id: int,
purchase_id: int
) -> Specification:
"""
Check Specification provenance.
Validates:
- Specification exists
- Belongs to same Project
- Linked to Purchase via PurchaseSpecification
Args:
project_id: Project ID
specification_id: Specification ID
purchase_id: Purchase ID
Raises:
SpecificationNotFoundError: Specification не существует
ProjectMismatchError: Specification другого Project
SpecificationNotLinkedToPurchaseError: Не связана с Purchase
"""
# Check Specification exists
specification = self.db.query(Specification).filter(
Specification.id == specification_id
).first()
if not specification:
raise SpecificationNotFoundError(
f"Specification {specification_id} not found"
)
# Check Project match
if specification.project_id != project_id:
raise ProjectMismatchError(
f"Specification {specification_id} belongs to Project "
f"{specification.project_id}, not {project_id}"
)
# Check Specification linked to Purchase via PurchaseSpecification
linked = self.db.query(PurchaseSpecification).filter(
PurchaseSpecification.purchase_id == purchase_id,
PurchaseSpecification.specification_id == specification_id
).first()
if not linked:
raise SpecificationNotLinkedToPurchaseError(
f"Specification {specification_id} not linked to Purchase {purchase_id} "
f"via PurchaseSpecification"
)
return specification
def _check_specification_fulfillment(
self,
specification_id: int,
module_id: int,
new_quantity: int | Decimal
) -> None:
"""
Check SpecificationItem fulfillment for Module.
Validates:
- SpecificationItem exists for Module
- received_for_spec + new_quantity <= SpecificationItem.quantity
Args:
specification_id: Specification ID
module_id: Module ID
new_quantity: Quantity to receive
Raises:
SpecificationItemNotFoundError: SpecificationItem отсутствует
SpecificationQuantityExceededError: Превышено quantity SpecificationItem
"""
# Check SpecificationItem exists for Module
spec_item = self.db.query(SpecificationItem).filter(
SpecificationItem.specification_id == specification_id,
SpecificationItem.module_id == module_id
).first()
if not spec_item:
raise SpecificationItemNotFoundError(
f"SpecificationItem for Module {module_id} not found in Specification {specification_id}"
)
required = spec_item.quantity
# Sum received for this Specification and Module
received_for_spec = self.db.query(
func.sum(Resource.quantity)
).filter(
Resource.specification_id == specification_id,
Resource.module_id == module_id
).scalar() or 0
if received_for_spec + new_quantity > required:
raise SpecificationQuantityExceededError(
f"Cannot receive {new_quantity}: would exceed SpecificationItem quantity "
f"({required}) for Module {module_id}. Already received: {received_for_spec}."
)
def validate_provenance_chain(self, invoice_id: int) -> dict:
"""
Validate provenance chain for Invoice (read-only).
Args:
invoice_id: Invoice ID
Returns:
Dictionary with chain data
Raises:
InvoiceNotFoundError: Invoice не существует
PurchaseNotFoundError: Purchase не существует
ProjectMismatchError: Mismatch
"""
invoice = self.db.query(Invoice).filter(
Invoice.id == invoice_id
).first()
if not invoice:
raise InvoiceNotFoundError(f"Invoice {invoice_id} not found")
purchase = self.db.query(Purchase).filter(
Purchase.id == invoice.purchase_id
).first()
if not purchase:
raise PurchaseNotFoundError(
f"Purchase {invoice.purchase_id} not found"
)
return {
'invoice': {
'id': invoice.id,
'invoice_number': invoice.invoice_number,
'purchase_id': invoice.purchase_id,
},
'purchase': {
'id': purchase.id,
'purchase_number': purchase.purchase_number,
'project_id': purchase.project_id,
}
}
def get_ordered_quantity(self, purchase_id: int, module_id: int) -> int:
"""
Get ordered quantity for Module in Purchase.
Args:
purchase_id: Purchase ID
module_id: Module ID
Returns:
Ordered quantity (0 if not found)
"""
purchase_item = self._get_purchase_item(purchase_id, module_id)
return purchase_item.quantity if purchase_item else 0
def get_received_quantity(self, purchase_id: int, module_id: int) -> int:
"""
Get received quantity for Module from Purchase.
Args:
purchase_id: Purchase ID
module_id: Module ID
Returns:
Received quantity
"""
received = self.db.query(
func.sum(Resource.quantity)
).join(
Invoice, Resource.invoice_id == Invoice.id
).filter(
Invoice.purchase_id == purchase_id,
Resource.module_id == module_id
).scalar() or 0
return received
@@ -0,0 +1,73 @@
"""
Procurement Flow Service Exceptions
"""
class ProcurementFlowError(Exception):
"""Base exception for procurement flow errors"""
pass
class InvoiceNotFoundError(ProcurementFlowError):
"""Invoice не существует"""
pass
class PurchaseNotFoundError(ProcurementFlowError):
"""Purchase не существует"""
pass
class SpecificationNotFoundError(ProcurementFlowError):
"""Specification не существует"""
pass
class ModuleNotFoundError(ProcurementFlowError):
"""Module не существует"""
pass
class ProjectNotFoundError(ProcurementFlowError):
"""Project не существует"""
pass
class ProjectMismatchError(ProcurementFlowError):
"""Purchase/Specification относится к другому Project"""
pass
class SpecificationNotLinkedToPurchaseError(ProcurementFlowError):
"""Specification не связана с Purchase через PurchaseSpecification"""
pass
class ModuleNotInPurchaseError(ProcurementFlowError):
"""Module отсутствует в PurchaseItem закупки"""
pass
class OrderedQuantityExceededError(ProcurementFlowError):
"""Превышено ordered quantity для Module"""
pass
class SpecificationItemNotFoundError(ProcurementFlowError):
"""SpecificationItem отсутствует для Module в Specification"""
pass
class SpecificationQuantityExceededError(ProcurementFlowError):
"""Превышено quantity SpecificationItem (over-fulfillment)"""
pass
class InvalidQuantityError(ProcurementFlowError):
"""quantity ≤ 0"""
pass
class IntegrityError(ProcurementFlowError):
"""Database integrity violation (transaction rolled back)"""
pass
@@ -0,0 +1,392 @@
"""
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
+311
View File
@@ -0,0 +1,311 @@
"""
Service for Resource Allocation operations.
Handles allocation of resources from project pool to Systems/Guardians.
Implements all business rules from 003-business-rules-design-v1.md.
"""
from sqlalchemy.orm import Session
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from app.models import (
Resource,
ResourceAllocation,
SystemModule,
System,
Guardian,
Module,
Project
)
from app.services.exceptions import ResourceNotFoundError, SystemNotFoundError, AllocationError, ValidationError, GuardianNotFoundError
class ResourceAllocationError(Exception):
"""Base exception for resource allocation errors"""
pass
class InsufficientBalanceError(ResourceAllocationError):
"""Not enough remaining balance in resource"""
pass
class CoreInCommonError(ResourceAllocationError):
"""Cannot allocate Core to Common part"""
pass
class InvalidGuardianError(ResourceAllocationError):
"""Guardian doesn't belong to specified System"""
pass
class ProjectMismatchError(ResourceAllocationError):
"""Resource and System belong to different Projects"""
pass
class CoreAlreadyExistsError(ResourceAllocationError):
"""Cannot create second Core for same Guardian"""
pass
class ResourceAllocationService:
"""Service for resource allocation operations"""
def __init__(self, db: Session):
self.db = db
def allocate_resource(
self,
resource_id: int,
system_id: int,
quantity: int,
guardian_id: int | None = None,
module_name: str | None = None,
description: str | None = None
) -> ResourceAllocation:
"""
Allocate resource to System/Guardian.
Atomic operation that:
1. Validates all conditions
2. Creates ResourceAllocation
3. Updates/creates SystemModule
4. Commits all changes
Args:
resource_id: ID of Resource to allocate from
system_id: ID of System to allocate to
quantity: Amount to allocate
guardian_id: Optional Guardian ID (NULL for Common part)
module_name: Optional module name (used for Core validation)
description: Optional description
Returns:
Created ResourceAllocation
Raises:
ResourceNotFoundError: If Resource doesn't exist
SystemNotFoundError: If System doesn't exist
InsufficientBalanceError: Not enough remaining balance
CoreInCommonError: Cannot allocate Core to Common
InvalidGuardianError: Guardian doesn't belong to System
ProjectMismatchError: Resource and System different Projects
ValidationError: If quantity <= 0
IntegrityError: If Core already exists for Guardian
"""
# Validate quantity > 0
if quantity <= 0:
raise ValidationError("Quantity must be greater than 0")
# Retry loop for concurrent allocation protection
max_retries = 3
for attempt in range(max_retries):
try:
return self._allocate_atomic(
resource_id=resource_id,
system_id=system_id,
quantity=quantity,
guardian_id=guardian_id,
module_name=module_name,
description=description
)
except IntegrityError as e:
# Core already exists for Guardian
if "Core already exists" in str(e):
raise CoreAlreadyExistsError("Cannot create second Core for same Guardian")
# Retry on potential race condition
if attempt < max_retries - 1:
self.db.rollback()
continue
raise
except IntegrityError:
# Other integrity errors - don't retry
raise
# Should never reach here, but just in case
self.db.rollback()
raise ResourceAllocationError("Failed to allocate after multiple attempts")
def _allocate_atomic(
self,
resource_id: int,
system_id: int,
quantity: int,
guardian_id: int | None,
module_name: str | None,
description: str | None
) -> ResourceAllocation:
"""
Core allocation logic within transaction boundary.
All checks and updates happen in one transaction.
"""
# 1. Validate Resource exists
resource = self.db.query(Resource).filter(
Resource.id == resource_id
).first()
if not resource:
raise ResourceNotFoundError(f"Resource {resource_id} not found")
# 2. Validate System exists
system = self.db.query(System).filter(
System.id == system_id
).first()
if not system:
raise SystemNotFoundError(f"System {system_id} not found")
# 3. Check Project match
if resource.project_id != system.project_id:
raise ProjectMismatchError(
f"Resource belongs to Project {resource.project_id}, "
f"System belongs to Project {system.project_id}"
)
# 4. Check Guardian if specified
if guardian_id is not None:
guardian = self.db.query(Guardian).filter(
Guardian.id == guardian_id
).first()
if not guardian:
raise GuardianNotFoundError(f"Guardian {guardian_id} not found")
if guardian.system_id != system_id:
raise InvalidGuardianError(
f"Guardian {guardian_id} belongs to System {guardian.system_id}, "
f"not to System {system_id}"
)
# 5. Check Core in Common restriction
# If guardian is specified and module is Core, ensure we're not creating duplicate Core
if module_name and module_name.lower() == 'core':
existing_core = self.db.query(SystemModule).filter(
SystemModule.guardian_id == guardian_id,
SystemModule.module_id == self._get_core_module_id(),
).first()
if existing_core:
raise CoreAlreadyExistsError(
f"Guardian {guardian_id} already has Core Module"
)
# 6. Check remaining balance
remaining = self._calculate_remaining(resource_id)
if quantity > remaining:
raise InsufficientBalanceError(
f"Cannot allocate {quantity}, only {remaining} remaining in Resource {resource_id}"
)
# 7. Check Core in Common (if guardian_id is None and module is Core)
if guardian_id is None and module_name and module_name.lower() == 'core':
raise CoreInCommonError("Cannot allocate Core to Common part")
# 8. Create ResourceAllocation
allocation = ResourceAllocation(
resource_id=resource_id,
system_id=system_id,
guardian_id=guardian_id,
quantity=quantity,
description=description
)
self.db.add(allocation)
# 9. Update/Create SystemModule
self._update_system_module(
system_id=system_id,
guardian_id=guardian_id,
module_name=module_name,
quantity=quantity
)
# 10. Commit transaction
self.db.commit()
self.db.refresh(allocation)
return allocation
def _calculate_remaining(self, resource_id: int) -> int:
"""Calculate remaining balance for Resource"""
# Sum all existing allocations
allocated = self.db.query(func.sum(ResourceAllocation.quantity)).filter(
ResourceAllocation.resource_id == resource_id
).scalar() or 0
# Get resource quantity
resource = self.db.query(Resource).filter(
Resource.id == resource_id
).first()
return resource.quantity - allocated
def _get_core_module_id(self) -> int:
"""Get ID of Core module"""
core = self.db.query(Module).filter(
Module.name.ilike('core')
).first()
if core:
return core.id
# If Core doesn't exist, create it (shouldn't happen in normal operation)
core = Module(name="Core", description="Core module - required for Guardian")
self.db.add(core)
self.db.commit()
self.db.refresh(core)
return core.id
def _update_system_module(
self,
system_id: int,
guardian_id: int | None,
module_name: str | None,
quantity: int
) -> SystemModule:
"""
Update or create SystemModule for the allocation.
Handles both Common part (guardian_id=None) and Guardian-specific allocations.
"""
# Find existing SystemModule
existing = self.db.query(SystemModule).filter(
SystemModule.system_id == system_id,
SystemModule.guardian_id == guardian_id
).first()
if existing:
# Update existing
existing.quantity += quantity
else:
# Create new - need module_id
module_id = self._get_module_id_by_name(module_name)
if module_id is None:
# If module_name not provided, we can't create SystemModule
raise ValidationError(f"Module {module_name} not found or not provided")
existing = SystemModule(
system_id=system_id,
guardian_id=guardian_id,
module_id=module_id,
quantity=quantity
)
self.db.add(existing)
return existing
def _get_module_id_by_name(self, name: str | None) -> int | None:
"""Get module ID by name"""
if not name:
return None
module = self.db.query(Module).filter(
Module.name.ilike(name)
).first()
return module.id if module else None
+218
View File
@@ -0,0 +1,218 @@
"""
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
@@ -0,0 +1,45 @@
"""
Resource Receipt Service - exceptions
Custom exceptions for resource receipt operations.
"""
class ResourceReceiptError(Exception):
"""Base exception for resource receipt operations."""
pass
class ProjectNotFoundError(ResourceReceiptError):
"""Project не существует."""
pass
class ModuleNotFoundError(ResourceReceiptError):
"""Module не существует."""
pass
class InvoiceNotFoundError(ResourceReceiptError):
"""Invoice не существует."""
pass
class SpecificationNotFoundError(ResourceReceiptError):
"""Specification не существует."""
pass
class SpecificationProjectMismatchError(ResourceReceiptError):
"""Specification принадлежит другому Project."""
pass
class InvoiceProjectMismatchError(ResourceReceiptError):
"""Invoice принадлежит другому Project."""
pass
class ValidationError(ResourceReceiptError):
"""Ошибка валидации (quantity ≤ 0 и т.п.)."""
pass