Small Business Inventory System FastAPI implementation
This commit is contained in:
parent
d9f1b2bc87
commit
6f86572c79
117
README.md
117
README.md
@ -1,3 +1,116 @@
|
||||
# FastAPI Application
|
||||
# Small Business Inventory System
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A comprehensive FastAPI-based inventory management system designed for small businesses to track products, manage stock levels, and monitor supplier relationships.
|
||||
|
||||
## Features
|
||||
|
||||
- **Product Management**: Complete CRUD operations for products with SKU tracking
|
||||
- **Category Management**: Organize products into categories
|
||||
- **Supplier Management**: Track supplier information and relationships
|
||||
- **Inventory Tracking**: Real-time stock level monitoring with low-stock alerts
|
||||
- **Stock Movements**: Track all inventory movements (IN/OUT/ADJUSTMENTS)
|
||||
- **Reporting**: Stock reports and analytics
|
||||
- **API Documentation**: Auto-generated OpenAPI documentation
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run the application:
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
3. Access the API documentation at: `http://localhost:8000/docs`
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Products
|
||||
- `GET /products/` - List all products (with filtering options)
|
||||
- `POST /products/` - Create a new product
|
||||
- `GET /products/{product_id}` - Get product by ID
|
||||
- `GET /products/sku/{sku}` - Get product by SKU
|
||||
- `PUT /products/{product_id}` - Update product
|
||||
- `DELETE /products/{product_id}` - Delete product
|
||||
|
||||
### Categories
|
||||
- `GET /categories/` - List all categories
|
||||
- `POST /categories/` - Create a new category
|
||||
- `GET /categories/{category_id}` - Get category by ID
|
||||
- `PUT /categories/{category_id}` - Update category
|
||||
- `DELETE /categories/{category_id}` - Delete category
|
||||
|
||||
### Suppliers
|
||||
- `GET /suppliers/` - List all suppliers
|
||||
- `POST /suppliers/` - Create a new supplier
|
||||
- `GET /suppliers/{supplier_id}` - Get supplier by ID
|
||||
- `PUT /suppliers/{supplier_id}` - Update supplier
|
||||
- `DELETE /suppliers/{supplier_id}` - Delete supplier
|
||||
|
||||
### Inventory
|
||||
- `POST /inventory/stock-movement` - Record stock movement
|
||||
- `GET /inventory/stock-movements` - List stock movements
|
||||
- `GET /inventory/low-stock` - Get low stock products
|
||||
- `GET /inventory/stock-report` - Get stock analytics
|
||||
- `PUT /inventory/adjust-stock/{product_id}` - Adjust stock levels
|
||||
|
||||
### System
|
||||
- `GET /` - API information and links
|
||||
- `GET /health` - Health check endpoint
|
||||
|
||||
## Database
|
||||
|
||||
The system uses SQLite database with the following storage structure:
|
||||
- Database file: `/app/storage/db/db.sqlite`
|
||||
|
||||
## Environment Variables
|
||||
|
||||
No environment variables are required for basic operation. The system uses SQLite with default paths.
|
||||
|
||||
## Development
|
||||
|
||||
### Database Migrations
|
||||
|
||||
The project uses Alembic for database migrations:
|
||||
|
||||
```bash
|
||||
# Run migrations
|
||||
alembic upgrade head
|
||||
|
||||
# Create new migration
|
||||
alembic revision --autogenerate -m "description"
|
||||
```
|
||||
|
||||
### Code Quality
|
||||
|
||||
The project uses Ruff for linting and formatting:
|
||||
|
||||
```bash
|
||||
# Install ruff
|
||||
pip install ruff
|
||||
|
||||
# Run linting
|
||||
ruff check .
|
||||
|
||||
# Auto-fix issues
|
||||
ruff check . --fix
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── main.py # FastAPI application entry point
|
||||
├── requirements.txt # Python dependencies
|
||||
├── alembic.ini # Alembic configuration
|
||||
├── alembic/ # Database migrations
|
||||
├── app/
|
||||
│ ├── db/ # Database configuration
|
||||
│ ├── models/ # SQLAlchemy models
|
||||
│ ├── schemas/ # Pydantic schemas
|
||||
│ └── routers/ # API route handlers
|
||||
└── storage/
|
||||
└── db/ # SQLite database storage
|
||||
```
|
||||
|
42
alembic.ini
Normal file
42
alembic.ini
Normal file
@ -0,0 +1,42 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
version_path_separator = os
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
version_locations = %(here)s/alembic/versions
|
||||
|
||||
[post_write_hooks]
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
55
alembic/env.py
Normal file
55
alembic/env.py
Normal file
@ -0,0 +1,55 @@
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
from alembic import context
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
|
||||
|
||||
from app.db.base import Base
|
||||
from app.models.category import Category
|
||||
from app.models.supplier import Supplier
|
||||
from app.models.product import Product
|
||||
from app.models.stock_movement import StockMovement
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
99
alembic/versions/001_initial_migration.py
Normal file
99
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,99 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2024-01-01 12:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create categories table
|
||||
op.create_table('categories',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_categories_id'), 'categories', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_categories_name'), 'categories', ['name'], unique=True)
|
||||
|
||||
# Create suppliers table
|
||||
op.create_table('suppliers',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('contact_person', sa.String(length=100), nullable=True),
|
||||
sa.Column('email', sa.String(length=100), nullable=True),
|
||||
sa.Column('phone', sa.String(length=20), nullable=True),
|
||||
sa.Column('address', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_suppliers_id'), 'suppliers', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_suppliers_name'), 'suppliers', ['name'], unique=True)
|
||||
op.create_index(op.f('ix_suppliers_email'), 'suppliers', ['email'], unique=True)
|
||||
|
||||
# Create products table
|
||||
op.create_table('products',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=200), nullable=False),
|
||||
sa.Column('sku', sa.String(length=100), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('price', sa.Float(), nullable=False),
|
||||
sa.Column('cost', sa.Float(), nullable=True),
|
||||
sa.Column('category_id', sa.Integer(), nullable=True),
|
||||
sa.Column('supplier_id', sa.Integer(), nullable=True),
|
||||
sa.Column('quantity_in_stock', sa.Integer(), nullable=True),
|
||||
sa.Column('min_stock_level', sa.Integer(), nullable=True),
|
||||
sa.Column('max_stock_level', sa.Integer(), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
|
||||
sa.ForeignKeyConstraint(['supplier_id'], ['suppliers.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_products_id'), 'products', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_products_name'), 'products', ['name'], unique=False)
|
||||
op.create_index(op.f('ix_products_sku'), 'products', ['sku'], unique=True)
|
||||
|
||||
# Create stock_movements table
|
||||
op.create_table('stock_movements',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('product_id', sa.Integer(), nullable=False),
|
||||
sa.Column('movement_type', sa.Enum('IN', 'OUT', 'ADJUSTMENT', name='movementtype'), nullable=False),
|
||||
sa.Column('quantity', sa.Integer(), nullable=False),
|
||||
sa.Column('reference_number', sa.String(length=100), nullable=True),
|
||||
sa.Column('notes', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.ForeignKeyConstraint(['product_id'], ['products.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_stock_movements_id'), 'stock_movements', ['id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f('ix_stock_movements_id'), table_name='stock_movements')
|
||||
op.drop_table('stock_movements')
|
||||
op.drop_index(op.f('ix_products_sku'), table_name='products')
|
||||
op.drop_index(op.f('ix_products_name'), table_name='products')
|
||||
op.drop_index(op.f('ix_products_id'), table_name='products')
|
||||
op.drop_table('products')
|
||||
op.drop_index(op.f('ix_suppliers_email'), table_name='suppliers')
|
||||
op.drop_index(op.f('ix_suppliers_name'), table_name='suppliers')
|
||||
op.drop_index(op.f('ix_suppliers_id'), table_name='suppliers')
|
||||
op.drop_table('suppliers')
|
||||
op.drop_index(op.f('ix_categories_name'), table_name='categories')
|
||||
op.drop_index(op.f('ix_categories_id'), table_name='categories')
|
||||
op.drop_table('categories')
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
22
app/db/session.py
Normal file
22
app/db/session.py
Normal file
@ -0,0 +1,22 @@
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
DB_DIR = Path("/app") / "storage" / "db"
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
15
app/models/category.py
Normal file
15
app/models/category.py
Normal file
@ -0,0 +1,15 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
class Category(Base):
|
||||
__tablename__ = "categories"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, index=True, nullable=False)
|
||||
description = Column(Text)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
products = relationship("Product", back_populates="category")
|
26
app/models/product.py
Normal file
26
app/models/product.py
Normal file
@ -0,0 +1,26 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
class Product(Base):
|
||||
__tablename__ = "products"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(200), index=True, nullable=False)
|
||||
sku = Column(String(100), unique=True, index=True, nullable=False)
|
||||
description = Column(Text)
|
||||
price = Column(Float, nullable=False)
|
||||
cost = Column(Float)
|
||||
category_id = Column(Integer, ForeignKey("categories.id"))
|
||||
supplier_id = Column(Integer, ForeignKey("suppliers.id"))
|
||||
quantity_in_stock = Column(Integer, default=0)
|
||||
min_stock_level = Column(Integer, default=0)
|
||||
max_stock_level = Column(Integer)
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
category = relationship("Category", back_populates="products")
|
||||
supplier = relationship("Supplier", back_populates="products")
|
||||
stock_movements = relationship("StockMovement", back_populates="product")
|
23
app/models/stock_movement.py
Normal file
23
app/models/stock_movement.py
Normal file
@ -0,0 +1,23 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
import enum
|
||||
|
||||
class MovementType(enum.Enum):
|
||||
IN = "in"
|
||||
OUT = "out"
|
||||
ADJUSTMENT = "adjustment"
|
||||
|
||||
class StockMovement(Base):
|
||||
__tablename__ = "stock_movements"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
||||
movement_type = Column(Enum(MovementType), nullable=False)
|
||||
quantity = Column(Integer, nullable=False)
|
||||
reference_number = Column(String(100))
|
||||
notes = Column(Text)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
product = relationship("Product", back_populates="stock_movements")
|
18
app/models/supplier.py
Normal file
18
app/models/supplier.py
Normal file
@ -0,0 +1,18 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
class Supplier(Base):
|
||||
__tablename__ = "suppliers"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, index=True, nullable=False)
|
||||
contact_person = Column(String(100))
|
||||
email = Column(String(100), unique=True, index=True)
|
||||
phone = Column(String(20))
|
||||
address = Column(Text)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
products = relationship("Product", back_populates="supplier")
|
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
52
app/routers/categories.py
Normal file
52
app/routers/categories.py
Normal file
@ -0,0 +1,52 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from app.db.session import get_db
|
||||
from app.models.category import Category
|
||||
from app.schemas.category import Category as CategorySchema, CategoryCreate, CategoryUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", response_model=CategorySchema)
|
||||
def create_category(category: CategoryCreate, db: Session = Depends(get_db)):
|
||||
db_category = Category(**category.dict())
|
||||
db.add(db_category)
|
||||
db.commit()
|
||||
db.refresh(db_category)
|
||||
return db_category
|
||||
|
||||
@router.get("/", response_model=List[CategorySchema])
|
||||
def read_categories(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
categories = db.query(Category).offset(skip).limit(limit).all()
|
||||
return categories
|
||||
|
||||
@router.get("/{category_id}", response_model=CategorySchema)
|
||||
def read_category(category_id: int, db: Session = Depends(get_db)):
|
||||
category = db.query(Category).filter(Category.id == category_id).first()
|
||||
if category is None:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
return category
|
||||
|
||||
@router.put("/{category_id}", response_model=CategorySchema)
|
||||
def update_category(category_id: int, category: CategoryUpdate, db: Session = Depends(get_db)):
|
||||
db_category = db.query(Category).filter(Category.id == category_id).first()
|
||||
if db_category is None:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
|
||||
update_data = category.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_category, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_category)
|
||||
return db_category
|
||||
|
||||
@router.delete("/{category_id}")
|
||||
def delete_category(category_id: int, db: Session = Depends(get_db)):
|
||||
db_category = db.query(Category).filter(Category.id == category_id).first()
|
||||
if db_category is None:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
|
||||
db.delete(db_category)
|
||||
db.commit()
|
||||
return {"message": "Category deleted successfully"}
|
89
app/routers/inventory.py
Normal file
89
app/routers/inventory.py
Normal file
@ -0,0 +1,89 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from app.db.session import get_db
|
||||
from app.models.product import Product
|
||||
from app.models.stock_movement import StockMovement, MovementType
|
||||
from app.schemas.stock_movement import StockMovement as StockMovementSchema, StockMovementCreate
|
||||
from app.schemas.product import Product as ProductSchema
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/stock-movement", response_model=StockMovementSchema)
|
||||
def create_stock_movement(movement: StockMovementCreate, db: Session = Depends(get_db)):
|
||||
product = db.query(Product).filter(Product.id == movement.product_id).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
db_movement = StockMovement(**movement.dict())
|
||||
db.add(db_movement)
|
||||
|
||||
if movement.movement_type == MovementType.IN:
|
||||
product.quantity_in_stock += movement.quantity
|
||||
elif movement.movement_type == MovementType.OUT:
|
||||
if product.quantity_in_stock < movement.quantity:
|
||||
raise HTTPException(status_code=400, detail="Insufficient stock")
|
||||
product.quantity_in_stock -= movement.quantity
|
||||
elif movement.movement_type == MovementType.ADJUSTMENT:
|
||||
product.quantity_in_stock = movement.quantity
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_movement)
|
||||
return db_movement
|
||||
|
||||
@router.get("/stock-movements", response_model=List[StockMovementSchema])
|
||||
def read_stock_movements(skip: int = 0, limit: int = 100, product_id: int = None, db: Session = Depends(get_db)):
|
||||
query = db.query(StockMovement)
|
||||
if product_id:
|
||||
query = query.filter(StockMovement.product_id == product_id)
|
||||
movements = query.order_by(StockMovement.created_at.desc()).offset(skip).limit(limit).all()
|
||||
return movements
|
||||
|
||||
@router.get("/low-stock", response_model=List[ProductSchema])
|
||||
def get_low_stock_products(db: Session = Depends(get_db)):
|
||||
products = db.query(Product).filter(
|
||||
Product.quantity_in_stock <= Product.min_stock_level,
|
||||
Product.is_active == True
|
||||
).all()
|
||||
return products
|
||||
|
||||
@router.get("/stock-report")
|
||||
def get_stock_report(db: Session = Depends(get_db)):
|
||||
total_products = db.query(Product).filter(Product.is_active == True).count()
|
||||
low_stock_count = db.query(Product).filter(
|
||||
Product.quantity_in_stock <= Product.min_stock_level,
|
||||
Product.is_active == True
|
||||
).count()
|
||||
out_of_stock_count = db.query(Product).filter(
|
||||
Product.quantity_in_stock == 0,
|
||||
Product.is_active == True
|
||||
).count()
|
||||
|
||||
total_stock_value = db.query(Product).filter(Product.is_active == True).all()
|
||||
total_value = sum(p.quantity_in_stock * (p.cost or 0) for p in total_stock_value)
|
||||
|
||||
return {
|
||||
"total_products": total_products,
|
||||
"low_stock_products": low_stock_count,
|
||||
"out_of_stock_products": out_of_stock_count,
|
||||
"total_stock_value": total_value
|
||||
}
|
||||
|
||||
@router.put("/adjust-stock/{product_id}")
|
||||
def adjust_stock(product_id: int, new_quantity: int, notes: str = None, 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")
|
||||
|
||||
movement = StockMovement(
|
||||
product_id=product_id,
|
||||
movement_type=MovementType.ADJUSTMENT,
|
||||
quantity=new_quantity,
|
||||
notes=notes or f"Stock adjusted to {new_quantity}"
|
||||
)
|
||||
|
||||
db.add(movement)
|
||||
product.quantity_in_stock = new_quantity
|
||||
db.commit()
|
||||
|
||||
return {"message": f"Stock adjusted to {new_quantity}", "new_quantity": new_quantity}
|
78
app/routers/products.py
Normal file
78
app/routers/products.py
Normal file
@ -0,0 +1,78 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
from app.db.session import get_db
|
||||
from app.models.product import Product
|
||||
from app.schemas.product import Product as ProductSchema, ProductCreate, ProductUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", response_model=ProductSchema)
|
||||
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.get("/", response_model=List[ProductSchema])
|
||||
def read_products(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
category_id: Optional[int] = Query(None),
|
||||
supplier_id: Optional[int] = Query(None),
|
||||
is_active: Optional[bool] = Query(None),
|
||||
low_stock: Optional[bool] = Query(None),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
query = db.query(Product)
|
||||
|
||||
if category_id:
|
||||
query = query.filter(Product.category_id == category_id)
|
||||
if supplier_id:
|
||||
query = query.filter(Product.supplier_id == supplier_id)
|
||||
if is_active is not None:
|
||||
query = query.filter(Product.is_active == is_active)
|
||||
if low_stock:
|
||||
query = query.filter(Product.quantity_in_stock <= Product.min_stock_level)
|
||||
|
||||
products = query.offset(skip).limit(limit).all()
|
||||
return products
|
||||
|
||||
@router.get("/{product_id}", response_model=ProductSchema)
|
||||
def read_product(product_id: int, db: Session = Depends(get_db)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if product is None:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
return product
|
||||
|
||||
@router.put("/{product_id}", response_model=ProductSchema)
|
||||
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 db_product is None:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
update_data = product.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_product, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_product)
|
||||
return db_product
|
||||
|
||||
@router.delete("/{product_id}")
|
||||
def delete_product(product_id: int, db: Session = Depends(get_db)):
|
||||
db_product = db.query(Product).filter(Product.id == product_id).first()
|
||||
if db_product is None:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
db.delete(db_product)
|
||||
db.commit()
|
||||
return {"message": "Product deleted successfully"}
|
||||
|
||||
@router.get("/sku/{sku}", response_model=ProductSchema)
|
||||
def read_product_by_sku(sku: str, db: Session = Depends(get_db)):
|
||||
product = db.query(Product).filter(Product.sku == sku).first()
|
||||
if product is None:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
return product
|
52
app/routers/suppliers.py
Normal file
52
app/routers/suppliers.py
Normal file
@ -0,0 +1,52 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from app.db.session import get_db
|
||||
from app.models.supplier import Supplier
|
||||
from app.schemas.supplier import Supplier as SupplierSchema, SupplierCreate, SupplierUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", response_model=SupplierSchema)
|
||||
def create_supplier(supplier: SupplierCreate, db: Session = Depends(get_db)):
|
||||
db_supplier = Supplier(**supplier.dict())
|
||||
db.add(db_supplier)
|
||||
db.commit()
|
||||
db.refresh(db_supplier)
|
||||
return db_supplier
|
||||
|
||||
@router.get("/", response_model=List[SupplierSchema])
|
||||
def read_suppliers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
suppliers = db.query(Supplier).offset(skip).limit(limit).all()
|
||||
return suppliers
|
||||
|
||||
@router.get("/{supplier_id}", response_model=SupplierSchema)
|
||||
def read_supplier(supplier_id: int, db: Session = Depends(get_db)):
|
||||
supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
|
||||
if supplier is None:
|
||||
raise HTTPException(status_code=404, detail="Supplier not found")
|
||||
return supplier
|
||||
|
||||
@router.put("/{supplier_id}", response_model=SupplierSchema)
|
||||
def update_supplier(supplier_id: int, supplier: SupplierUpdate, db: Session = Depends(get_db)):
|
||||
db_supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
|
||||
if db_supplier is None:
|
||||
raise HTTPException(status_code=404, detail="Supplier not found")
|
||||
|
||||
update_data = supplier.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_supplier, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_supplier)
|
||||
return db_supplier
|
||||
|
||||
@router.delete("/{supplier_id}")
|
||||
def delete_supplier(supplier_id: int, db: Session = Depends(get_db)):
|
||||
db_supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
|
||||
if db_supplier is None:
|
||||
raise HTTPException(status_code=404, detail="Supplier not found")
|
||||
|
||||
db.delete(db_supplier)
|
||||
db.commit()
|
||||
return {"message": "Supplier deleted successfully"}
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
22
app/schemas/category.py
Normal file
22
app/schemas/category.py
Normal file
@ -0,0 +1,22 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
class CategoryBase(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class CategoryCreate(CategoryBase):
|
||||
pass
|
||||
|
||||
class CategoryUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class Category(CategoryBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
44
app/schemas/product.py
Normal file
44
app/schemas/product.py
Normal file
@ -0,0 +1,44 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from app.schemas.category import Category
|
||||
from app.schemas.supplier import Supplier
|
||||
|
||||
class ProductBase(BaseModel):
|
||||
name: str
|
||||
sku: str
|
||||
description: Optional[str] = None
|
||||
price: float
|
||||
cost: Optional[float] = None
|
||||
category_id: Optional[int] = None
|
||||
supplier_id: Optional[int] = None
|
||||
quantity_in_stock: int = 0
|
||||
min_stock_level: int = 0
|
||||
max_stock_level: Optional[int] = None
|
||||
is_active: bool = True
|
||||
|
||||
class ProductCreate(ProductBase):
|
||||
pass
|
||||
|
||||
class ProductUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
sku: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
price: Optional[float] = None
|
||||
cost: Optional[float] = None
|
||||
category_id: Optional[int] = None
|
||||
supplier_id: Optional[int] = None
|
||||
quantity_in_stock: Optional[int] = None
|
||||
min_stock_level: Optional[int] = None
|
||||
max_stock_level: Optional[int] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
class Product(ProductBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
category: Optional[Category] = None
|
||||
supplier: Optional[Supplier] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
21
app/schemas/stock_movement.py
Normal file
21
app/schemas/stock_movement.py
Normal file
@ -0,0 +1,21 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from app.models.stock_movement import MovementType
|
||||
|
||||
class StockMovementBase(BaseModel):
|
||||
product_id: int
|
||||
movement_type: MovementType
|
||||
quantity: int
|
||||
reference_number: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
class StockMovementCreate(StockMovementBase):
|
||||
pass
|
||||
|
||||
class StockMovement(StockMovementBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
28
app/schemas/supplier.py
Normal file
28
app/schemas/supplier.py
Normal file
@ -0,0 +1,28 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
class SupplierBase(BaseModel):
|
||||
name: str
|
||||
contact_person: Optional[str] = None
|
||||
email: Optional[EmailStr] = None
|
||||
phone: Optional[str] = None
|
||||
address: Optional[str] = None
|
||||
|
||||
class SupplierCreate(SupplierBase):
|
||||
pass
|
||||
|
||||
class SupplierUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
contact_person: Optional[str] = None
|
||||
email: Optional[EmailStr] = None
|
||||
phone: Optional[str] = None
|
||||
address: Optional[str] = None
|
||||
|
||||
class Supplier(SupplierBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
41
main.py
Normal file
41
main.py
Normal file
@ -0,0 +1,41 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.routers import products, categories, suppliers, inventory
|
||||
from app.db.session import engine
|
||||
from app.db.base import Base
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="Small Business Inventory System",
|
||||
description="A comprehensive inventory management system for small businesses",
|
||||
version="1.0.0",
|
||||
openapi_url="/openapi.json"
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(products.router, prefix="/products", tags=["products"])
|
||||
app.include_router(categories.router, prefix="/categories", tags=["categories"])
|
||||
app.include_router(suppliers.router, prefix="/suppliers", tags=["suppliers"])
|
||||
app.include_router(inventory.router, prefix="/inventory", tags=["inventory"])
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"title": "Small Business Inventory System",
|
||||
"description": "A comprehensive inventory management system for small businesses",
|
||||
"version": "1.0.0",
|
||||
"documentation": "/docs",
|
||||
"health_check": "/health"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy", "service": "inventory-system"}
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -0,0 +1,7 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
alembic==1.12.1
|
||||
pydantic==2.5.0
|
||||
python-multipart==0.0.6
|
||||
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user