Initial commit
This commit is contained in:
Executable
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
# Database configuration
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./specs.db")
|
||||
|
||||
# Create engine
|
||||
engine = create_engine(DATABASE_URL, echo=True)
|
||||
|
||||
# Create session
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Base class for models
|
||||
Base = declarative_base()
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
Executable
+298
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
SQLAlchemy Models for Specs Accounting System V1
|
||||
|
||||
Consistent domain model according to 001-domain-model-v1.md specification.
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, Numeric, UniqueConstraint, CheckConstraint, ForeignKeyConstraint
|
||||
from sqlalchemy.orm import relationship, validates
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Customer(Base, TimestampMixin):
|
||||
"""Заказчик проекта."""
|
||||
__tablename__ = 'customers'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
projects = relationship("Project", secondary="project_customers", back_populates="customers")
|
||||
|
||||
|
||||
class LegalEntity(Base, TimestampMixin):
|
||||
"""Юридическое лицо проекта."""
|
||||
__tablename__ = 'legal_entities'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
inn = Column(String(50))
|
||||
kpp = Column(String(50))
|
||||
address = Column(Text)
|
||||
customer_id = Column(Integer, ForeignKey('customers.id', ondelete='RESTRICT'), nullable=False)
|
||||
|
||||
|
||||
class Project(Base, TimestampMixin):
|
||||
"""Корневой объект учета."""
|
||||
__tablename__ = 'projects'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
customers = relationship("Customer", secondary="project_customers", back_populates="projects")
|
||||
|
||||
|
||||
class ProjectCustomer(Base):
|
||||
"""Связующая таблица Project ↔ Customer."""
|
||||
__tablename__ = 'project_customers'
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), primary_key=True)
|
||||
customer_id = Column(Integer, ForeignKey('customers.id', ondelete='CASCADE'), primary_key=True)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class ProjectLegalEntity(Base):
|
||||
"""Связующая таблица Project ↔ LegalEntity."""
|
||||
__tablename__ = 'project_legal_entities'
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), primary_key=True)
|
||||
legal_entity_id = Column(Integer, ForeignKey('legal_entities.id', ondelete='CASCADE'), primary_key=True)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Module(Base, TimestampMixin):
|
||||
"""Вид лицензируемого модуля ПО."""
|
||||
__tablename__ = 'modules'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(100), nullable=False, unique=True)
|
||||
description = Column(Text)
|
||||
software_id = Column(Integer, ForeignKey('softwares.id', ondelete='SET NULL'), nullable=True)
|
||||
|
||||
|
||||
class System(Base, TimestampMixin):
|
||||
"""Основной объект лицензирования."""
|
||||
__tablename__ = 'systems'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), nullable=False)
|
||||
customer_id = Column(Integer, ForeignKey('customers.id', ondelete='RESTRICT'), nullable=False)
|
||||
project = relationship("Project")
|
||||
customer = relationship("Customer")
|
||||
guardians = relationship("Guardian", back_populates="system")
|
||||
|
||||
|
||||
class Guardian(Base, TimestampMixin):
|
||||
"""Физический ключ защиты ПО (Hardware key)."""
|
||||
__tablename__ = 'guardians'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
serial_number = Column(String(100))
|
||||
location = Column(String(255))
|
||||
system_id = Column(Integer, ForeignKey('systems.id', ondelete='CASCADE'), nullable=False)
|
||||
system = relationship("System", back_populates="guardians")
|
||||
__table_args__ = (
|
||||
UniqueConstraint('system_id', 'serial_number', name='uq_guardian_system_serial'),
|
||||
)
|
||||
|
||||
|
||||
class SystemModule(Base, TimestampMixin):
|
||||
"""Использование модуля в системе через Guardian или Common part."""
|
||||
__tablename__ = 'system_modules'
|
||||
id = Column(Integer, primary_key=True)
|
||||
system_id = Column(Integer, ForeignKey('systems.id', ondelete='CASCADE'), nullable=False)
|
||||
guardian_id = Column(Integer, ForeignKey('guardians.id', ondelete='CASCADE'), nullable=True)
|
||||
module_id = Column(Integer, ForeignKey('modules.id', ondelete='CASCADE'), nullable=False)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
__table_args__ = (
|
||||
UniqueConstraint('system_id', 'guardian_id', 'module_id', name='uq_system_module_guardian'),
|
||||
CheckConstraint('quantity > 0', name='check_module_quantity_positive'),
|
||||
)
|
||||
|
||||
|
||||
class Software(Base, TimestampMixin):
|
||||
"""Программный продукт."""
|
||||
__tablename__ = 'softwares'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Resource(Base, TimestampMixin):
|
||||
"""Приобретенная партия Module."""
|
||||
__tablename__ = 'resources'
|
||||
id = Column(Integer, primary_key=True)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), nullable=False)
|
||||
module_id = Column(Integer, ForeignKey('modules.id', ondelete='RESTRICT'), nullable=False)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
invoice_number = Column(String(100))
|
||||
invoice_date = Column(DateTime)
|
||||
specification_number = Column(String(100))
|
||||
specification_id = Column(Integer, ForeignKey('specifications.id', ondelete='SET NULL'), nullable=True)
|
||||
invoice_id = Column(Integer, ForeignKey('invoices.id', ondelete='RESTRICT'), nullable=False)
|
||||
description = Column(Text)
|
||||
__table_args__ = (
|
||||
CheckConstraint('quantity > 0', name='check_resource_quantity_positive'),
|
||||
)
|
||||
|
||||
|
||||
class ResourceAllocation(Base, TimestampMixin):
|
||||
"""Распределение ресурса из общего пула в System/Guardian."""
|
||||
__tablename__ = 'resource_allocations'
|
||||
id = Column(Integer, primary_key=True)
|
||||
resource_id = Column(Integer, ForeignKey('resources.id', ondelete='CASCADE'), nullable=False)
|
||||
system_id = Column(Integer, ForeignKey('systems.id', ondelete='CASCADE'), nullable=False)
|
||||
guardian_id = Column(Integer, ForeignKey('guardians.id', ondelete='SET NULL'), nullable=True)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
allocation_date = Column(DateTime, default=func.now())
|
||||
description = Column(Text)
|
||||
__table_args__ = (
|
||||
CheckConstraint('quantity > 0', name='check_allocation_quantity_positive'),
|
||||
)
|
||||
|
||||
|
||||
class Contract(Base, TimestampMixin):
|
||||
"""Контракт проекта."""
|
||||
__tablename__ = 'contracts'
|
||||
id = Column(Integer, primary_key=True)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), nullable=False)
|
||||
contract_number = Column(String(100), nullable=False)
|
||||
contract_date = Column(DateTime)
|
||||
start_date = Column(DateTime)
|
||||
end_date = Column(DateTime)
|
||||
description = Column(Text)
|
||||
__table_args__ = (
|
||||
UniqueConstraint('project_id', 'contract_number', name='uq_contract_project_number'),
|
||||
)
|
||||
|
||||
|
||||
class ContractAddendum(Base, TimestampMixin):
|
||||
"""Дополнение к контракту."""
|
||||
__tablename__ = 'contract_addendums'
|
||||
id = Column(Integer, primary_key=True)
|
||||
contract_id = Column(Integer, ForeignKey('contracts.id', ondelete='CASCADE'), nullable=False)
|
||||
addendum_number = Column(String(100), nullable=False)
|
||||
addendum_date = Column(DateTime)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Specification(Base, TimestampMixin):
|
||||
"""Спецификация (потребность заказчика)."""
|
||||
__tablename__ = 'specifications'
|
||||
id = Column(Integer, primary_key=True)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), nullable=False)
|
||||
contract_id = Column(Integer, ForeignKey('contracts.id', ondelete='CASCADE'), nullable=False)
|
||||
specification_number = Column(String(100), nullable=False)
|
||||
specification_date = Column(DateTime)
|
||||
description = Column(Text)
|
||||
purchases = relationship("Purchase", secondary="purchase_specifications", back_populates="specifications")
|
||||
__table_args__ = (
|
||||
UniqueConstraint('contract_id', 'specification_number', name='uq_specification_contract_number'),
|
||||
)
|
||||
|
||||
|
||||
class SpecificationItem(Base, TimestampMixin):
|
||||
"""Позиция спецификации."""
|
||||
__tablename__ = 'specification_items'
|
||||
id = Column(Integer, primary_key=True)
|
||||
specification_id = Column(Integer, ForeignKey('specifications.id', ondelete='CASCADE'), nullable=False)
|
||||
module_id = Column(Integer, ForeignKey('modules.id', ondelete='RESTRICT'), nullable=False)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Vendor(Base, TimestampMixin):
|
||||
"""Поставщик."""
|
||||
__tablename__ = 'vendors'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
contact_person = Column(String(255))
|
||||
phone = Column(String(50))
|
||||
email = Column(String(255))
|
||||
address = Column(Text)
|
||||
|
||||
|
||||
class Purchase(Base, TimestampMixin):
|
||||
"""Закупка у поставщика."""
|
||||
__tablename__ = 'purchases'
|
||||
id = Column(Integer, primary_key=True)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'), nullable=False)
|
||||
vendor_id = Column(Integer, ForeignKey('vendors.id', ondelete='RESTRICT'), nullable=False)
|
||||
purchase_number = Column(String(100), nullable=False)
|
||||
purchase_date = Column(DateTime)
|
||||
description = Column(Text)
|
||||
specifications = relationship("Specification", secondary="purchase_specifications", back_populates="purchases")
|
||||
|
||||
|
||||
class PurchaseSpecification(Base):
|
||||
"""Связующая таблица Purchase ↔ Specification (M:N)."""
|
||||
__tablename__ = 'purchase_specifications'
|
||||
purchase_id = Column(Integer, ForeignKey('purchases.id', ondelete='CASCADE'), primary_key=True)
|
||||
specification_id = Column(Integer, ForeignKey('specifications.id', ondelete='CASCADE'), primary_key=True)
|
||||
|
||||
|
||||
class PurchaseItem(Base, TimestampMixin):
|
||||
"""Позиция закупки."""
|
||||
__tablename__ = 'purchase_items'
|
||||
id = Column(Integer, primary_key=True)
|
||||
purchase_id = Column(Integer, ForeignKey('purchases.id', ondelete='CASCADE'), nullable=False)
|
||||
module_id = Column(Integer, ForeignKey('modules.id', ondelete='RESTRICT'), nullable=False)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
unit_price = Column(Numeric(12, 2))
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Invoice(Base, TimestampMixin):
|
||||
"""Счет поставщика."""
|
||||
__tablename__ = 'invoices'
|
||||
id = Column(Integer, primary_key=True)
|
||||
purchase_id = Column(Integer, ForeignKey('purchases.id', ondelete='CASCADE'), nullable=False)
|
||||
vendor_id = Column(Integer, ForeignKey('vendors.id', ondelete='RESTRICT'), nullable=False)
|
||||
invoice_number = Column(String(100), nullable=False)
|
||||
invoice_date = Column(DateTime)
|
||||
amount = Column(Numeric(12, 2))
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Shipment(Base, TimestampMixin):
|
||||
"""Фактическая поставка/отгрузка."""
|
||||
__tablename__ = 'shipments'
|
||||
id = Column(Integer, primary_key=True)
|
||||
purchase_id = Column(Integer, ForeignKey('purchases.id', ondelete='CASCADE'), nullable=False)
|
||||
shipment_number = Column(String(100))
|
||||
shipment_date = Column(DateTime)
|
||||
tracking_number = Column(String(100))
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class Document(Base, TimestampMixin):
|
||||
"""Логический документ."""
|
||||
__tablename__ = 'documents'
|
||||
id = Column(Integer, primary_key=True)
|
||||
project_id = Column(Integer, ForeignKey('projects.id', ondelete='SET NULL'), nullable=True)
|
||||
document_type = Column(String(50))
|
||||
document_number = Column(String(100), nullable=False)
|
||||
document_date = Column(DateTime)
|
||||
title = Column(String(255))
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class DocumentFile(Base, TimestampMixin):
|
||||
"""Файл документа."""
|
||||
__tablename__ = 'document_files'
|
||||
id = Column(Integer, primary_key=True)
|
||||
document_id = Column(Integer, ForeignKey('documents.id', ondelete='CASCADE'), nullable=False)
|
||||
file_path = Column(String(500), nullable=False)
|
||||
file_name = Column(String(255), nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
|
||||
class DocumentDispatch(Base, TimestampMixin):
|
||||
"""Факт отправки документа."""
|
||||
__tablename__ = 'document_dispatches'
|
||||
id = Column(Integer, primary_key=True)
|
||||
document_id = Column(Integer, ForeignKey('documents.id', ondelete='CASCADE'), nullable=False)
|
||||
dispatch_date = Column(DateTime)
|
||||
recipient = Column(String(255))
|
||||
package = Column(String(255))
|
||||
channel = Column(String(50))
|
||||
status = Column(String(50))
|
||||
description = Column(Text)
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
from sqlalchemy import Column, DateTime, func
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
class TimestampMixin:
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
Empty __init__.py for repositories package
|
||||
"""
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
Repository for PoolResource operations
|
||||
"""
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models import PoolResource, PoolReceipt, PoolAllocation
|
||||
|
||||
class PoolResourceRepository:
|
||||
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
|
||||
Executable
Binary file not shown.
@@ -0,0 +1,183 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import Contract, ContractAddendum, Specification, SpecificationItem
|
||||
from app.schemas import ContractCreate, ContractUpdate, ContractAddendumCreate, ContractAddendumUpdate, SpecificationCreate, SpecificationUpdate, SpecificationItemCreate, SpecificationItemUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Contract routes
|
||||
@router.get("/contracts")
|
||||
async def get_contracts(db: Session = Depends(get_db)):
|
||||
contracts = db.query(Contract).all()
|
||||
return contracts
|
||||
|
||||
@router.get("/contracts/{contract_id}")
|
||||
async def get_contract(contract_id: int, db: Session = Depends(get_db)):
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if not contract:
|
||||
raise HTTPException(status_code=404, detail="Contract not found")
|
||||
return contract
|
||||
|
||||
@router.post("/contracts")
|
||||
async def create_contract(contract: ContractCreate, db: Session = Depends(get_db)):
|
||||
db_contract = Contract(**contract.dict())
|
||||
db.add(db_contract)
|
||||
db.commit()
|
||||
db.refresh(db_contract)
|
||||
return db_contract
|
||||
|
||||
@router.put("/contracts/{contract_id}")
|
||||
async def update_contract(contract_id: int, contract: ContractUpdate, db: Session = Depends(get_db)):
|
||||
db_contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if not db_contract:
|
||||
raise HTTPException(status_code=404, detail="Contract not found")
|
||||
|
||||
for key, value in contract.dict(exclude_unset=True).items():
|
||||
setattr(db_contract, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_contract)
|
||||
return db_contract
|
||||
|
||||
@router.delete("/contracts/{contract_id}")
|
||||
async def delete_contract(contract_id: int, db: Session = Depends(get_db)):
|
||||
db_contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if not db_contract:
|
||||
raise HTTPException(status_code=404, detail="Contract not found")
|
||||
|
||||
db.delete(db_contract)
|
||||
db.commit()
|
||||
return {"message": "Contract deleted successfully"}
|
||||
|
||||
# ContractAddendum routes
|
||||
@router.get("/contract_addendums")
|
||||
async def get_contract_addendums(db: Session = Depends(get_db)):
|
||||
addendums = db.query(ContractAddendum).all()
|
||||
return addendums
|
||||
|
||||
@router.get("/contract_addendums/{addendum_id}")
|
||||
async def get_contract_addendum(addendum_id: int, db: Session = Depends(get_db)):
|
||||
addendum = db.query(ContractAddendum).filter(ContractAddendum.id == addendum_id).first()
|
||||
if not addendum:
|
||||
raise HTTPException(status_code=404, detail="Contract addendum not found")
|
||||
return addendum
|
||||
|
||||
@router.post("/contract_addendums")
|
||||
async def create_contract_addendum(addendum: ContractAddendumCreate, db: Session = Depends(get_db)):
|
||||
db_addendum = ContractAddendum(**addendum.dict())
|
||||
db.add(db_addendum)
|
||||
db.commit()
|
||||
db.refresh(db_addendum)
|
||||
return db_addendum
|
||||
|
||||
@router.put("/contract_addendums/{addendum_id}")
|
||||
async def update_contract_addendum(addendum_id: int, addendum: ContractAddendumUpdate, db: Session = Depends(get_db)):
|
||||
db_addendum = db.query(ContractAddendum).filter(ContractAddendum.id == addendum_id).first()
|
||||
if not db_addendum:
|
||||
raise HTTPException(status_code=404, detail="Contract addendum not found")
|
||||
|
||||
for key, value in addendum.dict(exclude_unset=True).items():
|
||||
setattr(db_addendum, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_addendum)
|
||||
return db_addendum
|
||||
|
||||
@router.delete("/contract_addendums/{addendum_id}")
|
||||
async def delete_contract_addendum(addendum_id: int, db: Session = Depends(get_db)):
|
||||
db_addendum = db.query(ContractAddendum).filter(ContractAddendum.id == addendum_id).first()
|
||||
if not db_addendum:
|
||||
raise HTTPException(status_code=404, detail="Contract addendum not found")
|
||||
|
||||
db.delete(db_addendum)
|
||||
db.commit()
|
||||
return {"message": "Contract addendum deleted successfully"}
|
||||
|
||||
# Specification routes
|
||||
@router.get("/specifications")
|
||||
async def get_specifications(db: Session = Depends(get_db)):
|
||||
specifications = db.query(Specification).all()
|
||||
return specifications
|
||||
|
||||
@router.get("/specifications/{specification_id}")
|
||||
async def get_specification(specification_id: int, db: Session = Depends(get_db)):
|
||||
specification = db.query(Specification).filter(Specification.id == specification_id).first()
|
||||
if not specification:
|
||||
raise HTTPException(status_code=404, detail="Specification not found")
|
||||
return specification
|
||||
|
||||
@router.post("/specifications")
|
||||
async def create_specification(specification: SpecificationCreate, db: Session = Depends(get_db)):
|
||||
db_specification = Specification(**specification.dict())
|
||||
db.add(db_specification)
|
||||
db.commit()
|
||||
db.refresh(db_specification)
|
||||
return db_specification
|
||||
|
||||
@router.put("/specifications/{specification_id}")
|
||||
async def update_specification(specification_id: int, specification: SpecificationUpdate, db: Session = Depends(get_db)):
|
||||
db_specification = db.query(Specification).filter(Specification.id == specification_id).first()
|
||||
if not db_specification:
|
||||
raise HTTPException(status_code=404, detail="Specification not found")
|
||||
|
||||
for key, value in specification.dict(exclude_unset=True).items():
|
||||
setattr(db_specification, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_specification)
|
||||
return db_specification
|
||||
|
||||
@router.delete("/specifications/{specification_id}")
|
||||
async def delete_specification(specification_id: int, db: Session = Depends(get_db)):
|
||||
db_specification = db.query(Specification).filter(Specification.id == specification_id).first()
|
||||
if not db_specification:
|
||||
raise HTTPException(status_code=404, detail="Specification not found")
|
||||
|
||||
db.delete(db_specification)
|
||||
db.commit()
|
||||
return {"message": "Specification deleted successfully"}
|
||||
|
||||
# SpecificationItem routes
|
||||
@router.get("/specification_items")
|
||||
async def get_specification_items(db: Session = Depends(get_db)):
|
||||
items = db.query(SpecificationItem).all()
|
||||
return items
|
||||
|
||||
@router.get("/specification_items/{item_id}")
|
||||
async def get_specification_item(item_id: int, db: Session = Depends(get_db)):
|
||||
item = db.query(SpecificationItem).filter(SpecificationItem.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Specification item not found")
|
||||
return item
|
||||
|
||||
@router.post("/specification_items")
|
||||
async def create_specification_item(item: SpecificationItemCreate, db: Session = Depends(get_db)):
|
||||
db_item = SpecificationItem(**item.dict())
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@router.put("/specification_items/{item_id}")
|
||||
async def update_specification_item(item_id: int, item: SpecificationItemUpdate, db: Session = Depends(get_db)):
|
||||
db_item = db.query(SpecificationItem).filter(SpecificationItem.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(status_code=404, detail="Specification item not found")
|
||||
|
||||
for key, value in item.dict(exclude_unset=True).items():
|
||||
setattr(db_item, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@router.delete("/specification_items/{item_id}")
|
||||
async def delete_specification_item(item_id: int, db: Session = Depends(get_db)):
|
||||
db_item = db.query(SpecificationItem).filter(SpecificationItem.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(status_code=404, detail="Specification item not found")
|
||||
|
||||
db.delete(db_item)
|
||||
db.commit()
|
||||
return {"message": "Specification item deleted successfully"}
|
||||
@@ -0,0 +1,139 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import Customer, LegalEntity, Project
|
||||
from app.schemas import CustomerCreate, CustomerUpdate, LegalEntityCreate, LegalEntityUpdate, ProjectCreate, ProjectUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Customer routes
|
||||
@router.get("/customers")
|
||||
async def get_customers(db: Session = Depends(get_db)):
|
||||
customers = db.query(Customer).all()
|
||||
return customers
|
||||
|
||||
@router.get("/customers/{customer_id}")
|
||||
async def get_customer(customer_id: int, db: Session = Depends(get_db)):
|
||||
customer = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not customer:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
return customer
|
||||
|
||||
@router.post("/customers")
|
||||
async def create_customer(customer: CustomerCreate, db: Session = Depends(get_db)):
|
||||
db_customer = Customer(**customer.dict())
|
||||
db.add(db_customer)
|
||||
db.commit()
|
||||
db.refresh(db_customer)
|
||||
return db_customer
|
||||
|
||||
@router.put("/customers/{customer_id}")
|
||||
async def update_customer(customer_id: int, customer: CustomerUpdate, db: Session = Depends(get_db)):
|
||||
db_customer = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not db_customer:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
|
||||
for key, value in customer.dict(exclude_unset=True).items():
|
||||
setattr(db_customer, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_customer)
|
||||
return db_customer
|
||||
|
||||
@router.delete("/customers/{customer_id}")
|
||||
async def delete_customer(customer_id: int, db: Session = Depends(get_db)):
|
||||
db_customer = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not db_customer:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
|
||||
db.delete(db_customer)
|
||||
db.commit()
|
||||
return {"message": "Customer deleted successfully"}
|
||||
|
||||
# Legal Entity routes
|
||||
@router.get("/legal_entities")
|
||||
async def get_legal_entities(db: Session = Depends(get_db)):
|
||||
entities = db.query(LegalEntity).all()
|
||||
return entities
|
||||
|
||||
@router.get("/legal_entities/{entity_id}")
|
||||
async def get_legal_entity(entity_id: int, db: Session = Depends(get_db)):
|
||||
entity = db.query(LegalEntity).filter(LegalEntity.id == entity_id).first()
|
||||
if not entity:
|
||||
raise HTTPException(status_code=404, detail="Legal entity not found")
|
||||
return entity
|
||||
|
||||
@router.post("/legal_entities")
|
||||
async def create_legal_entity(entity: LegalEntityCreate, db: Session = Depends(get_db)):
|
||||
db_entity = LegalEntity(**entity.dict())
|
||||
db.add(db_entity)
|
||||
db.commit()
|
||||
db.refresh(db_entity)
|
||||
return db_entity
|
||||
|
||||
@router.put("/legal_entities/{entity_id}")
|
||||
async def update_legal_entity(entity_id: int, entity: LegalEntityUpdate, db: Session = Depends(get_db)):
|
||||
db_entity = db.query(LegalEntity).filter(LegalEntity.id == entity_id).first()
|
||||
if not db_entity:
|
||||
raise HTTPException(status_code=404, detail="Legal entity not found")
|
||||
|
||||
for key, value in entity.dict(exclude_unset=True).items():
|
||||
setattr(db_entity, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_entity)
|
||||
return db_entity
|
||||
|
||||
@router.delete("/legal_entities/{entity_id}")
|
||||
async def delete_legal_entity(entity_id: int, db: Session = Depends(get_db)):
|
||||
db_entity = db.query(LegalEntity).filter(LegalEntity.id == entity_id).first()
|
||||
if not db_entity:
|
||||
raise HTTPException(status_code=404, detail="Legal entity not found")
|
||||
|
||||
db.delete(db_entity)
|
||||
db.commit()
|
||||
return {"message": "Legal entity deleted successfully"}
|
||||
|
||||
# Project routes
|
||||
@router.get("/projects")
|
||||
async def get_projects(db: Session = Depends(get_db)):
|
||||
projects = db.query(Project).all()
|
||||
return projects
|
||||
|
||||
@router.get("/projects/{project_id}")
|
||||
async def get_project(project_id: int, db: Session = Depends(get_db)):
|
||||
project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return project
|
||||
|
||||
@router.post("/projects")
|
||||
async def create_project(project: ProjectCreate, db: Session = Depends(get_db)):
|
||||
db_project = Project(**project.dict())
|
||||
db.add(db_project)
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
return db_project
|
||||
|
||||
@router.put("/projects/{project_id}")
|
||||
async def update_project(project_id: int, project: ProjectUpdate, db: Session = Depends(get_db)):
|
||||
db_project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not db_project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
for key, value in project.dict(exclude_unset=True).items():
|
||||
setattr(db_project, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
return db_project
|
||||
|
||||
@router.delete("/projects/{project_id}")
|
||||
async def delete_project(project_id: int, db: Session = Depends(get_db)):
|
||||
db_project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not db_project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
db.delete(db_project)
|
||||
db.commit()
|
||||
return {"message": "Project deleted successfully"}
|
||||
@@ -0,0 +1,139 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import Document, DocumentFile, DocumentDispatch
|
||||
from app.schemas import DocumentCreate, DocumentUpdate, DocumentFileCreate, DocumentFileUpdate, DocumentDispatchCreate, DocumentDispatchUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Document routes
|
||||
@router.get("/documents")
|
||||
async def get_documents(db: Session = Depends(get_db)):
|
||||
documents = db.query(Document).all()
|
||||
return documents
|
||||
|
||||
@router.get("/documents/{document_id}")
|
||||
async def get_document(document_id: int, db: Session = Depends(get_db)):
|
||||
document = db.query(Document).filter(Document.id == document_id).first()
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
return document
|
||||
|
||||
@router.post("/documents")
|
||||
async def create_document(document: DocumentCreate, db: Session = Depends(get_db)):
|
||||
db_document = Document(**document.dict())
|
||||
db.add(db_document)
|
||||
db.commit()
|
||||
db.refresh(db_document)
|
||||
return db_document
|
||||
|
||||
@router.put("/documents/{document_id}")
|
||||
async def update_document(document_id: int, document: DocumentUpdate, db: Session = Depends(get_db)):
|
||||
db_document = db.query(Document).filter(Document.id == document_id).first()
|
||||
if not db_document:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
for key, value in document.dict(exclude_unset=True).items():
|
||||
setattr(db_document, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_document)
|
||||
return db_document
|
||||
|
||||
@router.delete("/documents/{document_id}")
|
||||
async def delete_document(document_id: int, db: Session = Depends(get_db)):
|
||||
db_document = db.query(Document).filter(Document.id == document_id).first()
|
||||
if not db_document:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
db.delete(db_document)
|
||||
db.commit()
|
||||
return {"message": "Document deleted successfully"}
|
||||
|
||||
# DocumentFile routes
|
||||
@router.get("/document_files")
|
||||
async def get_document_files(db: Session = Depends(get_db)):
|
||||
files = db.query(DocumentFile).all()
|
||||
return files
|
||||
|
||||
@router.get("/document_files/{file_id}")
|
||||
async def get_document_file(file_id: int, db: Session = Depends(get_db)):
|
||||
file = db.query(DocumentFile).filter(DocumentFile.id == file_id).first()
|
||||
if not file:
|
||||
raise HTTPException(status_code=404, detail="Document file not found")
|
||||
return file
|
||||
|
||||
@router.post("/document_files")
|
||||
async def create_document_file(file: DocumentFileCreate, db: Session = Depends(get_db)):
|
||||
db_file = DocumentFile(**file.dict())
|
||||
db.add(db_file)
|
||||
db.commit()
|
||||
db.refresh(db_file)
|
||||
return db_file
|
||||
|
||||
@router.put("/document_files/{file_id}")
|
||||
async def update_document_file(file_id: int, file: DocumentFileUpdate, db: Session = Depends(get_db)):
|
||||
db_file = db.query(DocumentFile).filter(DocumentFile.id == file_id).first()
|
||||
if not db_file:
|
||||
raise HTTPException(status_code=404, detail="Document file not found")
|
||||
|
||||
for key, value in file.dict(exclude_unset=True).items():
|
||||
setattr(db_file, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_file)
|
||||
return db_file
|
||||
|
||||
@router.delete("/document_files/{file_id}")
|
||||
async def delete_document_file(file_id: int, db: Session = Depends(get_db)):
|
||||
db_file = db.query(DocumentFile).filter(DocumentFile.id == file_id).first()
|
||||
if not db_file:
|
||||
raise HTTPException(status_code=404, detail="Document file not found")
|
||||
|
||||
db.delete(db_file)
|
||||
db.commit()
|
||||
return {"message": "Document file deleted successfully"}
|
||||
|
||||
# DocumentDispatch routes
|
||||
@router.get("/document_dispatches")
|
||||
async def get_document_dispatches(db: Session = Depends(get_db)):
|
||||
dispatches = db.query(DocumentDispatch).all()
|
||||
return dispatches
|
||||
|
||||
@router.get("/document_dispatches/{dispatch_id}")
|
||||
async def get_document_dispatch(dispatch_id: int, db: Session = Depends(get_db)):
|
||||
dispatch = db.query(DocumentDispatch).filter(DocumentDispatch.id == dispatch_id).first()
|
||||
if not dispatch:
|
||||
raise HTTPException(status_code=404, detail="Document dispatch not found")
|
||||
return dispatch
|
||||
|
||||
@router.post("/document_dispatches")
|
||||
async def create_document_dispatch(dispatch: DocumentDispatchCreate, db: Session = Depends(get_db)):
|
||||
db_dispatch = DocumentDispatch(**dispatch.dict())
|
||||
db.add(db_dispatch)
|
||||
db.commit()
|
||||
db.refresh(db_dispatch)
|
||||
return db_dispatch
|
||||
|
||||
@router.put("/document_dispatches/{dispatch_id}")
|
||||
async def update_document_dispatch(dispatch_id: int, dispatch: DocumentDispatchUpdate, db: Session = Depends(get_db)):
|
||||
db_dispatch = db.query(DocumentDispatch).filter(DocumentDispatch.id == dispatch_id).first()
|
||||
if not db_dispatch:
|
||||
raise HTTPException(status_code=404, detail="Document dispatch not found")
|
||||
|
||||
for key, value in dispatch.dict(exclude_unset=True).items():
|
||||
setattr(db_dispatch, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_dispatch)
|
||||
return db_dispatch
|
||||
|
||||
@router.delete("/document_dispatches/{dispatch_id}")
|
||||
async def delete_document_dispatch(dispatch_id: int, db: Session = Depends(get_db)):
|
||||
db_dispatch = db.query(DocumentDispatch).filter(DocumentDispatch.id == dispatch_id).first()
|
||||
if not db_dispatch:
|
||||
raise HTTPException(status_code=404, detail="Document dispatch not found")
|
||||
|
||||
db.delete(db_dispatch)
|
||||
db.commit()
|
||||
return {"message": "Document dispatch deleted successfully"}
|
||||
@@ -0,0 +1,139 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import License, LicenseType, Product
|
||||
from app.schemas import LicenseCreate, LicenseUpdate, LicenseTypeCreate, LicenseTypeUpdate, ProductCreate, ProductUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# License routes
|
||||
@router.get("/licenses")
|
||||
async def get_licenses(db: Session = Depends(get_db)):
|
||||
licenses = db.query(License).all()
|
||||
return licenses
|
||||
|
||||
@router.get("/licenses/{license_id}")
|
||||
async def get_license(license_id: int, db: Session = Depends(get_db)):
|
||||
license = db.query(License).filter(License.id == license_id).first()
|
||||
if not license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
return license
|
||||
|
||||
@router.post("/licenses")
|
||||
async def create_license(license: LicenseCreate, db: Session = Depends(get_db)):
|
||||
db_license = License(**license.dict())
|
||||
db.add(db_license)
|
||||
db.commit()
|
||||
db.refresh(db_license)
|
||||
return db_license
|
||||
|
||||
@router.put("/licenses/{license_id}")
|
||||
async def update_license(license_id: int, license: LicenseUpdate, db: Session = Depends(get_db)):
|
||||
db_license = db.query(License).filter(License.id == license_id).first()
|
||||
if not db_license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
|
||||
for key, value in license.dict(exclude_unset=True).items():
|
||||
setattr(db_license, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_license)
|
||||
return db_license
|
||||
|
||||
@router.delete("/licenses/{license_id}")
|
||||
async def delete_license(license_id: int, db: Session = Depends(get_db)):
|
||||
db_license = db.query(License).filter(License.id == license_id).first()
|
||||
if not db_license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
|
||||
db.delete(db_license)
|
||||
db.commit()
|
||||
return {"message": "License deleted successfully"}
|
||||
|
||||
# LicenseType routes
|
||||
@router.get("/license_types")
|
||||
async def get_license_types(db: Session = Depends(get_db)):
|
||||
license_types = db.query(LicenseType).all()
|
||||
return license_types
|
||||
|
||||
@router.get("/license_types/{license_type_id}")
|
||||
async def get_license_type(license_type_id: int, db: Session = Depends(get_db)):
|
||||
license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
return license_type
|
||||
|
||||
@router.post("/license_types")
|
||||
async def create_license_type(license_type: LicenseTypeCreate, db: Session = Depends(get_db)):
|
||||
db_license_type = LicenseType(**license_type.dict())
|
||||
db.add(db_license_type)
|
||||
db.commit()
|
||||
db.refresh(db_license_type)
|
||||
return db_license_type
|
||||
|
||||
@router.put("/license_types/{license_type_id}")
|
||||
async def update_license_type(license_type_id: int, license_type: LicenseTypeUpdate, db: Session = Depends(get_db)):
|
||||
db_license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not db_license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
|
||||
for key, value in license_type.dict(exclude_unset=True).items():
|
||||
setattr(db_license_type, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_license_type)
|
||||
return db_license_type
|
||||
|
||||
@router.delete("/license_types/{license_type_id}")
|
||||
async def delete_license_type(license_type_id: int, db: Session = Depends(get_db)):
|
||||
db_license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not db_license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
|
||||
db.delete(db_license_type)
|
||||
db.commit()
|
||||
return {"message": "License type deleted successfully"}
|
||||
|
||||
# Product routes
|
||||
@router.get("/products")
|
||||
async def get_products(db: Session = Depends(get_db)):
|
||||
products = db.query(Product).all()
|
||||
return products
|
||||
|
||||
@router.get("/products/{product_id}")
|
||||
async def get_product(product_id: int, db: Session = Depends(get_db)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
return product
|
||||
|
||||
@router.post("/products")
|
||||
async def create_product(product: ProductCreate, db: Session = Depends(get_db)):
|
||||
db_product = Product(**product.dict())
|
||||
db.add(db_product)
|
||||
db.commit()
|
||||
db.refresh(db_product)
|
||||
return db_product
|
||||
|
||||
@router.put("/products/{product_id}")
|
||||
async def update_product(product_id: int, product: ProductUpdate, db: Session = Depends(get_db)):
|
||||
db_product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not db_product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
for key, value in product.dict(exclude_unset=True).items():
|
||||
setattr(db_product, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_product)
|
||||
return db_product
|
||||
|
||||
@router.delete("/products/{product_id}")
|
||||
async def delete_product(product_id: int, db: Session = Depends(get_db)):
|
||||
db_product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not db_product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
db.delete(db_product)
|
||||
db.commit()
|
||||
return {"message": "Product deleted successfully"}
|
||||
@@ -0,0 +1,183 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import ResourcePool, PoolResource, PoolReceipt, PoolAllocation
|
||||
from app.schemas import ResourcePoolCreate, ResourcePoolUpdate, PoolResourceCreate, PoolResourceUpdate, PoolReceiptCreate, PoolReceiptUpdate, PoolAllocationCreate, PoolAllocationUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# ResourcePool routes
|
||||
@router.get("/resource_pools")
|
||||
async def get_resource_pools(db: Session = Depends(get_db)):
|
||||
pools = db.query(ResourcePool).all()
|
||||
return pools
|
||||
|
||||
@router.get("/resource_pools/{pool_id}")
|
||||
async def get_resource_pool(pool_id: int, db: Session = Depends(get_db)):
|
||||
pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
return pool
|
||||
|
||||
@router.post("/resource_pools")
|
||||
async def create_resource_pool(pool: ResourcePoolCreate, db: Session = Depends(get_db)):
|
||||
db_pool = ResourcePool(**pool.dict())
|
||||
db.add(db_pool)
|
||||
db.commit()
|
||||
db.refresh(db_pool)
|
||||
return db_pool
|
||||
|
||||
@router.put("/resource_pools/{pool_id}")
|
||||
async def update_resource_pool(pool_id: int, pool: ResourcePoolUpdate, db: Session = Depends(get_db)):
|
||||
db_pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not db_pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
|
||||
for key, value in pool.dict(exclude_unset=True).items():
|
||||
setattr(db_pool, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_pool)
|
||||
return db_pool
|
||||
|
||||
@router.delete("/resource_pools/{pool_id}")
|
||||
async def delete_resource_pool(pool_id: int, db: Session = Depends(get_db)):
|
||||
db_pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not db_pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
|
||||
db.delete(db_pool)
|
||||
db.commit()
|
||||
return {"message": "Resource pool deleted successfully"}
|
||||
|
||||
# PoolResource routes
|
||||
@router.get("/pool_resources")
|
||||
async def get_pool_resources(db: Session = Depends(get_db)):
|
||||
resources = db.query(PoolResource).all()
|
||||
return resources
|
||||
|
||||
@router.get("/pool_resources/{resource_id}")
|
||||
async def get_pool_resource(resource_id: int, db: Session = Depends(get_db)):
|
||||
resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
return resource
|
||||
|
||||
@router.post("/pool_resources")
|
||||
async def create_pool_resource(resource: PoolResourceCreate, db: Session = Depends(get_db)):
|
||||
db_resource = PoolResource(**resource.dict())
|
||||
db.add(db_resource)
|
||||
db.commit()
|
||||
db.refresh(db_resource)
|
||||
return db_resource
|
||||
|
||||
@router.put("/pool_resources/{resource_id}")
|
||||
async def update_pool_resource(resource_id: int, resource: PoolResourceUpdate, db: Session = Depends(get_db)):
|
||||
db_resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not db_resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
|
||||
for key, value in resource.dict(exclude_unset=True).items():
|
||||
setattr(db_resource, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_resource)
|
||||
return db_resource
|
||||
|
||||
@router.delete("/pool_resources/{resource_id}")
|
||||
async def delete_pool_resource(resource_id: int, db: Session = Depends(get_db)):
|
||||
db_resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not db_resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
|
||||
db.delete(db_resource)
|
||||
db.commit()
|
||||
return {"message": "Pool resource deleted successfully"}
|
||||
|
||||
# PoolReceipt routes
|
||||
@router.get("/pool_receipts")
|
||||
async def get_pool_receipts(db: Session = Depends(get_db)):
|
||||
receipts = db.query(PoolReceipt).all()
|
||||
return receipts
|
||||
|
||||
@router.get("/pool_receipts/{receipt_id}")
|
||||
async def get_pool_receipt(receipt_id: int, db: Session = Depends(get_db)):
|
||||
receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
return receipt
|
||||
|
||||
@router.post("/pool_receipts")
|
||||
async def create_pool_receipt(receipt: PoolReceiptCreate, db: Session = Depends(get_db)):
|
||||
db_receipt = PoolReceipt(**receipt.dict())
|
||||
db.add(db_receipt)
|
||||
db.commit()
|
||||
db.refresh(db_receipt)
|
||||
return db_receipt
|
||||
|
||||
@router.put("/pool_receipts/{receipt_id}")
|
||||
async def update_pool_receipt(receipt_id: int, receipt: PoolReceiptUpdate, db: Session = Depends(get_db)):
|
||||
db_receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not db_receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
|
||||
for key, value in receipt.dict(exclude_unset=True).items():
|
||||
setattr(db_receipt, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_receipt)
|
||||
return db_receipt
|
||||
|
||||
@router.delete("/pool_receipts/{receipt_id}")
|
||||
async def delete_pool_receipt(receipt_id: int, db: Session = Depends(get_db)):
|
||||
db_receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not db_receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
|
||||
db.delete(db_receipt)
|
||||
db.commit()
|
||||
return {"message": "Pool receipt deleted successfully"}
|
||||
|
||||
# PoolAllocation routes
|
||||
@router.get("/pool_allocations")
|
||||
async def get_pool_allocations(db: Session = Depends(get_db)):
|
||||
allocations = db.query(PoolAllocation).all()
|
||||
return allocations
|
||||
|
||||
@router.get("/pool_allocations/{allocation_id}")
|
||||
async def get_pool_allocation(allocation_id: int, db: Session = Depends(get_db)):
|
||||
allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
return allocation
|
||||
|
||||
@router.post("/pool_allocations")
|
||||
async def create_pool_allocation(allocation: PoolAllocationCreate, db: Session = Depends(get_db)):
|
||||
db_allocation = PoolAllocation(**allocation.dict())
|
||||
db.add(db_allocation)
|
||||
db.commit()
|
||||
db.refresh(db_allocation)
|
||||
return db_allocation
|
||||
|
||||
@router.put("/pool_allocations/{allocation_id}")
|
||||
async def update_pool_allocation(allocation_id: int, allocation: PoolAllocationUpdate, db: Session = Depends(get_db)):
|
||||
db_allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not db_allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
|
||||
for key, value in allocation.dict(exclude_unset=True).items():
|
||||
setattr(db_allocation, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_allocation)
|
||||
return db_allocation
|
||||
|
||||
@router.delete("/pool_allocations/{allocation_id}")
|
||||
async def delete_pool_allocation(allocation_id: int, db: Session = Depends(get_db)):
|
||||
db_allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not db_allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
|
||||
db.delete(db_allocation)
|
||||
db.commit()
|
||||
return {"message": "Pool allocation deleted successfully"}
|
||||
@@ -0,0 +1,227 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import Vendor, Purchase, PurchaseItem, Invoice, Shipment
|
||||
from app.schemas import VendorCreate, VendorUpdate, PurchaseCreate, PurchaseUpdate, PurchaseItemCreate, PurchaseItemUpdate, InvoiceCreate, InvoiceUpdate, ShipmentCreate, ShipmentUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Vendor routes
|
||||
@router.get("/vendors")
|
||||
async def get_vendors(db: Session = Depends(get_db)):
|
||||
vendors = db.query(Vendor).all()
|
||||
return vendors
|
||||
|
||||
@router.get("/vendors/{vendor_id}")
|
||||
async def get_vendor(vendor_id: int, db: Session = Depends(get_db)):
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if not vendor:
|
||||
raise HTTPException(status_code=404, detail="Vendor not found")
|
||||
return vendor
|
||||
|
||||
@router.post("/vendors")
|
||||
async def create_vendor(vendor: VendorCreate, db: Session = Depends(get_db)):
|
||||
db_vendor = Vendor(**vendor.dict())
|
||||
db.add(db_vendor)
|
||||
db.commit()
|
||||
db.refresh(db_vendor)
|
||||
return db_vendor
|
||||
|
||||
@router.put("/vendors/{vendor_id}")
|
||||
async def update_vendor(vendor_id: int, vendor: VendorUpdate, db: Session = Depends(get_db)):
|
||||
db_vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if not db_vendor:
|
||||
raise HTTPException(status_code=404, detail="Vendor not found")
|
||||
|
||||
for key, value in vendor.dict(exclude_unset=True).items():
|
||||
setattr(db_vendor, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_vendor)
|
||||
return db_vendor
|
||||
|
||||
@router.delete("/vendors/{vendor_id}")
|
||||
async def delete_vendor(vendor_id: int, db: Session = Depends(get_db)):
|
||||
db_vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if not db_vendor:
|
||||
raise HTTPException(status_code=404, detail="Vendor not found")
|
||||
|
||||
db.delete(db_vendor)
|
||||
db.commit()
|
||||
return {"message": "Vendor deleted successfully"}
|
||||
|
||||
# Purchase routes
|
||||
@router.get("/purchases")
|
||||
async def get_purchases(db: Session = Depends(get_db)):
|
||||
purchases = db.query(Purchase).all()
|
||||
return purchases
|
||||
|
||||
@router.get("/purchases/{purchase_id}")
|
||||
async def get_purchase(purchase_id: int, db: Session = Depends(get_db)):
|
||||
purchase = db.query(Purchase).filter(Purchase.id == purchase_id).first()
|
||||
if not purchase:
|
||||
raise HTTPException(status_code=404, detail="Purchase not found")
|
||||
return purchase
|
||||
|
||||
@router.post("/purchases")
|
||||
async def create_purchase(purchase: PurchaseCreate, db: Session = Depends(get_db)):
|
||||
db_purchase = Purchase(**purchase.dict())
|
||||
db.add(db_purchase)
|
||||
db.commit()
|
||||
db.refresh(db_purchase)
|
||||
return db_purchase
|
||||
|
||||
@router.put("/purchases/{purchase_id}")
|
||||
async def update_purchase(purchase_id: int, purchase: PurchaseUpdate, db: Session = Depends(get_db)):
|
||||
db_purchase = db.query(Purchase).filter(Purchase.id == purchase_id).first()
|
||||
if not db_purchase:
|
||||
raise HTTPException(status_code=404, detail="Purchase not found")
|
||||
|
||||
for key, value in purchase.dict(exclude_unset=True).items():
|
||||
setattr(db_purchase, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_purchase)
|
||||
return db_purchase
|
||||
|
||||
@router.delete("/purchases/{purchase_id}")
|
||||
async def delete_purchase(purchase_id: int, db: Session = Depends(get_db)):
|
||||
db_purchase = db.query(Purchase).filter(Purchase.id == purchase_id).first()
|
||||
if not db_purchase:
|
||||
raise HTTPException(status_code=404, detail="Purchase not found")
|
||||
|
||||
db.delete(db_purchase)
|
||||
db.commit()
|
||||
return {"message": "Purchase deleted successfully"}
|
||||
|
||||
# PurchaseItem routes
|
||||
@router.get("/purchase_items")
|
||||
async def get_purchase_items(db: Session = Depends(get_db)):
|
||||
items = db.query(PurchaseItem).all()
|
||||
return items
|
||||
|
||||
@router.get("/purchase_items/{item_id}")
|
||||
async def get_purchase_item(item_id: int, db: Session = Depends(get_db)):
|
||||
item = db.query(PurchaseItem).filter(PurchaseItem.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Purchase item not found")
|
||||
return item
|
||||
|
||||
@router.post("/purchase_items")
|
||||
async def create_purchase_item(item: PurchaseItemCreate, db: Session = Depends(get_db)):
|
||||
db_item = PurchaseItem(**item.dict())
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@router.put("/purchase_items/{item_id}")
|
||||
async def update_purchase_item(item_id: int, item: PurchaseItemUpdate, db: Session = Depends(get_db)):
|
||||
db_item = db.query(PurchaseItem).filter(PurchaseItem.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(status_code=404, detail="Purchase item not found")
|
||||
|
||||
for key, value in item.dict(exclude_unset=True).items():
|
||||
setattr(db_item, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@router.delete("/purchase_items/{item_id}")
|
||||
async def delete_purchase_item(item_id: int, db: Session = Depends(get_db)):
|
||||
db_item = db.query(PurchaseItem).filter(PurchaseItem.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(status_code=404, detail="Purchase item not found")
|
||||
|
||||
db.delete(db_item)
|
||||
db.commit()
|
||||
return {"message": "Purchase item deleted successfully"}
|
||||
|
||||
# Invoice routes
|
||||
@router.get("/invoices")
|
||||
async def get_invoices(db: Session = Depends(get_db)):
|
||||
invoices = db.query(Invoice).all()
|
||||
return invoices
|
||||
|
||||
@router.get("/invoices/{invoice_id}")
|
||||
async def get_invoice(invoice_id: int, db: Session = Depends(get_db)):
|
||||
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||
if not invoice:
|
||||
raise HTTPException(status_code=404, detail="Invoice not found")
|
||||
return invoice
|
||||
|
||||
@router.post("/invoices")
|
||||
async def create_invoice(invoice: InvoiceCreate, db: Session = Depends(get_db)):
|
||||
db_invoice = Invoice(**invoice.dict())
|
||||
db.add(db_invoice)
|
||||
db.commit()
|
||||
db.refresh(db_invoice)
|
||||
return db_invoice
|
||||
|
||||
@router.put("/invoices/{invoice_id}")
|
||||
async def update_invoice(invoice_id: int, invoice: InvoiceUpdate, db: Session = Depends(get_db)):
|
||||
db_invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||
if not db_invoice:
|
||||
raise HTTPException(status_code=404, detail="Invoice not found")
|
||||
|
||||
for key, value in invoice.dict(exclude_unset=True).items():
|
||||
setattr(db_invoice, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_invoice)
|
||||
return db_invoice
|
||||
|
||||
@router.delete("/invoices/{invoice_id}")
|
||||
async def delete_invoice(invoice_id: int, db: Session = Depends(get_db)):
|
||||
db_invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||
if not db_invoice:
|
||||
raise HTTPException(status_code=404, detail="Invoice not found")
|
||||
|
||||
db.delete(db_invoice)
|
||||
db.commit()
|
||||
return {"message": "Invoice deleted successfully"}
|
||||
|
||||
# Shipment routes
|
||||
@router.get("/shipments")
|
||||
async def get_shipments(db: Session = Depends(get_db)):
|
||||
shipments = db.query(Shipment).all()
|
||||
return shipments
|
||||
|
||||
@router.get("/shipments/{shipment_id}")
|
||||
async def get_shipment(shipment_id: int, db: Session = Depends(get_db)):
|
||||
shipment = db.query(Shipment).filter(Shipment.id == shipment_id).first()
|
||||
if not shipment:
|
||||
raise HTTPException(status_code=404, detail="Shipment not found")
|
||||
return shipment
|
||||
|
||||
@router.post("/shipments")
|
||||
async def create_shipment(shipment: ShipmentCreate, db: Session = Depends(get_db)):
|
||||
db_shipment = Shipment(**shipment.dict())
|
||||
db.add(db_shipment)
|
||||
db.commit()
|
||||
db.refresh(db_shipment)
|
||||
return db_shipment
|
||||
|
||||
@router.put("/shipments/{shipment_id}")
|
||||
async def update_shipment(shipment_id: int, shipment: ShipmentUpdate, db: Session = Depends(get_db)):
|
||||
db_shipment = db.query(Shipment).filter(Shipment.id == shipment_id).first()
|
||||
if not db_shipment:
|
||||
raise HTTPException(status_code=404, detail="Shipment not found")
|
||||
|
||||
for key, value in shipment.dict(exclude_unset=True).items():
|
||||
setattr(db_shipment, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_shipment)
|
||||
return db_shipment
|
||||
|
||||
@router.delete("/shipments/{shipment_id}")
|
||||
async def delete_shipment(shipment_id: int, db: Session = Depends(get_db)):
|
||||
db_shipment = db.query(Shipment).filter(Shipment.id == shipment_id).first()
|
||||
if not db_shipment:
|
||||
raise HTTPException(status_code=404, detail="Shipment not found")
|
||||
|
||||
db.delete(db_shipment)
|
||||
db.commit()
|
||||
return {"message": "Shipment deleted successfully"}
|
||||
@@ -0,0 +1,491 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.models import Project, System, Key, Guardian, License, LicenseType, Product, ResourcePool, PoolResource, PoolReceipt, PoolAllocation
|
||||
from app.schemas import ProjectCreate, ProjectUpdate, SystemCreate, SystemUpdate, KeyCreate, KeyUpdate, GuardianCreate, GuardianUpdate, LicenseCreate, LicenseUpdate, LicenseTypeCreate, LicenseTypeUpdate, ProductCreate, ProductUpdate, ResourcePoolCreate, ResourcePoolUpdate, PoolResourceCreate, PoolResourceUpdate, PoolReceiptCreate, PoolReceiptUpdate, PoolAllocationCreate, PoolAllocationUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Project routes
|
||||
@router.get("/projects")
|
||||
async def get_projects(db: Session = Depends(get_db)):
|
||||
projects = db.query(Project).all()
|
||||
return projects
|
||||
|
||||
@router.get("/projects/{project_id}")
|
||||
async def get_project(project_id: int, db: Session = Depends(get_db)):
|
||||
project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return project
|
||||
|
||||
@router.post("/projects")
|
||||
async def create_project(project: ProjectCreate, db: Session = Depends(get_db)):
|
||||
db_project = Project(**project.dict())
|
||||
db.add(db_project)
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
return db_project
|
||||
|
||||
@router.put("/projects/{project_id}")
|
||||
async def update_project(project_id: int, project: ProjectUpdate, db: Session = Depends(get_db)):
|
||||
db_project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not db_project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
for key, value in project.dict(exclude_unset=True).items():
|
||||
setattr(db_project, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
return db_project
|
||||
|
||||
@router.delete("/projects/{project_id}")
|
||||
async def delete_project(project_id: int, db: Session = Depends(get_db)):
|
||||
db_project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not db_project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
db.delete(db_project)
|
||||
db.commit()
|
||||
return {"message": "Project deleted successfully"}
|
||||
|
||||
# System routes
|
||||
@router.get("/systems")
|
||||
async def get_systems(db: Session = Depends(get_db)):
|
||||
systems = db.query(System).all()
|
||||
return systems
|
||||
|
||||
@router.get("/systems/{system_id}")
|
||||
async def get_system(system_id: int, db: Session = Depends(get_db)):
|
||||
system = db.query(System).filter(System.id == system_id).first()
|
||||
if not system:
|
||||
raise HTTPException(status_code=404, detail="System not found")
|
||||
return system
|
||||
|
||||
@router.post("/systems")
|
||||
async def create_system(system: SystemCreate, db: Session = Depends(get_db)):
|
||||
db_system = System(**system.dict())
|
||||
db.add(db_system)
|
||||
db.commit()
|
||||
db.refresh(db_system)
|
||||
return db_system
|
||||
|
||||
@router.put("/systems/{system_id}")
|
||||
async def update_system(system_id: int, system: SystemUpdate, db: Session = Depends(get_db)):
|
||||
db_system = db.query(System).filter(System.id == system_id).first()
|
||||
if not db_system:
|
||||
raise HTTPException(status_code=404, detail="System not found")
|
||||
|
||||
for key, value in system.dict(exclude_unset=True).items():
|
||||
setattr(db_system, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_system)
|
||||
return db_system
|
||||
|
||||
@router.delete("/systems/{system_id}")
|
||||
async def delete_system(system_id: int, db: Session = Depends(get_db)):
|
||||
db_system = db.query(System).filter(System.id == system_id).first()
|
||||
if not db_system:
|
||||
raise HTTPException(status_code=404, detail="System not found")
|
||||
|
||||
db.delete(db_system)
|
||||
db.commit()
|
||||
return {"message": "System deleted successfully"}
|
||||
|
||||
# Key routes
|
||||
@router.get("/keys")
|
||||
async def get_keys(db: Session = Depends(get_db)):
|
||||
keys = db.query(Key).all()
|
||||
return keys
|
||||
|
||||
@router.get("/keys/{key_id}")
|
||||
async def get_key(key_id: int, db: Session = Depends(get_db)):
|
||||
key = db.query(Key).filter(Key.id == key_id).first()
|
||||
if not key:
|
||||
raise HTTPException(status_code=404, detail="Key not found")
|
||||
return key
|
||||
|
||||
@router.post("/keys")
|
||||
async def create_key(key: KeyCreate, db: Session = Depends(get_db)):
|
||||
db_key = Key(**key.dict())
|
||||
db.add(db_key)
|
||||
db.commit()
|
||||
db.refresh(db_key)
|
||||
return db_key
|
||||
|
||||
@router.put("/keys/{key_id}")
|
||||
async def update_key(key_id: int, key: KeyUpdate, db: Session = Depends(get_db)):
|
||||
db_key = db.query(Key).filter(Key.id == key_id).first()
|
||||
if not db_key:
|
||||
raise HTTPException(status_code=404, detail="Key not found")
|
||||
|
||||
for key, value in key.dict(exclude_unset=True).items():
|
||||
setattr(db_key, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_key)
|
||||
return db_key
|
||||
|
||||
@router.delete("/keys/{key_id}")
|
||||
async def delete_key(key_id: int, db: Session = Depends(get_db)):
|
||||
db_key = db.query(Key).filter(Key.id == key_id).first()
|
||||
if not db_key:
|
||||
raise HTTPException(status_code=404, detail="Key not found")
|
||||
|
||||
db.delete(db_key)
|
||||
db.commit()
|
||||
return {"message": "Key deleted successfully"}
|
||||
|
||||
# Guardian routes
|
||||
@router.get("/guardians")
|
||||
async def get_guardians(db: Session = Depends(get_db)):
|
||||
guardians = db.query(Guardian).all()
|
||||
return guardians
|
||||
|
||||
@router.get("/guardians/{guardian_id}")
|
||||
async def get_guardian(guardian_id: int, db: Session = Depends(get_db)):
|
||||
guardian = db.query(Guardian).filter(Guardian.id == guardian_id).first()
|
||||
if not guardian:
|
||||
raise HTTPException(status_code=404, detail="Guardian not found")
|
||||
return guardian
|
||||
|
||||
@router.post("/guardians")
|
||||
async def create_guardian(guardian: GuardianCreate, db: Session = Depends(get_db)):
|
||||
db_guardian = Guardian(**guardian.dict())
|
||||
db.add(db_guardian)
|
||||
db.commit()
|
||||
db.refresh(db_guardian)
|
||||
return db_guardian
|
||||
|
||||
@router.put("/guardians/{guardian_id}")
|
||||
async def update_guardian(guardian_id: int, guardian: GuardianUpdate, db: Session = Depends(get_db)):
|
||||
db_guardian = db.query(Guardian).filter(Guardian.id == guardian_id).first()
|
||||
if not db_guardian:
|
||||
raise HTTPException(status_code=404, detail="Guardian not found")
|
||||
|
||||
for key, value in guardian.dict(exclude_unset=True).items():
|
||||
setattr(db_guardian, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_guardian)
|
||||
return db_guardian
|
||||
|
||||
@router.delete("/guardians/{guardian_id}")
|
||||
async def delete_guardian(guardian_id: int, db: Session = Depends(get_db)):
|
||||
db_guardian = db.query(Guardian).filter(Guardian.id == guardian_id).first()
|
||||
if not db_guardian:
|
||||
raise HTTPException(status_code=404, detail="Guardian not found")
|
||||
|
||||
db.delete(db_guardian)
|
||||
db.commit()
|
||||
return {"message": "Guardian deleted successfully"}
|
||||
|
||||
# License routes
|
||||
@router.get("/licenses")
|
||||
async def get_licenses(db: Session = Depends(get_db)):
|
||||
licenses = db.query(License).all()
|
||||
return licenses
|
||||
|
||||
@router.get("/licenses/{license_id}")
|
||||
async def get_license(license_id: int, db: Session = Depends(get_db)):
|
||||
license = db.query(License).filter(License.id == license_id).first()
|
||||
if not license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
return license
|
||||
|
||||
@router.post("/licenses")
|
||||
async def create_license(license: LicenseCreate, db: Session = Depends(get_db)):
|
||||
db_license = License(**license.dict())
|
||||
db.add(db_license)
|
||||
db.commit()
|
||||
db.refresh(db_license)
|
||||
return db_license
|
||||
|
||||
@router.put("/licenses/{license_id}")
|
||||
async def update_license(license_id: int, license: LicenseUpdate, db: Session = Depends(get_db)):
|
||||
db_license = db.query(License).filter(License.id == license_id).first()
|
||||
if not db_license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
|
||||
for key, value in license.dict(exclude_unset=True).items():
|
||||
setattr(db_license, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_license)
|
||||
return db_license
|
||||
|
||||
@router.delete("/licenses/{license_id}")
|
||||
async def delete_license(license_id: int, db: Session = Depends(get_db)):
|
||||
db_license = db.query(License).filter(License.id == license_id).first()
|
||||
if not db_license:
|
||||
raise HTTPException(status_code=404, detail="License not found")
|
||||
|
||||
db.delete(db_license)
|
||||
db.commit()
|
||||
return {"message": "License deleted successfully"}
|
||||
|
||||
# LicenseType routes
|
||||
@router.get("/license_types")
|
||||
async def get_license_types(db: Session = Depends(get_db)):
|
||||
license_types = db.query(LicenseType).all()
|
||||
return license_types
|
||||
|
||||
@router.get("/license_types/{license_type_id}")
|
||||
async def get_license_type(license_type_id: int, db: Session = Depends(get_db)):
|
||||
license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
return license_type
|
||||
|
||||
@router.post("/license_types")
|
||||
async def create_license_type(license_type: LicenseTypeCreate, db: Session = Depends(get_db)):
|
||||
db_license_type = LicenseType(**license_type.dict())
|
||||
db.add(db_license_type)
|
||||
db.commit()
|
||||
db.refresh(db_license_type)
|
||||
return db_license_type
|
||||
|
||||
@router.put("/license_types/{license_type_id}")
|
||||
async def update_license_type(license_type_id: int, license_type: LicenseTypeUpdate, db: Session = Depends(get_db)):
|
||||
db_license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not db_license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
|
||||
for key, value in license_type.dict(exclude_unset=True).items():
|
||||
setattr(db_license_type, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_license_type)
|
||||
return db_license_type
|
||||
|
||||
@router.delete("/license_types/{license_type_id}")
|
||||
async def delete_license_type(license_type_id: int, db: Session = Depends(get_db)):
|
||||
db_license_type = db.query(LicenseType).filter(LicenseType.id == license_type_id).first()
|
||||
if not db_license_type:
|
||||
raise HTTPException(status_code=404, detail="License type not found")
|
||||
|
||||
db.delete(db_license_type)
|
||||
db.commit()
|
||||
return {"message": "License type deleted successfully"}
|
||||
|
||||
# Product routes
|
||||
@router.get("/products")
|
||||
async def get_products(db: Session = Depends(get_db)):
|
||||
products = db.query(Product).all()
|
||||
return products
|
||||
|
||||
@router.get("/products/{product_id}")
|
||||
async def get_product(product_id: int, db: Session = Depends(get_db)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
return product
|
||||
|
||||
@router.post("/products")
|
||||
async def create_product(product: ProductCreate, db: Session = Depends(get_db)):
|
||||
db_product = Product(**product.dict())
|
||||
db.add(db_product)
|
||||
db.commit()
|
||||
db.refresh(db_product)
|
||||
return db_product
|
||||
|
||||
@router.put("/products/{product_id}")
|
||||
async def update_product(product_id: int, product: ProductUpdate, db: Session = Depends(get_db)):
|
||||
db_product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not db_product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
for key, value in product.dict(exclude_unset=True).items():
|
||||
setattr(db_product, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_product)
|
||||
return db_product
|
||||
|
||||
@router.delete("/products/{product_id}")
|
||||
async def delete_product(product_id: int, db: Session = Depends(get_db)):
|
||||
db_product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not db_product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
db.delete(db_product)
|
||||
db.commit()
|
||||
return {"message": "Product deleted successfully"}
|
||||
|
||||
# ResourcePool routes
|
||||
@router.get("/resource_pools")
|
||||
async def get_resource_pools(db: Session = Depends(get_db)):
|
||||
pools = db.query(ResourcePool).all()
|
||||
return pools
|
||||
|
||||
@router.get("/resource_pools/{pool_id}")
|
||||
async def get_resource_pool(pool_id: int, db: Session = Depends(get_db)):
|
||||
pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
return pool
|
||||
|
||||
@router.post("/resource_pools")
|
||||
async def create_resource_pool(pool: ResourcePoolCreate, db: Session = Depends(get_db)):
|
||||
db_pool = ResourcePool(**pool.dict())
|
||||
db.add(db_pool)
|
||||
db.commit()
|
||||
db.refresh(db_pool)
|
||||
return db_pool
|
||||
|
||||
@router.put("/resource_pools/{pool_id}")
|
||||
async def update_resource_pool(pool_id: int, pool: ResourcePoolUpdate, db: Session = Depends(get_db)):
|
||||
db_pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not db_pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
|
||||
for key, value in pool.dict(exclude_unset=True).items():
|
||||
setattr(db_pool, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_pool)
|
||||
return db_pool
|
||||
|
||||
@router.delete("/resource_pools/{pool_id}")
|
||||
async def delete_resource_pool(pool_id: int, db: Session = Depends(get_db)):
|
||||
db_pool = db.query(ResourcePool).filter(ResourcePool.id == pool_id).first()
|
||||
if not db_pool:
|
||||
raise HTTPException(status_code=404, detail="Resource pool not found")
|
||||
|
||||
db.delete(db_pool)
|
||||
db.commit()
|
||||
return {"message": "Resource pool deleted successfully"}
|
||||
|
||||
# PoolResource routes
|
||||
@router.get("/pool_resources")
|
||||
async def get_pool_resources(db: Session = Depends(get_db)):
|
||||
resources = db.query(PoolResource).all()
|
||||
return resources
|
||||
|
||||
@router.get("/pool_resources/{resource_id}")
|
||||
async def get_pool_resource(resource_id: int, db: Session = Depends(get_db)):
|
||||
resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
return resource
|
||||
|
||||
@router.post("/pool_resources")
|
||||
async def create_pool_resource(resource: PoolResourceCreate, db: Session = Depends(get_db)):
|
||||
db_resource = PoolResource(**resource.dict())
|
||||
db.add(db_resource)
|
||||
db.commit()
|
||||
db.refresh(db_resource)
|
||||
return db_resource
|
||||
|
||||
@router.put("/pool_resources/{resource_id}")
|
||||
async def update_pool_resource(resource_id: int, resource: PoolResourceUpdate, db: Session = Depends(get_db)):
|
||||
db_resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not db_resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
|
||||
for key, value in resource.dict(exclude_unset=True).items():
|
||||
setattr(db_resource, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_resource)
|
||||
return db_resource
|
||||
|
||||
@router.delete("/pool_resources/{resource_id}")
|
||||
async def delete_pool_resource(resource_id: int, db: Session = Depends(get_db)):
|
||||
db_resource = db.query(PoolResource).filter(PoolResource.id == resource_id).first()
|
||||
if not db_resource:
|
||||
raise HTTPException(status_code=404, detail="Pool resource not found")
|
||||
|
||||
db.delete(db_resource)
|
||||
db.commit()
|
||||
return {"message": "Pool resource deleted successfully"}
|
||||
|
||||
# PoolReceipt routes
|
||||
@router.get("/pool_receipts")
|
||||
async def get_pool_receipts(db: Session = Depends(get_db)):
|
||||
receipts = db.query(PoolReceipt).all()
|
||||
return receipts
|
||||
|
||||
@router.get("/pool_receipts/{receipt_id}")
|
||||
async def get_pool_receipt(receipt_id: int, db: Session = Depends(get_db)):
|
||||
receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
return receipt
|
||||
|
||||
@router.post("/pool_receipts")
|
||||
async def create_pool_receipt(receipt: PoolReceiptCreate, db: Session = Depends(get_db)):
|
||||
db_receipt = PoolReceipt(**receipt.dict())
|
||||
db.add(db_receipt)
|
||||
db.commit()
|
||||
db.refresh(db_receipt)
|
||||
return db_receipt
|
||||
|
||||
@router.put("/pool_receipts/{receipt_id}")
|
||||
async def update_pool_receipt(receipt_id: int, receipt: PoolReceiptUpdate, db: Session = Depends(get_db)):
|
||||
db_receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not db_receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
|
||||
for key, value in receipt.dict(exclude_unset=True).items():
|
||||
setattr(db_receipt, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_receipt)
|
||||
return db_receipt
|
||||
|
||||
@router.delete("/pool_receipts/{receipt_id}")
|
||||
async def delete_pool_receipt(receipt_id: int, db: Session = Depends(get_db)):
|
||||
db_receipt = db.query(PoolReceipt).filter(PoolReceipt.id == receipt_id).first()
|
||||
if not db_receipt:
|
||||
raise HTTPException(status_code=404, detail="Pool receipt not found")
|
||||
|
||||
db.delete(db_receipt)
|
||||
db.commit()
|
||||
return {"message": "Pool receipt deleted successfully"}
|
||||
|
||||
# PoolAllocation routes
|
||||
@router.get("/pool_allocations")
|
||||
async def get_pool_allocations(db: Session = Depends(get_db)):
|
||||
allocations = db.query(PoolAllocation).all()
|
||||
return allocations
|
||||
|
||||
@router.get("/pool_allocations/{allocation_id}")
|
||||
async def get_pool_allocation(allocation_id: int, db: Session = Depends(get_db)):
|
||||
allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
return allocation
|
||||
|
||||
@router.post("/pool_allocations")
|
||||
async def create_pool_allocation(allocation: PoolAllocationCreate, db: Session = Depends(get_db)):
|
||||
db_allocation = PoolAllocation(**allocation.dict())
|
||||
db.add(db_allocation)
|
||||
db.commit()
|
||||
db.refresh(db_allocation)
|
||||
return db_allocation
|
||||
|
||||
@router.put("/pool_allocations/{allocation_id}")
|
||||
async def update_pool_allocation(allocation_id: int, allocation: PoolAllocationUpdate, db: Session = Depends(get_db)):
|
||||
db_allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not db_allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
|
||||
for key, value in allocation.dict(exclude_unset=True).items():
|
||||
setattr(db_allocation, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_allocation)
|
||||
return db_allocation
|
||||
|
||||
@router.delete("/pool_allocations/{allocation_id}")
|
||||
async def delete_pool_allocation(allocation_id: int, db: Session = Depends(get_db)):
|
||||
db_allocation = db.query(PoolAllocation).filter(PoolAllocation.id == allocation_id).first()
|
||||
if not db_allocation:
|
||||
raise HTTPException(status_code=404, detail="Pool allocation not found")
|
||||
|
||||
db.delete(db_allocation)
|
||||
db.commit()
|
||||
return {"message": "Pool allocation deleted successfully"}
|
||||
@@ -0,0 +1,363 @@
|
||||
"""
|
||||
UI Routes for Specs Accounting System.
|
||||
FastAPI + Jinja2 templates.
|
||||
"""
|
||||
from fastapi import APIRouter, Request, Query, HTTPException, Depends
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
|
||||
from app.database import get_db
|
||||
from app.services.resource_allocation_service import ResourceAllocationService
|
||||
from app.services.procurement_flow_service import ProcurementFlowService
|
||||
from app.models import Project, System, Guardian, Module, Resource, ResourceAllocation, Specification, Purchase
|
||||
|
||||
router = APIRouter(prefix="/ui", tags=["UI"])
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
def get_project_stats(db: Session, project_id: int) -> dict:
|
||||
"""Get statistics for a project."""
|
||||
systems_count = db.query(System).filter(
|
||||
System.project_id == project_id
|
||||
).count()
|
||||
|
||||
resources = db.query(Resource).filter(
|
||||
Resource.project_id == project_id
|
||||
).all()
|
||||
|
||||
total_received = sum(r.quantity for r in resources)
|
||||
total_allocated = sum(
|
||||
db.query(ResourceAllocation.quantity).filter(
|
||||
ResourceAllocation.resource_id == r.id
|
||||
).scalar() or 0
|
||||
for r in resources
|
||||
)
|
||||
|
||||
return {
|
||||
'systems_count': systems_count,
|
||||
'total_received': total_received,
|
||||
'total_allocated': total_allocated,
|
||||
'total_remaining': total_received - total_allocated
|
||||
}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def home(request: Request, db: Session = Depends(get_db)):
|
||||
"""Home page with project list."""
|
||||
projects = db.query(Project).all()
|
||||
project_stats = {p.id: get_project_stats(db, p.id) for p in projects}
|
||||
return templates.TemplateResponse(
|
||||
"home.html",
|
||||
{
|
||||
"request": request,
|
||||
"projects": projects,
|
||||
"stats": project_stats
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/projects")
|
||||
async def projects_list(request: Request, db: Session = Depends(get_db)):
|
||||
"""List all projects."""
|
||||
projects = db.query(Project).all()
|
||||
return templates.TemplateResponse(
|
||||
"projects/list.html",
|
||||
{"request": request, "projects": projects}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}")
|
||||
async def project_detail(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
"""Project detail page."""
|
||||
project = db.query(Project).filter(Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
customers = db.query(Project).filter(Project.id == project_id).first().customers
|
||||
systems = db.query(System).filter(System.project_id == project_id).all()
|
||||
contracts = db.query(Project).filter(Project.id == project_id).first().contracts
|
||||
resources = db.query(Resource).filter(Resource.project_id == project_id).all()
|
||||
purchases = db.query(Purchase).filter(Purchase.project_id == project_id).all()
|
||||
|
||||
stats = get_project_stats(db, project_id)
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"projects/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"project": project,
|
||||
"customers": customers,
|
||||
"systems": systems,
|
||||
"contracts": contracts,
|
||||
"resources": resources,
|
||||
"purchases": purchases,
|
||||
"stats": stats
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/systems")
|
||||
async def systems_list(request: Request, project_id: Optional[int] = None, db: Session = Depends(get_db)):
|
||||
"""List all systems."""
|
||||
if project_id:
|
||||
systems = db.query(System).filter(System.project_id == project_id).all()
|
||||
else:
|
||||
systems = db.query(System).all()
|
||||
return templates.TemplateResponse(
|
||||
"systems/list.html",
|
||||
{"request": request, "systems": systems}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/systems/{system_id}")
|
||||
async def system_detail(request: Request, system_id: int, db: Session = Depends(get_db)):
|
||||
"""System detail page - main UI page."""
|
||||
system = db.query(System).filter(System.id == system_id).first()
|
||||
if not system:
|
||||
raise HTTPException(status_code=404, detail="System not found")
|
||||
|
||||
# Get Common part (guardian_id = NULL)
|
||||
common_modules = db.query(SystemModule).filter(
|
||||
SystemModule.system_id == system_id,
|
||||
SystemModule.guardian_id == None
|
||||
).all()
|
||||
|
||||
# Get Guardians
|
||||
guardians = db.query(Guardian).filter(Guardian.system_id == system_id).all()
|
||||
|
||||
guardian_data = []
|
||||
for guardian in guardians:
|
||||
core = db.query(SystemModule).filter(
|
||||
SystemModule.system_id == system_id,
|
||||
SystemModule.guardian_id == guardian.id,
|
||||
Module.name == "Core"
|
||||
).first()
|
||||
|
||||
other_modules = db.query(SystemModule).filter(
|
||||
SystemModule.system_id == system_id,
|
||||
SystemModule.guardian_id == guardian.id
|
||||
).all()
|
||||
|
||||
guardian_data.append({
|
||||
'guardian': guardian,
|
||||
'core': core,
|
||||
'modules': [m for m in other_modules if m.module.name != 'Core']
|
||||
})
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"systems/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"system": system,
|
||||
"common_modules": common_modules,
|
||||
"guardian_data": guardian_data
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/guardians/{guardian_id}")
|
||||
async def guardian_detail(request: Request, guardian_id: int, db: Session = Depends(get_db)):
|
||||
"""Guardian detail page."""
|
||||
guardian = db.query(Guardian).filter(Guardian.id == guardian_id).first()
|
||||
if not guardian:
|
||||
raise HTTPException(status_code=404, detail="Guardian not found")
|
||||
|
||||
core = db.query(SystemModule).filter(
|
||||
SystemModule.guardian_id == guardian_id,
|
||||
Module.name == "Core"
|
||||
).first()
|
||||
|
||||
modules = db.query(SystemModule).filter(
|
||||
SystemModule.guardian_id == guardian_id
|
||||
).all()
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"guardians/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"guardian": guardian,
|
||||
"core": core,
|
||||
"modules": modules
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/resources")
|
||||
async def resources_list(request: Request, project_id: Optional[int] = None, db: Session = Depends(get_db)):
|
||||
"""Resource pool page."""
|
||||
query = db.query(Resource)
|
||||
if project_id:
|
||||
query = query.filter(Resource.project_id == project_id)
|
||||
|
||||
resources = query.all()
|
||||
return templates.TemplateResponse(
|
||||
"resources/list.html",
|
||||
{"request": request, "resources": resources, "project_id": project_id}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/resources/{resource_id}")
|
||||
async def resource_detail(request: Request, resource_id: int, db: Session = Depends(get_db)):
|
||||
"""Resource detail page."""
|
||||
resource = db.query(Resource).filter(Resource.id == resource_id).first()
|
||||
if not resource:
|
||||
raise HTTPException(status_code=404, detail="Resource not found")
|
||||
|
||||
# Get allocations for this resource
|
||||
allocations = db.query(ResourceAllocation).filter(
|
||||
ResourceAllocation.resource_id == resource_id
|
||||
).all()
|
||||
|
||||
# Calculate remaining
|
||||
allocated = sum(a.quantity for a in allocations)
|
||||
remaining = resource.quantity - allocated
|
||||
|
||||
# Get system and guardian info for allocations
|
||||
allocation_details = []
|
||||
for alloc in allocations:
|
||||
system = db.query(System).filter(System.id == alloc.system_id).first()
|
||||
guardian = db.query(Guardian).filter(Guardian.id == alloc.guardian_id).first() if alloc.guardian_id else None
|
||||
|
||||
allocation_details.append({
|
||||
'allocation': alloc,
|
||||
'system': system,
|
||||
'guardian': guardian,
|
||||
'is_common': guardian is None
|
||||
})
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"resources/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"resource": resource,
|
||||
"allocations": allocation_details,
|
||||
"remaining": remaining
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/resources/{resource_id}/allocate")
|
||||
async def allocate_resource(
|
||||
request: Request,
|
||||
resource_id: int,
|
||||
system_id: int = Query(..., description="System ID"),
|
||||
guardian_id: Optional[int] = Query(None, description="Guardian ID (optional)"),
|
||||
quantity: int = Query(..., description="Quantity to allocate"),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Allocate resource to system/guardian."""
|
||||
try:
|
||||
service = ResourceAllocationService(db)
|
||||
allocation = service.allocate_resource(
|
||||
resource_id=resource_id,
|
||||
system_id=system_id,
|
||||
quantity=quantity,
|
||||
guardian_id=guardian_id,
|
||||
description="UI allocation"
|
||||
)
|
||||
return templates.TemplateResponse(
|
||||
"resources/allocated.html",
|
||||
{
|
||||
"request": request,
|
||||
"allocation": allocation,
|
||||
"resource_id": resource_id
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
return templates.TemplateResponse(
|
||||
"resources/allocate_error.html",
|
||||
{
|
||||
"request": request,
|
||||
"resource_id": resource_id,
|
||||
"error": str(e)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/specifications")
|
||||
async def specifications_list(request: Request, project_id: Optional[int] = None, db: Session = Depends(get_db)):
|
||||
"""Specifications list page."""
|
||||
query = db.query(Specification)
|
||||
if project_id:
|
||||
query = query.filter(Specification.project_id == project_id)
|
||||
|
||||
specifications = query.all()
|
||||
return templates.TemplateResponse(
|
||||
"specifications/list.html",
|
||||
{"request": request, "specifications": specifications, "project_id": project_id}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/specifications/{specification_id}")
|
||||
async def specification_detail(request: Request, specification_id: int, db: Session = Depends(get_db)):
|
||||
"""Specification detail page."""
|
||||
specification = db.query(Specification).filter(Specification.id == specification_id).first()
|
||||
if not specification:
|
||||
raise HTTPException(status_code=404, detail="Specification not found")
|
||||
|
||||
items = db.query(SpecificationItem).filter(
|
||||
SpecificationItem.specification_id == specification_id
|
||||
).all()
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"specifications/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"specification": specification,
|
||||
"items": items
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/purchases")
|
||||
async def purchases_list(request: Request, project_id: Optional[int] = None, db: Session = Depends(get_db)):
|
||||
"""Purchases list page."""
|
||||
query = db.query(Purchase)
|
||||
if project_id:
|
||||
query = query.filter(Purchase.project_id == project_id)
|
||||
|
||||
purchases = query.all()
|
||||
return templates.TemplateResponse(
|
||||
"purchases/list.html",
|
||||
{"request": request, "purchases": purchases, "project_id": project_id}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/purchases/{purchase_id}")
|
||||
async def purchase_detail(request: Request, purchase_id: int, db: Session = Depends(get_db)):
|
||||
"""Purchase detail page."""
|
||||
purchase = db.query(Purchase).filter(Purchase.id == purchase_id).first()
|
||||
if not purchase:
|
||||
raise HTTPException(status_code=404, detail="Purchase not found")
|
||||
|
||||
items = db.query(PurchaseItem).filter(
|
||||
PurchaseItem.purchase_id == purchase_id
|
||||
).all()
|
||||
|
||||
specifications = db.query(Specification).filter(
|
||||
Specification.id.in_(
|
||||
db.query(PurchaseSpecification.specification_id).filter(
|
||||
PurchaseSpecification.purchase_id == purchase_id
|
||||
)
|
||||
)
|
||||
).all()
|
||||
|
||||
return templates.TemplateResponse(
|
||||
"purchases/detail.html",
|
||||
{
|
||||
"request": request,
|
||||
"purchase": purchase,
|
||||
"items": items,
|
||||
"specifications": specifications
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/seed")
|
||||
async def seed_demo_data(db: Session = Depends(get_db)):
|
||||
"""Seed demo data endpoint."""
|
||||
from app.utils.seed_data import seed_demo_data
|
||||
seed_demo_data(db)
|
||||
return {"message": "Demo data seeded successfully"}
|
||||
Executable
+491
@@ -0,0 +1,491 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# Base schema
|
||||
class TimestampMixin(BaseModel):
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
# Customer schemas
|
||||
class CustomerBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class CustomerCreate(CustomerBase):
|
||||
pass
|
||||
|
||||
class CustomerUpdate(CustomerBase):
|
||||
pass
|
||||
|
||||
class Customer(CustomerBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# LegalEntity schemas
|
||||
class LegalEntityBase(TimestampMixin):
|
||||
name: str
|
||||
inn: Optional[str] = None
|
||||
kpp: Optional[str] = None
|
||||
address: Optional[str] = None
|
||||
customer_id: int
|
||||
|
||||
class LegalEntityCreate(LegalEntityBase):
|
||||
pass
|
||||
|
||||
class LegalEntityUpdate(LegalEntityBase):
|
||||
pass
|
||||
|
||||
class LegalEntity(LegalEntityBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Project schemas
|
||||
class ProjectBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
customer_id: int
|
||||
legal_entity_id: int
|
||||
status: Optional[str] = None
|
||||
|
||||
class ProjectCreate(ProjectBase):
|
||||
pass
|
||||
|
||||
class ProjectUpdate(ProjectBase):
|
||||
pass
|
||||
|
||||
class Project(ProjectBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# System schemas
|
||||
class SystemBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
project_id: int
|
||||
customer_id: int
|
||||
|
||||
class SystemCreate(SystemBase):
|
||||
pass
|
||||
|
||||
class SystemUpdate(SystemBase):
|
||||
pass
|
||||
|
||||
class System(SystemBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Key schemas
|
||||
class KeyBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
system_id: int
|
||||
guardian_id: int
|
||||
|
||||
class KeyCreate(KeyBase):
|
||||
pass
|
||||
|
||||
class KeyUpdate(KeyBase):
|
||||
pass
|
||||
|
||||
class Key(KeyBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Guardian schemas
|
||||
class GuardianBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
serial_number: Optional[str] = None
|
||||
location: Optional[str] = None
|
||||
|
||||
class GuardianCreate(GuardianBase):
|
||||
pass
|
||||
|
||||
class GuardianUpdate(GuardianBase):
|
||||
pass
|
||||
|
||||
class Guardian(GuardianBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# LicenseType schemas
|
||||
class LicenseTypeBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class LicenseTypeCreate(LicenseTypeBase):
|
||||
pass
|
||||
|
||||
class LicenseTypeUpdate(LicenseTypeBase):
|
||||
pass
|
||||
|
||||
class LicenseType(LicenseTypeBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Product schemas
|
||||
class ProductBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class ProductCreate(ProductBase):
|
||||
pass
|
||||
|
||||
class ProductUpdate(ProductBase):
|
||||
pass
|
||||
|
||||
class Product(ProductBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# ResourcePool schemas
|
||||
class ResourcePoolBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class ResourcePoolCreate(ResourcePoolBase):
|
||||
pass
|
||||
|
||||
class ResourcePoolUpdate(ResourcePoolBase):
|
||||
pass
|
||||
|
||||
class ResourcePool(ResourcePoolBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# PoolResource schemas
|
||||
class PoolResourceBase(TimestampMixin):
|
||||
resource_pool_id: int
|
||||
product_id: int
|
||||
license_type_id: int
|
||||
|
||||
class PoolResourceCreate(PoolResourceBase):
|
||||
pass
|
||||
|
||||
class PoolResourceUpdate(PoolResourceBase):
|
||||
pass
|
||||
|
||||
class PoolResource(PoolResourceBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# PoolReceipt schemas
|
||||
class PoolReceiptBase(TimestampMixin):
|
||||
pool_resource_id: int
|
||||
quantity: int
|
||||
receipt_date: datetime
|
||||
description: Optional[str] = None
|
||||
|
||||
class PoolReceiptCreate(PoolReceiptBase):
|
||||
pass
|
||||
|
||||
class PoolReceiptUpdate(PoolReceiptBase):
|
||||
pass
|
||||
|
||||
class PoolReceipt(PoolReceiptBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# PoolAllocation schemas
|
||||
class PoolAllocationBase(TimestampMixin):
|
||||
pool_resource_id: int
|
||||
quantity: int
|
||||
allocation_date: datetime
|
||||
description: Optional[str] = None
|
||||
|
||||
class PoolAllocationCreate(PoolAllocationBase):
|
||||
pass
|
||||
|
||||
class PoolAllocationUpdate(PoolAllocationBase):
|
||||
pass
|
||||
|
||||
class PoolAllocation(PoolAllocationBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# License schemas
|
||||
class LicenseBase(TimestampMixin):
|
||||
system_id: int
|
||||
key_id: Optional[int] = None
|
||||
product_id: int
|
||||
license_type_id: int
|
||||
|
||||
class LicenseCreate(LicenseBase):
|
||||
pass
|
||||
|
||||
class LicenseUpdate(LicenseBase):
|
||||
pass
|
||||
|
||||
class License(LicenseBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Contract schemas
|
||||
class ContractBase(TimestampMixin):
|
||||
project_id: int
|
||||
contract_number: str
|
||||
contract_date: Optional[datetime] = None
|
||||
start_date: Optional[datetime] = None
|
||||
end_date: Optional[datetime] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class ContractCreate(ContractBase):
|
||||
pass
|
||||
|
||||
class ContractUpdate(ContractBase):
|
||||
pass
|
||||
|
||||
class Contract(ContractBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# ContractAddendum schemas
|
||||
class ContractAddendumBase(TimestampMixin):
|
||||
contract_id: int
|
||||
addendum_number: str
|
||||
addendum_date: Optional[datetime] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class ContractAddendumCreate(ContractAddendumBase):
|
||||
pass
|
||||
|
||||
class ContractAddendumUpdate(ContractAddendumBase):
|
||||
pass
|
||||
|
||||
class ContractAddendum(ContractAddendumBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Specification schemas
|
||||
class SpecificationBase(TimestampMixin):
|
||||
contract_id: int
|
||||
project_id: int
|
||||
specification_number: str
|
||||
specification_date: Optional[datetime] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class SpecificationCreate(SpecificationBase):
|
||||
pass
|
||||
|
||||
class SpecificationUpdate(SpecificationBase):
|
||||
pass
|
||||
|
||||
class Specification(SpecificationBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# SpecificationItem schemas
|
||||
class SpecificationItemBase(TimestampMixin):
|
||||
specification_id: int
|
||||
product_id: int
|
||||
quantity: int
|
||||
unit: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class SpecificationItemCreate(SpecificationItemBase):
|
||||
pass
|
||||
|
||||
class SpecificationItemUpdate(SpecificationItemBase):
|
||||
pass
|
||||
|
||||
class SpecificationItem(SpecificationItemBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Vendor schemas
|
||||
class VendorBase(TimestampMixin):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
contact_person: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
address: Optional[str] = None
|
||||
|
||||
class VendorCreate(VendorBase):
|
||||
pass
|
||||
|
||||
class VendorUpdate(VendorBase):
|
||||
pass
|
||||
|
||||
class Vendor(VendorBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Purchase schemas
|
||||
class PurchaseBase(TimestampMixin):
|
||||
project_id: int
|
||||
vendor_id: int
|
||||
purchase_number: str
|
||||
purchase_date: Optional[datetime] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class PurchaseCreate(PurchaseBase):
|
||||
pass
|
||||
|
||||
class PurchaseUpdate(PurchaseBase):
|
||||
pass
|
||||
|
||||
class Purchase(PurchaseBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# PurchaseItem schemas
|
||||
class PurchaseItemBase(TimestampMixin):
|
||||
purchase_id: int
|
||||
product_id: int
|
||||
quantity: int
|
||||
unit_price: Optional[float] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class PurchaseItemCreate(PurchaseItemBase):
|
||||
pass
|
||||
|
||||
class PurchaseItemUpdate(PurchaseItemBase):
|
||||
pass
|
||||
|
||||
class PurchaseItem(PurchaseItemBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Invoice schemas
|
||||
class InvoiceBase(TimestampMixin):
|
||||
purchase_id: int
|
||||
invoice_number: str
|
||||
invoice_date: Optional[datetime] = None
|
||||
amount: Optional[float] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class InvoiceCreate(InvoiceBase):
|
||||
pass
|
||||
|
||||
class InvoiceUpdate(InvoiceBase):
|
||||
pass
|
||||
|
||||
class Invoice(InvoiceBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Shipment schemas
|
||||
class ShipmentBase(TimestampMixin):
|
||||
purchase_id: int
|
||||
shipment_number: str
|
||||
shipment_date: Optional[datetime] = None
|
||||
tracking_number: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class ShipmentCreate(ShipmentBase):
|
||||
pass
|
||||
|
||||
class ShipmentUpdate(ShipmentBase):
|
||||
pass
|
||||
|
||||
class Shipment(ShipmentBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# Document schemas
|
||||
class DocumentBase(TimestampMixin):
|
||||
project_id: Optional[int] = None
|
||||
document_type: Optional[str] = None
|
||||
document_number: str
|
||||
document_date: Optional[datetime] = None
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class DocumentCreate(DocumentBase):
|
||||
pass
|
||||
|
||||
class DocumentUpdate(DocumentBase):
|
||||
pass
|
||||
|
||||
class Document(DocumentBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# DocumentFile schemas
|
||||
class DocumentFileBase(TimestampMixin):
|
||||
document_id: int
|
||||
file_path: str
|
||||
file_name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class DocumentFileCreate(DocumentFileBase):
|
||||
pass
|
||||
|
||||
class DocumentFileUpdate(DocumentFileBase):
|
||||
pass
|
||||
|
||||
class DocumentFile(DocumentFileBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
# DocumentDispatch schemas
|
||||
class DocumentDispatchBase(TimestampMixin):
|
||||
document_id: int
|
||||
dispatch_date: Optional[datetime] = None
|
||||
recipient: Optional[str] = None
|
||||
package: Optional[str] = None
|
||||
channel: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class DocumentDispatchCreate(DocumentDispatchBase):
|
||||
pass
|
||||
|
||||
class DocumentDispatchUpdate(DocumentDispatchBase):
|
||||
pass
|
||||
|
||||
class DocumentDispatch(DocumentDispatchBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
Binary file not shown.
Executable
+3
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
Empty __init__.py for services package
|
||||
"""
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,55 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}Specs UI{% endblock %}</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
body { padding-top: 60px; }
|
||||
.navbar-brand { font-weight: bold; }
|
||||
.page-header { margin-bottom: 30px; }
|
||||
.stat-card { padding: 15px; margin: 10px 0; background: #f8f9fa; border-radius: 5px; }
|
||||
.stat-value { font-size: 2em; font-weight: bold; color: #0d6efd; }
|
||||
.stat-label { color: #6c758d; }
|
||||
.section-title { margin-top: 30px; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #dee2e6; }
|
||||
</style>
|
||||
{% block extra_css %}{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="{{ url_for('home') }}">Specs System</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarNav">
|
||||
<ul class="navbar-nav">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{{ url_for('projects_list') }}">Проекты</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{{ url_for('systems_list') }}">Системы</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{{ url_for('specifications_list') }}">Спецификации</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{{ url_for('purchases_list') }}">Закупки</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{{ url_for('resources_list') }}">Ресурсы</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
{% block extra_js %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,75 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ guardian.name }} - Guardian{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Guardian: {{ guardian.name }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('systems_list') }}">Системы</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('system_detail', system_id=guardian.system_id) }}">{{ guardian.system.name if guardian.system else 'N/A' }}</a></li>
|
||||
<li class="breadcrumb-item active">{{ guardian.name }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<p class="text-muted">
|
||||
<strong>System:</strong> {{ guardian.system.name if guardian.system else 'N/A' }}<br>
|
||||
<strong>Serial:</strong> {{ guardian.serial_number if guardian.serial_number else 'N/A' }}<br>
|
||||
<strong>Location:</strong> {{ guardian.location if guardian.location else 'N/A' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info">
|
||||
<strong>Структура Guardian:</strong>
|
||||
<pre class="mb-0" style="background: #e9ecef; padding: 10px;">Guardian {{ guardian.name }}
|
||||
├── Core: 1
|
||||
└── Modules: {{ modules|length }}
|
||||
{% for m in modules %}
|
||||
- {{ m.module.name }} × {{ m.quantity }}
|
||||
{% endfor %}</pre>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Core</div>
|
||||
{% if core %}
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ core.quantity }}</div>
|
||||
<div class="stat-label">Количество Core (только 1 допускается)</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-warning">Core отсутствует! Guardian должен иметь ровно один Core.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="section-title">Модули</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Модуль</th>
|
||||
<th>Количество</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for m in modules %}
|
||||
<tr>
|
||||
<td><strong>{{ m.module.name }}</strong></td>
|
||||
<td>{{ m.quantity }}</td>
|
||||
<td>{{ m.module.description if m.module.description else 'N/A' }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="3" class="text-center">Модули отсутствуют</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('system_detail', system_id=guardian.system_id) }}" class="btn btn-secondary">
|
||||
К System
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,61 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Specs UI - Главная{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Система учета спецификаций</h1>
|
||||
<p class="text-muted">Версия 1.0 - Прототип UI для визуальной проверки предметной модели</p>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="alert alert-info">
|
||||
<strong>Навигация:</strong> Используйте меню сверху для перехода между разделами.
|
||||
Откройте <a href="{{ url_for('projects_list') }}">проекты</a> или <a href="{{ url_for('systems_list') }}">системы</a> для начала работы.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Проекты</div>
|
||||
|
||||
{% if projects %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Название</th>
|
||||
<th>Заказчиков</th>
|
||||
<th>Систем</th>
|
||||
<th>Всего получено</th>
|
||||
<th>Распределено</th>
|
||||
<th>Свободно</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for project in projects %}
|
||||
<tr>
|
||||
<td>{{ project.id }}</td>
|
||||
<td><a href="{{ url_for('project_detail', project_id=project.id) }}">{{ project.name }}</a></td>
|
||||
<td>{{ project.customers|length }}</td>
|
||||
<td>{{ stats.get(project.id, {}).get('systems_count', 0) }}</td>
|
||||
<td>{{ stats.get(project.id, {}).get('total_received', 0) }}</td>
|
||||
<td>{{ stats.get(project.id, {}).get('total_allocated', 0) }}</td>
|
||||
<td>{{ stats.get(project.id, {}).get('total_remaining', 0) }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('project_detail', project_id=project.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-warning">Нет проектов. <a href="{{ url_for('seed_demo_data') }}">Создать демо-данные</a>.</div>
|
||||
{% endif %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,189 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ project.name }} - Проект{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Проект: {{ project.name }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('projects_list') }}">Проекты</a></li>
|
||||
<li class="breadcrumb-item active">{{ project.name }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ stats.total_received }}</div>
|
||||
<div class="stat-label">Всего получено</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ stats.total_allocated }}</div>
|
||||
<div class="stat-label">Распределено</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ stats.total_remaining }}</div>
|
||||
<div class="stat-label">Свободно</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ stats.systems_count }}</div>
|
||||
<div class="stat-label">Систем</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Заказчики</div>
|
||||
<ul class="list-group">
|
||||
{% for customer in customers %}
|
||||
<li class="list-group-item">{{ customer.name }}{% if customer.description %} - {{ customer.description }}{% endif %}</li>
|
||||
{% else %}
|
||||
<li class="list-group-item">Нет заказчиков</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
<div class="section-title">Системы</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Название</th>
|
||||
<th>Заказчик</th>
|
||||
<th>Гарданты</th>
|
||||
<th>Модули</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for system in systems %}
|
||||
<tr>
|
||||
<td>{{ system.id }}</td>
|
||||
<td><a href="{{ url_for('system_detail', system_id=system.id) }}">{{ system.name }}</a></td>
|
||||
<td>{{ system.customer.name if system.customer else 'N/A' }}</td>
|
||||
<td>{{ system.guardians|length }}</td>
|
||||
<td>{{ system.system_modules|length }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('system_detail', system_id=system.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="6">Нет систем в этом проекте</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Спецификации</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Номер</th>
|
||||
<th>Дата</th>
|
||||
<th>Договор</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for contract in contracts %}
|
||||
{% for spec in contract.specifications %}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('specification_detail', specification_id=spec.id) }}">{{ spec.specification_number }}</a></td>
|
||||
<td>{{ spec.specification_date.strftime('%Y-%m-%d') if spec.specification_date else 'N/A' }}</td>
|
||||
<td>{{ contract.contract_number }}</td>
|
||||
<td><a href="{{ url_for('specification_detail', specification_id=spec.id) }}" class="btn btn-sm btn-secondary">Открыть</a></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="4">Нет спецификаций</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Закупки</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Номер</th>
|
||||
<th>Дата</th>
|
||||
<th>Поставщик</th>
|
||||
<th>Позиций</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for purchase in purchases %}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('purchase_detail', purchase_id=purchase.id) }}">{{ purchase.purchase_number }}</a></td>
|
||||
<td>{{ purchase.purchase_date.strftime('%Y-%m-%d') if purchase.purchase_date else 'N/A' }}</td>
|
||||
<td>{{ purchase.vendor.name if purchase.vendor else 'N/A' }}</td>
|
||||
<td>{{ purchase.purchase_items|length }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('purchase_detail', purchase_id=purchase.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="5">Нет закупок</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Ресурсы</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Модуль</th>
|
||||
<th>Получено</th>
|
||||
<th>Invoice</th>
|
||||
<th>Specification</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for resource in resources %}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('resource_detail', resource_id=resource.id) }}">{{ resource.id }}</a></td>
|
||||
<td>{{ resource.module.name if resource.module else 'N/A' }}</td>
|
||||
<td>{{ resource.quantity }}</td>
|
||||
<td>{{ resource.invoice_number if resource.invoice_number else 'N/A' }}</td>
|
||||
<td>{{ resource.specification_number if resource.specification_number else 'N/A' }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('resource_detail', resource_id=resource.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="6">Нет ресурсов</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,101 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ purchase.purchase_number }} - Закупка{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Закупка: {{ purchase.purchase_number }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('purchases_list') }}">Закупки</a></li>
|
||||
<li class="breadcrumb-item active">{{ purchase.purchase_number }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<div class="card">
|
||||
<div class="card-header">Реквизиты закупки</div>
|
||||
<div class="card-body">
|
||||
<p><strong>ID:</strong> {{ purchase.id }}</p>
|
||||
<p><strong>Номер:</strong> {{ purchase.purchase_number }}</p>
|
||||
<p><strong>Дата:</strong> {{ purchase.purchase_date.strftime('%Y-%m-%d') if purchase.purchase_date else 'N/A' }}</p>
|
||||
<p><strong>Поставщик:</strong> {{ purchase.vendor.name if purchase.vendor else 'N/A' }}</p>
|
||||
<p><strong>Проект:</strong> {{ purchase.project.name if purchase.project else 'N/A' }}</p>
|
||||
<p><strong>Описание:</strong> {{ purchase.description or 'N/A' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">Связанные спецификации</div>
|
||||
<div class="card-body">
|
||||
{% if specifications %}
|
||||
<ul class="list-group">
|
||||
{% for spec in specifications %}
|
||||
<li class="list-group-item">
|
||||
<a href="{{ url_for('specification_detail', specification_id=spec.id) }}">
|
||||
{{ spec.specification_number }}
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<div class="text-muted">Нет связанных спецификаций</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Позиции закупки (PurchaseItems)</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Модуль</th>
|
||||
<th>Количество</th>
|
||||
<th>Цена</th>
|
||||
<th>Invoice</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in items %}
|
||||
<tr>
|
||||
<td>{{ item.id }}</td>
|
||||
<td><strong>{{ item.module.name }}</strong></td>
|
||||
<td>{{ item.quantity }}</td>
|
||||
<td>${{ "%.2f"|format(item.unit_price) if item.unit_price else 'N/A' }}</td>
|
||||
<td>
|
||||
{% set invoices = item.purchase.invoices | selectattr('invoice_id', 'equalto', item.id) %}
|
||||
{% for inv in invoices %}
|
||||
{{ inv.invoice_number }}<br>
|
||||
{% endfor %}
|
||||
<span class="text-muted">N/A</span>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="5" class="text-center">Нет позиций в закупке</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Информация о закупках</div>
|
||||
<p class="text-muted">Закупки связаны со спецификациями через PurchaseSpecification. Invoice относится к Purchase.</p>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('purchases_list', project_id=purchase.project_id) }}" class="btn btn-secondary">
|
||||
К списку закупок
|
||||
</a>
|
||||
<a href="{{ url_for('project_detail', project_id=purchase.project_id) }}" class="btn btn-secondary">
|
||||
К проекту
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,67 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Список закупок{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Закупки</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item active">Закупки</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{% if project_id %}
|
||||
<div class="alert alert-info">
|
||||
Фильтр: Проект #{{ project_id }}
|
||||
<a href="{{ url_for('purchases_list') }}" class="btn btn-sm btn-link">Показать все</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="section-title">Список закупок</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Номер</th>
|
||||
<th>Дата</th>
|
||||
<th>Поставщик</th>
|
||||
<th>Позиций</th>
|
||||
<th>Спецификации</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for purchase in purchases %}
|
||||
<tr>
|
||||
<td>{{ purchase.id }}</td>
|
||||
<td><a href="{{ url_for('purchase_detail', purchase_id=purchase.id) }}">{{ purchase.purchase_number }}</a></td>
|
||||
<td>{{ purchase.purchase_date.strftime('%Y-%m-%d') if purchase.purchase_date else 'N/A' }}</td>
|
||||
<td>{{ purchase.vendor.name if purchase.vendor else 'N/A' }}</td>
|
||||
<td>{{ purchase.purchase_items|length }}</td>
|
||||
<td>{{ purchase.specifications|length }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('purchase_detail', purchase_id=purchase.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="7" class="text-center">Нет закупок</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('projects_list') }}" class="btn btn-secondary">
|
||||
К проектам
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,26 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Ошибка распределения{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Ошибка распределения</h1>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-danger">
|
||||
<h4 class="alert-heading">Ошибка при распределении Resource</h4>
|
||||
<p><strong>{{ error }}</strong></p>
|
||||
<hr>
|
||||
<p class="mb-0">Пожалуйста, проверьте выбранные параметры и попробуйте снова.</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('resource_detail', resource_id=resource_id) }}" class="btn btn-primary">
|
||||
Назад к Resource
|
||||
</a>
|
||||
<a href="{{ url_for('resources_list') }}" class="btn btn-secondary">
|
||||
К пулу ресурсов
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,33 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Resource allocated{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Resource успешно распределено!</h1>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-success">
|
||||
<h4 class="alert-heading">Успех!</h4>
|
||||
<p>Resource было успешно распределено.</p>
|
||||
<hr>
|
||||
<h5>Детали:</h5>
|
||||
<ul>
|
||||
<li>Resource ID: {{ resource_id }}</li>
|
||||
<li>System: {{ allocation.system.name if allocation.system else 'N/A' }}</li>
|
||||
<li>Guardian: {{ allocation.guardian.name if allocation.guardian else 'Общая часть' }}</li>
|
||||
<li>Количество: <strong>{{ allocation.quantity }}</strong></li>
|
||||
<li>Дата: {{ allocation.allocation_date.strftime('%Y-%m-%d') if allocation.allocation_date else 'N/A' }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('resource_detail', resource_id=resource_id) }}" class="btn btn-primary">
|
||||
К Resource
|
||||
</a>
|
||||
<a href="{{ url_for('resources_list') }}" class="btn btn-secondary">
|
||||
К пулу ресурсов
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,154 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Resource #{{ resource.id }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Resource #{{ resource.id }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('resources_list') }}">Ресурсы</a></li>
|
||||
<li class="breadcrumb-item active">#{{ resource.id }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header bg-primary text-white">Получено</div>
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">{{ resource.quantity }}</h2>
|
||||
<p class="card-text">{{ resource.module.name if resource.module else 'N/A' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header bg-info text-white">Распределено</div>
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">{{ allocations|length }}</h2>
|
||||
<p class="card-text">Операций</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header bg-success text-white">Остаток</div>
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-success">{{ remaining }}</h2>
|
||||
<p class="card-text">Свободно</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header bg-secondary text-white">Происхождение</div>
|
||||
<div class="card-body">
|
||||
<p class="card-text"><strong>Invoice:</strong> {{ resource.invoice_number or 'N/A' }}</p>
|
||||
<p class="card-text"><strong>Specification:</strong> {{ resource.specification_number or 'N/A' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Распределения (ResourceAllocations)</div>
|
||||
<p class="text-muted">Resource находится в общем пуле проекта. Распределение выполняется через ResourceAllocation.</p>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>System</th>
|
||||
<th>Guardian</th>
|
||||
<th>Количество</th>
|
||||
<th>Дата</th>
|
||||
<th>Описание</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for data in allocations %}
|
||||
<tr>
|
||||
<td>{{ data.allocation.id }}</td>
|
||||
<td>{{ data.system.name if data.system else 'N/A' }}</td>
|
||||
<td>
|
||||
{% if data.is_common %}
|
||||
<span class="badge bg-info">Общая часть</span>
|
||||
{% else %}
|
||||
<a href="{{ url_for('guardian_detail', guardian_id=data.guardian.id) }}">{{ data.guardian.name if data.guardian else 'N/A' }}</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td><strong>{{ data.allocation.quantity }}</strong></td>
|
||||
<td>{{ data.allocation.allocation_date.strftime('%Y-%m-%d') if data.allocation.allocation_date else 'N/A' }}</td>
|
||||
<td>{{ data.allocation.description or 'N/A' }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="6" class="text-center">Нет распределений</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% if remaining > 0 %}
|
||||
<div class="section-title">Распределить Resource</div>
|
||||
<div class="card">
|
||||
<div class="card-header">Новое распределение</div>
|
||||
<div class="card-body">
|
||||
<form action="{{ url_for('allocate_resource', resource_id=resource.id) }}" method="GET">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Свободно: <strong>{{ remaining }}</strong></label>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="system_id">Система:</label>
|
||||
<select class="form-select" name="system_id" id="system_id" required>
|
||||
<option value="">-- Выберите систему --</option>
|
||||
{% for system in resource.project.systems %}
|
||||
<option value="{{ system.id }}">{{ system.name }} ({{ system.customer.name if system.customer else 'N/A' }})</option>
|
||||
{% else %}
|
||||
<option disabled>Нет систем в проекте</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="guardian_id">Guardian (опционально):</label>
|
||||
<select class="form-select" name="guardian_id" id="guardian_id">
|
||||
<option value="">Общая часть (NULL)</option>
|
||||
{% for system in resource.project.systems %}
|
||||
{% for guardian in system.guardians %}
|
||||
<option value="{{ guardian.id }}">{{ guardian.name }}</option>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<option disabled>Нет Guardian для выбора</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<small class="form-text text-muted">Оставьте пустым для распределения в общую часть</small>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="quantity">Количество:</label>
|
||||
<input type="number" class="form-control" name="quantity" id="quantity" min="1" max="{{ remaining }}" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary">Распределить</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-warning">
|
||||
Нет свободного ресурса для распределения.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('resources_list', project_id=resource.project_id) }}" class="btn btn-secondary">
|
||||
К пулу ресурсов
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,83 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Ресурсы - Pool{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Общий пул ресурсов</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item active">Ресурсы</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{% if project_id %}
|
||||
<div class="alert alert-info">
|
||||
Фильтр: Проект #{{ project_id }}
|
||||
<a href="{{ url_for('resources_list') }}" class="btn btn-sm btn-link">Показать все</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="section-title">Сводка ресурсов</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Module</th>
|
||||
<th>Получено</th>
|
||||
<th>Распределено</th>
|
||||
<th>Свободно</th>
|
||||
<th>Invoice</th>
|
||||
<th>Specification</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for resource in resources %}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('resource_detail', resource_id=resource.id) }}">{{ resource.id }}</a></td>
|
||||
<td>{{ resource.module.name if resource.module else 'N/A' }}</td>
|
||||
<td>{{ resource.quantity }}</td>
|
||||
<td>
|
||||
{% set allocated = resource.resource_allocations|sum(attribute='quantity', default=0) %}
|
||||
{{ allocated }}
|
||||
</td>
|
||||
<td>
|
||||
{% set allocated = resource.resource_allocations|sum(attribute='quantity', default=0) %}
|
||||
{% set remaining = resource.quantity - allocated %}
|
||||
<span class="badge {% if remaining <= 0 %}bg-danger{% elif remaining < 100 %}bg-warning{% else %}bg-success{% endif %}">
|
||||
{{ remaining }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ resource.invoice_number if resource.invoice_number else 'N/A' }}</td>
|
||||
<td>{{ resource.specification_number if resource.specification_number else 'N/A' }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('resource_detail', resource_id=resource.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="8" class="text-center">Нет ресурсов</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('projects_list') }}" class="btn btn-secondary">
|
||||
К проектам
|
||||
</a>
|
||||
{% if not project_id %}
|
||||
<a href="{{ url_for('seed_demo_data') }}" class="btn btn-success">
|
||||
Seed demo data
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,89 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ specification.specification_number }} - Спецификация{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Спецификация: {{ specification.specification_number }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('specifications_list') }}">Спецификации</a></li>
|
||||
<li class="breadcrumb-item active">{{ specification.specification_number }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">Реквизиты</div>
|
||||
<div class="card-body">
|
||||
<p><strong>ID:</strong> {{ specification.id }}</p>
|
||||
<p><strong>Номер:</strong> {{ specification.specification_number }}</p>
|
||||
<p><strong>Дата:</strong> {{ specification.specification_date.strftime('%Y-%m-%d') if specification.specification_date else 'N/A' }}</p>
|
||||
<p><strong>Договор:</strong> {{ specification.contract.contract_number if specification.contract else 'N/A' }}</p>
|
||||
<p><strong>Проект:</strong> {{ specification.project.name if specification.project else 'N/A' }}</p>
|
||||
<p><strong>Описание:</strong> {{ specification.description or 'N/A' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">Связанные закупки</div>
|
||||
<div class="card-body">
|
||||
{% if specification.purchases %}
|
||||
<ul class="list-group">
|
||||
{% for purchase in specification.purchases %}
|
||||
<li class="list-group-item">
|
||||
<a href="{{ url_for('purchase_detail', purchase_id=purchase.id) }}">{{ purchase.purchase_number }}</a>
|
||||
({{ purchase.purchase_date.strftime('%Y-%m-%d') if purchase.purchase_date else 'N/A' }})
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<div class="text-muted">Нет связанных закупок</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Позиции спецификации (SpecificationItems)</div>
|
||||
<p class="text-muted">Потребность заказчика по каждому модулю.</p>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Модуль</th>
|
||||
<th>Требуется</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in items %}
|
||||
<tr>
|
||||
<td><strong>{{ item.module.name }}</strong></td>
|
||||
<td>{{ item.quantity }}</td>
|
||||
<td>{{ item.description or 'N/A' }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="3" class="text-center">Нет позиций</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('specifications_list', project_id=specification.project_id) }}" class="btn btn-secondary">
|
||||
К списку спецификаций
|
||||
</a>
|
||||
<a href="{{ url_for('project_detail', project_id=specification.project_id) }}" class="btn btn-secondary">
|
||||
К проекту
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,65 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Список спецификаций{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Спецификации</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item active">Спецификации</li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{% if project_id %}
|
||||
<div class="alert alert-info">
|
||||
Фильтр: Проект #{{ project_id }}
|
||||
<a href="{{ url_for('specifications_list') }}" class="btn btn-sm btn-link">Показать все</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="section-title">Список спецификаций</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Номер</th>
|
||||
<th>Дата</th>
|
||||
<th>Договор</th>
|
||||
<th>Проект</th>
|
||||
<th>Позиций</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for spec in specifications %}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('specification_detail', specification_id=spec.id) }}">{{ spec.specification_number }}</a></td>
|
||||
<td>{{ spec.specification_date.strftime('%Y-%m-%d') if spec.specification_date else 'N/A' }}</td>
|
||||
<td>{{ spec.contract.contract_number if spec.contract else 'N/A' }}</td>
|
||||
<td>{{ spec.project.name if spec.project else 'N/A' }}</td>
|
||||
<td>{{ spec.specification_items|length }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('specification_detail', specification_id=spec.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="6" class="text-center">Нет спецификаций</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('projects_list') }}" class="btn btn-secondary">
|
||||
К проектам
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,122 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ system.name }} - Система{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Система: {{ system.name }}</h1>
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('home') }}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{{ url_for('systems_list') }}">Системы</a></li>
|
||||
<li class="breadcrumb-item active">{{ system.name }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<p class="text-muted">
|
||||
<strong>Заказчик:</strong> {{ system.customer.name if system.customer else 'N/A' }}<br>
|
||||
<strong>Проект:</strong> {{ system.project.name if system.project else 'N/A' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="alert alert-info">
|
||||
<strong>Структура системы:</strong>
|
||||
<pre class="mb-0" style="background: #e9ecef; padding: 10px;">System {{ system.name }}
|
||||
├── Common (guardian_id = NULL)
|
||||
│ └── Modules × N
|
||||
└── Guardians
|
||||
├── Core × 1
|
||||
└── Modules × N</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Общая часть (Common)</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Модуль</th>
|
||||
<th>Количество</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for module in common_modules %}
|
||||
<tr>
|
||||
<td>{{ module.module.name }}</td>
|
||||
<td><strong>{{ module.quantity }}</strong></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="2" class="text-center">В общей части нет модулей</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Guardians</div>
|
||||
<p class="text-muted">Каждый Guardian имеет ровно один Core и дополнительные модули.</p>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Guardian</th>
|
||||
<th>Core</th>
|
||||
<th>Модули</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for data in guardian_data %}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="{{ url_for('guardian_detail', guardian_id=data.guardian.id) }}">
|
||||
{{ data.guardian.name }}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
{% if data.core %}
|
||||
<span class="badge bg-success">{{ data.core.quantity }}</span>
|
||||
{% else %}
|
||||
<span class="badge bg-warning">Отсутствует</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if data.modules %}
|
||||
<ul class="list-unstyled mb-0">
|
||||
{% for m in data.modules %}
|
||||
<li><strong>{{ m.module.name }}</strong>: {{ m.quantity }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<span class="text-muted">Нет дополнительных модулей</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
<a href="{{ url_for('guardian_detail', guardian_id=data.guardian.id) }}" class="btn btn-sm btn-primary">
|
||||
Открыть
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="4" class="text-center">Нет Guardian</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="{{ url_for('resources_list', project_id=system.project_id) }}" class="btn btn-secondary">
|
||||
Ресурсы проекта
|
||||
</a>
|
||||
<a href="{{ url_for('project_detail', project_id=system.project_id) }}" class="btn btn-secondary">
|
||||
К проекту
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
Executable
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,438 @@
|
||||
"""
|
||||
Seed data for UI prototype demonstration.
|
||||
Creates a complete demo dataset that can be viewed manually.
|
||||
"""
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from app.models import (
|
||||
Customer, Project, ProjectCustomer, LegalEntity, System, Guardian,
|
||||
Module, SystemModule, Contract, Specification, SpecificationItem,
|
||||
Purchase, PurchaseSpecification, PurchaseItem, Invoice, Resource,
|
||||
ResourceAllocation
|
||||
)
|
||||
|
||||
|
||||
def seed_demo_data(db: Session):
|
||||
"""
|
||||
Create demo dataset for UI prototype.
|
||||
|
||||
Structure:
|
||||
- Project: Test Project
|
||||
- Customers: Customer A, Customer B
|
||||
- Systems: System 101 (Customer A), System 103 (Customer B)
|
||||
- System 103 has 3 Guardians with Core + modules
|
||||
- Common part with modules
|
||||
- Modules: Core, Agent, Camera, Tracker
|
||||
- Resources, Allocations, Specifications, Purchases
|
||||
"""
|
||||
|
||||
# Clear existing data (optional - can remove if needed)
|
||||
# db.query(ResourceAllocation).delete()
|
||||
# db.query.ResourceAllocation.delete()
|
||||
# ... (simpler to just add new data)
|
||||
|
||||
# === Create Modules ===
|
||||
# Check if modules already exist
|
||||
existing_modules = db.query(Module).all()
|
||||
if not existing_modules:
|
||||
core_module = Module(name="Core", description="Core module")
|
||||
agent_module = Module(name="Agent", description="Agent module")
|
||||
camera_module = Module(name="Camera", description="Camera module")
|
||||
tracker_module = Module(name="Tracker", description="Tracker module")
|
||||
|
||||
db.add_all([core_module, agent_module, camera_module, tracker_module])
|
||||
db.commit()
|
||||
else:
|
||||
print("Modules already exist, skipping...")
|
||||
|
||||
# === Create Project ===
|
||||
project = Project(
|
||||
name="Test Project",
|
||||
description="Demo project for UI prototype"
|
||||
)
|
||||
db.add(project)
|
||||
db.commit()
|
||||
|
||||
# === Create Customers ===
|
||||
customer_a = Customer(name="Customer A LLC", description="First customer")
|
||||
customer_b = Customer(name="Customer B Inc", description="Second customer")
|
||||
db.add_all([customer_a, customer_b])
|
||||
db.commit()
|
||||
|
||||
# Link customers to project
|
||||
db.add(ProjectCustomer(project_id=project.id, customer_id=customer_a.id))
|
||||
db.add(ProjectCustomer(project_id=project.id, customer_id=customer_b.id))
|
||||
db.commit()
|
||||
|
||||
# === Create System 101 (Customer A) ===
|
||||
system_101 = System(
|
||||
name="System 101",
|
||||
description="System for Customer A",
|
||||
project_id=project.id,
|
||||
customer_id=customer_a.id
|
||||
)
|
||||
db.add(system_101)
|
||||
db.commit()
|
||||
|
||||
# System 101: Common part
|
||||
system_module_101_common = SystemModule(
|
||||
system_id=system_101.id,
|
||||
guardian_id=None,
|
||||
module_id=agent_module.id,
|
||||
quantity=5
|
||||
)
|
||||
db.add(system_module_101_common)
|
||||
db.commit()
|
||||
|
||||
# === Create System 103 (Customer B) ===
|
||||
system_103 = System(
|
||||
name="System 103",
|
||||
description="System for Customer B",
|
||||
project_id=project.id,
|
||||
customer_id=customer_b.id
|
||||
)
|
||||
db.add(system_103)
|
||||
db.commit()
|
||||
|
||||
# System 103 Common part
|
||||
system_module_103_common_agent = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=None,
|
||||
module_id=agent_module.id,
|
||||
quantity=10
|
||||
)
|
||||
system_module_103_common_camera = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=None,
|
||||
module_id=camera_module.id,
|
||||
quantity=3002
|
||||
)
|
||||
db.add_all([system_module_103_common_agent, system_module_103_common_camera])
|
||||
db.commit()
|
||||
|
||||
# === Create Guardians for System 103 ===
|
||||
guardian_001 = Guardian(
|
||||
name="G-001",
|
||||
description="Guardian 001",
|
||||
system_id=system_103.id,
|
||||
serial_number="SER-001"
|
||||
)
|
||||
guardian_002 = Guardian(
|
||||
name="G-002",
|
||||
description="Guardian 002",
|
||||
system_id=system_103.id,
|
||||
serial_number="SER-002"
|
||||
)
|
||||
guardian_003 = Guardian(
|
||||
name="G-003",
|
||||
description="Guardian 003",
|
||||
system_id=system_103.id,
|
||||
serial_number="SER-003"
|
||||
)
|
||||
db.add_all([guardian_001, guardian_002, guardian_003])
|
||||
db.commit()
|
||||
|
||||
# Guardian 001: Core + modules
|
||||
system_module_001_core = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_001.id,
|
||||
module_id=core_module.id,
|
||||
quantity=1
|
||||
)
|
||||
system_module_001_agent = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_001.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=1
|
||||
)
|
||||
system_module_001_camera = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_001.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=60
|
||||
)
|
||||
db.add_all([system_module_001_core, system_module_001_agent, system_module_001_camera])
|
||||
db.commit()
|
||||
|
||||
# Guardian 002: Core + modules
|
||||
system_module_002_core = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_002.id,
|
||||
module_id=core_module.id,
|
||||
quantity=1
|
||||
)
|
||||
system_module_002_agent = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_002.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=1
|
||||
)
|
||||
system_module_002_camera = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_002.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=60
|
||||
)
|
||||
db.add_all([system_module_002_core, system_module_002_agent, system_module_002_camera])
|
||||
db.commit()
|
||||
|
||||
# Guardian 003: Core + modules
|
||||
system_module_003_core = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_003.id,
|
||||
module_id=core_module.id,
|
||||
quantity=1
|
||||
)
|
||||
system_module_003_camera = SystemModule(
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_003.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=72
|
||||
)
|
||||
db.add_all([system_module_003_core, system_module_003_camera])
|
||||
db.commit()
|
||||
|
||||
# === Create Contract ===
|
||||
contract = Contract(
|
||||
project_id=project.id,
|
||||
contract_number="CTR-DEMO-001",
|
||||
contract_date=date(2026, 1, 15),
|
||||
description="Demo contract"
|
||||
)
|
||||
db.add(contract)
|
||||
db.commit()
|
||||
|
||||
# === Create Specifications ===
|
||||
spec_a = Specification(
|
||||
project_id=project.id,
|
||||
contract_id=contract.id,
|
||||
specification_number="SPEC-A",
|
||||
specification_date=date(2026, 2, 1),
|
||||
description="Specification A"
|
||||
)
|
||||
spec_b = Specification(
|
||||
project_id=project.id,
|
||||
contract_id=contract.id,
|
||||
specification_number="SPEC-B",
|
||||
specification_date=date(2026, 2, 10),
|
||||
description="Specification B"
|
||||
)
|
||||
spec_c = Specification(
|
||||
project_id=project.id,
|
||||
contract_id=contract.id,
|
||||
specification_number="SPEC-C",
|
||||
specification_date=date(2026, 2, 15),
|
||||
description="Specification C"
|
||||
)
|
||||
db.add_all([spec_a, spec_b, spec_c])
|
||||
db.commit()
|
||||
|
||||
# Specification items
|
||||
spec_a_camera = SpecificationItem(
|
||||
specification_id=spec_a.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=2000,
|
||||
description="Camera for Spec A"
|
||||
)
|
||||
spec_a_agent = SpecificationItem(
|
||||
specification_id=spec_a.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=50,
|
||||
description="Agent for Spec A"
|
||||
)
|
||||
|
||||
spec_b_camera = SpecificationItem(
|
||||
specification_id=spec_b.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=1500,
|
||||
description="Camera for Spec B"
|
||||
)
|
||||
|
||||
spec_c_agent = SpecificationItem(
|
||||
specification_id=spec_c.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=215,
|
||||
description="Agent for Spec C"
|
||||
)
|
||||
db.add_all([spec_a_camera, spec_a_agent, spec_b_camera, spec_c_agent])
|
||||
db.commit()
|
||||
|
||||
# === Create Purchase ===
|
||||
from app.models import Vendor
|
||||
vendor = db.query(Vendor).filter(
|
||||
Vendor.name == "Demo Vendor"
|
||||
).first()
|
||||
if not vendor:
|
||||
from app.models import Vendor
|
||||
vendor = Vendor(
|
||||
name="Demo Vendor",
|
||||
description="Demo vendor"
|
||||
)
|
||||
db.add(vendor)
|
||||
db.commit()
|
||||
|
||||
purchase = Purchase(
|
||||
project_id=project.id,
|
||||
vendor_id=vendor.id,
|
||||
purchase_number="PO-DEMO-001",
|
||||
purchase_date=date(2026, 3, 1),
|
||||
description="Demo purchase"
|
||||
)
|
||||
db.add(purchase)
|
||||
db.commit()
|
||||
|
||||
# Purchase items
|
||||
purchase_item_camera = PurchaseItem(
|
||||
purchase_id=purchase.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=3500,
|
||||
unit_price=Decimal("100.00"),
|
||||
description="Camera purchase"
|
||||
)
|
||||
purchase_item_agent = PurchaseItem(
|
||||
purchase_id=purchase.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=500,
|
||||
unit_price=Decimal("50.00"),
|
||||
description="Agent purchase"
|
||||
)
|
||||
db.add_all([purchase_item_camera, purchase_item_agent])
|
||||
db.commit()
|
||||
|
||||
# Link Purchase to Specifications
|
||||
db.add(PurchaseSpecification(purchase_id=purchase.id, specification_id=spec_a.id))
|
||||
db.add(PurchaseSpecification(purchase_id=purchase.id, specification_id=spec_b.id))
|
||||
db.commit()
|
||||
|
||||
# === Create Invoices ===
|
||||
invoice_a = Invoice(
|
||||
purchase_id=purchase.id,
|
||||
vendor_id=vendor.id,
|
||||
invoice_number="INV-A",
|
||||
invoice_date=date(2026, 3, 5),
|
||||
amount=Decimal("200000.00"),
|
||||
description="Invoice A"
|
||||
)
|
||||
invoice_b = Invoice(
|
||||
purchase_id=purchase.id,
|
||||
vendor_id=vendor.id,
|
||||
invoice_number="INV-B",
|
||||
invoice_date=date(2026, 3, 10),
|
||||
amount=Decimal("150000.00"),
|
||||
description="Invoice B"
|
||||
)
|
||||
invoice_c = Invoice(
|
||||
purchase_id=purchase.id,
|
||||
vendor_id=vendor.id,
|
||||
invoice_number="INV-C",
|
||||
invoice_date=date(2026, 3, 15),
|
||||
amount=Decimal("25000.00"),
|
||||
description="Invoice C"
|
||||
)
|
||||
db.add_all([invoice_a, invoice_b, invoice_c])
|
||||
db.commit()
|
||||
|
||||
# === Create Resources ===
|
||||
resource_camera_2000 = Resource(
|
||||
project_id=project.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=2000,
|
||||
invoice_id=invoice_a.id,
|
||||
invoice_number="INV-A",
|
||||
invoice_date=date(2026, 3, 5),
|
||||
specification_id=spec_a.id,
|
||||
specification_number="SPEC-A",
|
||||
description="Camera received from Invoice A"
|
||||
)
|
||||
resource_camera_1500 = Resource(
|
||||
project_id=project.id,
|
||||
module_id=camera_module.id,
|
||||
quantity=1500,
|
||||
invoice_id=invoice_b.id,
|
||||
invoice_number="INV-B",
|
||||
invoice_date=date(2026, 3, 10),
|
||||
specification_id=spec_b.id,
|
||||
specification_number="SPEC-B",
|
||||
description="Camera received from Invoice B"
|
||||
)
|
||||
resource_agent_215 = Resource(
|
||||
project_id=project.id,
|
||||
module_id=agent_module.id,
|
||||
quantity=215,
|
||||
invoice_id=invoice_c.id,
|
||||
invoice_number="INV-C",
|
||||
invoice_date=date(2026, 3, 15),
|
||||
specification_id=spec_c.id,
|
||||
specification_number="SPEC-C",
|
||||
description="Agent received from Invoice C"
|
||||
)
|
||||
db.add_all([resource_camera_2000, resource_camera_1500, resource_agent_215])
|
||||
db.commit()
|
||||
|
||||
# === Create ResourceAllocations ===
|
||||
# Allocate some resources to System 103 Common
|
||||
alloc_common_agent = ResourceAllocation(
|
||||
resource_id=resource_agent_215.id,
|
||||
system_id=system_103.id,
|
||||
guardian_id=None,
|
||||
quantity=65,
|
||||
description="Allocated to Common"
|
||||
)
|
||||
|
||||
# Allocate to Guardian 001
|
||||
alloc_guardian_001 = ResourceAllocation(
|
||||
resource_id=resource_camera_2000.id,
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_001.id,
|
||||
quantity=300,
|
||||
description="Allocated to G-001"
|
||||
)
|
||||
|
||||
# Allocate to Guardian 002
|
||||
alloc_guardian_002 = ResourceAllocation(
|
||||
resource_id=resource_camera_2000.id,
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_002.id,
|
||||
quantity=500,
|
||||
description="Allocated to G-002"
|
||||
)
|
||||
|
||||
# Allocate to Guardian 003
|
||||
alloc_guardian_003 = ResourceAllocation(
|
||||
resource_id=resource_camera_1500.id,
|
||||
system_id=system_103.id,
|
||||
guardian_id=guardian_003.id,
|
||||
quantity=400,
|
||||
description="Allocated to G-003"
|
||||
)
|
||||
|
||||
# Allocate some to System 101
|
||||
alloc_system_101 = ResourceAllocation(
|
||||
resource_id=resource_agent_215.id,
|
||||
system_id=system_101.id,
|
||||
guardian_id=None,
|
||||
quantity=10,
|
||||
description="Allocated to System 101 Common"
|
||||
)
|
||||
|
||||
db.add_all([alloc_common_agent, alloc_guardian_001, alloc_guardian_002,
|
||||
alloc_guardian_003, alloc_system_101])
|
||||
db.commit()
|
||||
|
||||
print("Demo data seeded successfully!")
|
||||
print(f"Project: {project.name} (ID: {project.id})")
|
||||
print(f"Systems: 101, 103")
|
||||
print(f"Guardians: {guardian_001.name}, {guardian_002.name}, {guardian_003.name}")
|
||||
print(f"Resources: {resource_camera_2000.quantity}, {resource_camera_1500.quantity}, {resource_agent_215.quantity}")
|
||||
print(f"Allocations: 5 created")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from app.database import SessionLocal
|
||||
db = SessionLocal()
|
||||
try:
|
||||
seed_demo_data(db)
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user