63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from .. import models, schemas
|
|
from ..database import get_db
|
|
|
|
router = APIRouter(
|
|
prefix="/operations",
|
|
tags=["Operations"]
|
|
)
|
|
|
|
@router.post("/check-in", response_model=schemas.Item)
|
|
def check_in_item(op: schemas.OperationCreate, db: Session = Depends(get_db)):
|
|
if op.quantity <= 0:
|
|
raise HTTPException(status_code=400, detail="Quantity must be greater than zero")
|
|
|
|
item = db.query(models.Item).filter(models.Item.barcode == op.barcode).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found. Register item first.")
|
|
|
|
# Update quantity
|
|
item.quantity += op.quantity
|
|
|
|
# Create Mandatory Audit Log
|
|
audit = models.AuditLog(
|
|
user_id=op.user_id,
|
|
action="CHECK_IN",
|
|
target_item_id=item.id,
|
|
quantity_change=op.quantity
|
|
)
|
|
|
|
db.add(audit)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
@router.post("/check-out", response_model=schemas.Item)
|
|
def check_out_item(op: schemas.OperationCreate, db: Session = Depends(get_db)):
|
|
if op.quantity <= 0:
|
|
raise HTTPException(status_code=400, detail="Quantity must be greater than zero")
|
|
|
|
item = db.query(models.Item).filter(models.Item.barcode == op.barcode).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
if item.quantity < op.quantity:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Insufficient stock")
|
|
|
|
# Update quantity
|
|
item.quantity -= op.quantity
|
|
|
|
# Create Mandatory Audit Log
|
|
audit = models.AuditLog(
|
|
user_id=op.user_id,
|
|
action="CHECK_OUT",
|
|
target_item_id=item.id,
|
|
quantity_change=-op.quantity
|
|
)
|
|
|
|
db.add(audit)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|