
- Create project structure with FastAPI and SQLAlchemy - Implement database models for items, categories, suppliers, and stock movements - Add CRUD operations for all models - Configure Alembic for database migrations - Create RESTful API endpoints for inventory management - Add health endpoint for system monitoring - Update README with setup and usage instructions generated with BackendIM... (backend.im)
40 lines
1.5 KiB
Python
40 lines
1.5 KiB
Python
from sqlalchemy.orm import Session
|
|
from fastapi import HTTPException, status
|
|
from app.models.stock_movement import StockMovement
|
|
from app.schemas.stock_movement import StockMovementCreate
|
|
from app.crud.item import update_item_quantity, get_item
|
|
|
|
def get_stock_movements(db: Session, skip: int = 0, limit: int = 100, item_id: int = None):
|
|
query = db.query(StockMovement)
|
|
|
|
if item_id:
|
|
query = query.filter(StockMovement.item_id == item_id)
|
|
|
|
return query.order_by(StockMovement.created_at.desc()).offset(skip).limit(limit).all()
|
|
|
|
def get_stock_movement(db: Session, movement_id: int):
|
|
return db.query(StockMovement).filter(StockMovement.id == movement_id).first()
|
|
|
|
def create_stock_movement(db: Session, movement: StockMovementCreate):
|
|
# Check if item exists
|
|
item = get_item(db, movement.item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
|
|
|
|
# Create stock movement record
|
|
db_movement = StockMovement(**movement.model_dump())
|
|
db.add(db_movement)
|
|
|
|
# Update item quantity based on movement type
|
|
quantity_change = movement.quantity
|
|
if movement.movement_type in ["sale", "adjustment"] and quantity_change > 0:
|
|
quantity_change = -quantity_change
|
|
elif movement.movement_type in ["purchase", "return"] and quantity_change < 0:
|
|
quantity_change = abs(quantity_change)
|
|
|
|
# Update the item quantity
|
|
update_item_quantity(db, movement.item_id, quantity_change)
|
|
|
|
db.commit()
|
|
db.refresh(db_movement)
|
|
return db_movement |