Files
specs/app/services/pool_service.py
T
2026-10-10 11:30:27 +00:00

55 lines
2.0 KiB
Python
Executable File

"""
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