457 lines
15 KiB
Python
457 lines
15 KiB
Python
"""
|
||
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
|