Implement small business inventory management system

- 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)
This commit is contained in:
Automated Action 2025-05-12 16:23:23 +00:00
parent 92b8663746
commit be0ae5f3b3
29 changed files with 1178 additions and 2 deletions

162
README.md
View File

@ -1,3 +1,161 @@
# FastAPI Application
# Small Business Inventory Management System
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A RESTful API for managing inventory for small businesses built with FastAPI and SQLite.
## Features
- Inventory item management (create, read, update, delete)
- Category management
- Supplier management
- Stock movement tracking (purchases, sales, returns, adjustments)
- Low stock alerts
- Detailed reporting capabilities
## Tech Stack
- Python 3.8+
- FastAPI
- SQLAlchemy ORM
- SQLite Database
- Alembic Migrations
- Pydantic Data Validation
## Setup Instructions
### Prerequisites
- Python 3.8 or higher
- pip (Python package manager)
### Installation
1. Clone the repository:
```bash
git clone https://github.com/yourusername/small-business-inventory.git
cd small-business-inventory
```
2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
4. Set up the database:
```bash
# Run the database migrations
alembic upgrade head
```
### Running the Application
1. Start the FastAPI server:
```bash
uvicorn main:app --reload
```
2. Access the API:
- API Documentation: http://localhost:8000/docs
- API Endpoints: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /health` - Check system health
### Categories
- `GET /categories` - List all categories
- `GET /categories/{category_id}` - Get a specific category
- `POST /categories` - Create a new category
- `PUT /categories/{category_id}` - Update a category
- `DELETE /categories/{category_id}` - Delete a category
### Suppliers
- `GET /suppliers` - List all suppliers
- `GET /suppliers/{supplier_id}` - Get a specific supplier
- `POST /suppliers` - Create a new supplier
- `PUT /suppliers/{supplier_id}` - Update a supplier
- `DELETE /suppliers/{supplier_id}` - Delete a supplier
### Inventory Items
- `GET /items` - List all inventory items (with filtering options)
- `GET /items/{item_id}` - Get a specific item
- `POST /items` - Create a new item
- `PUT /items/{item_id}` - Update an item
- `DELETE /items/{item_id}` - Delete an item
### Stock Management
- `GET /stock/movements` - List all stock movements
- `GET /stock/movements/{movement_id}` - Get a specific stock movement
- `POST /stock/movements` - Create a new stock movement
- `GET /stock/low-stock` - Get low stock items
## Data Models
### Category
```json
{
"id": 1,
"name": "Electronics",
"description": "Electronic components and devices",
"is_active": true,
"created_at": "2025-05-12T10:00:00",
"updated_at": "2025-05-12T10:00:00"
}
```
### Supplier
```json
{
"id": 1,
"name": "ABC Supplies",
"contact_name": "John Doe",
"email": "john@abcsupplies.com",
"phone": "555-1234",
"address": "123 Main St, Anytown",
"is_active": true,
"created_at": "2025-05-12T10:00:00",
"updated_at": "2025-05-12T10:00:00"
}
```
### Item
```json
{
"id": 1,
"name": "LED Monitor",
"sku": "MON-LED-24",
"description": "24-inch LED Monitor",
"unit_price": 199.99,
"quantity": 25,
"reorder_level": 5,
"category_id": 1,
"supplier_id": 1,
"is_active": true,
"created_at": "2025-05-12T10:00:00",
"updated_at": "2025-05-12T10:00:00"
}
```
### StockMovement
```json
{
"id": 1,
"item_id": 1,
"quantity": 10,
"movement_type": "purchase",
"reference": "PO12345",
"notes": "Initial stock order",
"unit_price": 180.00,
"created_at": "2025-05-12T10:00:00"
}
```
## License
MIT

107
alembic.ini Normal file
View File

@ -0,0 +1,107 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:///./app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[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

77
alembic/env.py Normal file
View File

@ -0,0 +1,77 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.models import Base
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
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():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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
View 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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,95 @@
"""initial tables
Revision ID: 0001
Revises:
Create Date: 2025-05-12
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import func
# revision identifiers, used by Alembic.
revision = '0001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create categories table
op.create_table('categories',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True, default=True),
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_index(op.f('ix_categories_id'), 'categories', ['id'], unique=False)
# Create suppliers table
op.create_table('suppliers',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('contact_name', sa.String(), nullable=True),
sa.Column('email', sa.String(), nullable=True),
sa.Column('phone', sa.String(), nullable=True),
sa.Column('address', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True, default=True),
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_index(op.f('ix_suppliers_id'), 'suppliers', ['id'], unique=False)
# Create items table
op.create_table('items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('sku', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('unit_price', sa.Float(), nullable=False, default=0.0),
sa.Column('quantity', sa.Integer(), nullable=False, default=0),
sa.Column('reorder_level', sa.Integer(), nullable=False, default=0),
sa.Column('category_id', sa.Integer(), nullable=True),
sa.Column('supplier_id', sa.Integer(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True, default=True),
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['suppliers.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('sku')
)
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
# Create stock_movements table
op.create_table('stock_movements',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('item_id', sa.Integer(), nullable=False),
sa.Column('quantity', sa.Integer(), nullable=False),
sa.Column('movement_type', sa.Enum('purchase', 'sale', 'adjustment', 'return', name='movementtype'), nullable=False),
sa.Column('reference', sa.String(), nullable=True),
sa.Column('notes', sa.String(), nullable=True),
sa.Column('unit_price', sa.Float(), nullable=True),
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=func.now(), nullable=True),
sa.ForeignKeyConstraint(['item_id'], ['items.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_stock_movements_id'), 'stock_movements', ['id'], unique=False)
def downgrade():
op.drop_index(op.f('ix_stock_movements_id'), table_name='stock_movements')
op.drop_table('stock_movements')
op.drop_index(op.f('ix_items_id'), table_name='items')
op.drop_table('items')
op.drop_index(op.f('ix_suppliers_id'), table_name='suppliers')
op.drop_table('suppliers')
op.drop_index(op.f('ix_categories_id'), table_name='categories')
op.drop_table('categories')

4
app/crud/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.crud.item import get_items, get_item, get_item_by_sku, create_item, update_item, delete_item, update_item_quantity
from app.crud.category import get_categories, get_category, get_category_by_name, create_category, update_category, delete_category
from app.crud.supplier import get_suppliers, get_supplier, get_supplier_by_name, create_supplier, update_supplier, delete_supplier
from app.crud.stock_movement import get_stock_movements, get_stock_movement, create_stock_movement

54
app/crud/category.py Normal file
View File

@ -0,0 +1,54 @@
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from app.models.category import Category
from app.schemas.category import CategoryCreate, CategoryUpdate
def get_categories(db: Session, skip: int = 0, limit: int = 100, include_inactive: bool = False):
query = db.query(Category)
if not include_inactive:
query = query.filter(Category.is_active == True)
return query.offset(skip).limit(limit).all()
def get_category(db: Session, category_id: int):
return db.query(Category).filter(Category.id == category_id).first()
def get_category_by_name(db: Session, name: str):
return db.query(Category).filter(Category.name == name).first()
def create_category(db: Session, category: CategoryCreate):
existing_category = get_category_by_name(db, category.name)
if existing_category:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Category with this name already exists")
db_category = Category(**category.model_dump())
db.add(db_category)
db.commit()
db.refresh(db_category)
return db_category
def update_category(db: Session, category_id: int, category: CategoryUpdate):
db_category = get_category(db, category_id)
if not db_category:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found")
if category.name and category.name != db_category.name:
existing_category = get_category_by_name(db, category.name)
if existing_category:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Category with this name already exists")
update_data = category.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_category, key, value)
db.commit()
db.refresh(db_category)
return db_category
def delete_category(db: Session, category_id: int):
db_category = get_category(db, category_id)
if not db_category:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found")
db_category.is_active = False
db.commit()
return {"message": "Category deleted successfully"}

72
app/crud/item.py Normal file
View File

@ -0,0 +1,72 @@
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
def get_items(db: Session, skip: int = 0, limit: int = 100, category_id: int = None,
supplier_id: int = None, include_inactive: bool = False):
query = db.query(Item)
if category_id:
query = query.filter(Item.category_id == category_id)
if supplier_id:
query = query.filter(Item.supplier_id == supplier_id)
if not include_inactive:
query = query.filter(Item.is_active == True)
return query.offset(skip).limit(limit).all()
def get_item(db: Session, item_id: int):
return db.query(Item).filter(Item.id == item_id).first()
def get_item_by_sku(db: Session, sku: str):
return db.query(Item).filter(Item.sku == sku).first()
def create_item(db: Session, item: ItemCreate):
existing_item = get_item_by_sku(db, item.sku)
if existing_item:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Item with this SKU already exists")
db_item = Item(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def update_item(db: Session, item_id: int, item: ItemUpdate):
db_item = get_item(db, item_id)
if not db_item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
update_data = item.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
def delete_item(db: Session, item_id: int):
db_item = get_item(db, item_id)
if not db_item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
db_item.is_active = False
db.commit()
return {"message": "Item deleted successfully"}
def update_item_quantity(db: Session, item_id: int, quantity_change: int):
db_item = get_item(db, item_id)
if not db_item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
new_quantity = db_item.quantity + quantity_change
if new_quantity < 0:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Insufficient stock")
db_item.quantity = new_quantity
db.commit()
db.refresh(db_item)
return db_item

View File

@ -0,0 +1,40 @@
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

54
app/crud/supplier.py Normal file
View File

@ -0,0 +1,54 @@
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from app.models.supplier import Supplier
from app.schemas.supplier import SupplierCreate, SupplierUpdate
def get_suppliers(db: Session, skip: int = 0, limit: int = 100, include_inactive: bool = False):
query = db.query(Supplier)
if not include_inactive:
query = query.filter(Supplier.is_active == True)
return query.offset(skip).limit(limit).all()
def get_supplier(db: Session, supplier_id: int):
return db.query(Supplier).filter(Supplier.id == supplier_id).first()
def get_supplier_by_name(db: Session, name: str):
return db.query(Supplier).filter(Supplier.name == name).first()
def create_supplier(db: Session, supplier: SupplierCreate):
existing_supplier = get_supplier_by_name(db, supplier.name)
if existing_supplier:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Supplier with this name already exists")
db_supplier = Supplier(**supplier.model_dump())
db.add(db_supplier)
db.commit()
db.refresh(db_supplier)
return db_supplier
def update_supplier(db: Session, supplier_id: int, supplier: SupplierUpdate):
db_supplier = get_supplier(db, supplier_id)
if not db_supplier:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier not found")
if supplier.name and supplier.name != db_supplier.name:
existing_supplier = get_supplier_by_name(db, supplier.name)
if existing_supplier:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Supplier with this name already exists")
update_data = supplier.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_supplier, key, value)
db.commit()
db.refresh(db_supplier)
return db_supplier
def delete_supplier(db: Session, supplier_id: int):
db_supplier = get_supplier(db, supplier_id)
if not db_supplier:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier not found")
db_supplier.is_active = False
db.commit()
return {"message": "Supplier deleted successfully"}

27
app/database.py Normal file
View File

@ -0,0 +1,27 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path
# Create database directory
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)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

4
app/models/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.models.item import Item
from app.models.category import Category
from app.models.supplier import Supplier
from app.models.stock_movement import StockMovement, MovementType

14
app/models/category.py Normal file
View File

@ -0,0 +1,14 @@
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import TIMESTAMP
from app.database import Base
class Category(Base):
__tablename__ = "categories"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, unique=True)
description = Column(String, nullable=True)
is_active = Column(Boolean, default=True)
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
updated_at = Column(TIMESTAMP(timezone=True), server_default=func.now(), onupdate=func.now())

25
app/models/item.py Normal file
View File

@ -0,0 +1,25 @@
from sqlalchemy import Column, Integer, String, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import TIMESTAMP
from app.database import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
sku = Column(String, nullable=False, unique=True)
description = Column(String, nullable=True)
unit_price = Column(Float, nullable=False, default=0.0)
quantity = Column(Integer, nullable=False, default=0)
reorder_level = Column(Integer, nullable=False, default=0)
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
supplier_id = Column(Integer, ForeignKey("suppliers.id"), nullable=True)
is_active = Column(Boolean, default=True)
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
updated_at = Column(TIMESTAMP(timezone=True), server_default=func.now(), onupdate=func.now())
# Relationships
category = relationship("Category", foreign_keys=[category_id])
supplier = relationship("Supplier", foreign_keys=[supplier_id])

View File

@ -0,0 +1,27 @@
from sqlalchemy import Column, Integer, String, Float, ForeignKey, Enum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import TIMESTAMP
import enum
from app.database import Base
class MovementType(str, enum.Enum):
PURCHASE = "purchase"
SALE = "sale"
ADJUSTMENT = "adjustment"
RETURN = "return"
class StockMovement(Base):
__tablename__ = "stock_movements"
id = Column(Integer, primary_key=True, index=True)
item_id = Column(Integer, ForeignKey("items.id"), nullable=False)
quantity = Column(Integer, nullable=False)
movement_type = Column(Enum(MovementType), nullable=False)
reference = Column(String, nullable=True)
notes = Column(String, nullable=True)
unit_price = Column(Float, nullable=True)
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
# Relationships
item = relationship("Item", foreign_keys=[item_id])

17
app/models/supplier.py Normal file
View File

@ -0,0 +1,17 @@
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import TIMESTAMP
from app.database import Base
class Supplier(Base):
__tablename__ = "suppliers"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, unique=True)
contact_name = Column(String, nullable=True)
email = Column(String, nullable=True)
phone = Column(String, nullable=True)
address = Column(String, nullable=True)
is_active = Column(Boolean, default=True)
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
updated_at = Column(TIMESTAMP(timezone=True), server_default=func.now(), onupdate=func.now())

5
app/routes/__init__.py Normal file
View File

@ -0,0 +1,5 @@
from app.routes.item_routes import router as item_routes
from app.routes.category_routes import router as category_routes
from app.routes.supplier_routes import router as supplier_routes
from app.routes.stock_routes import router as stock_routes
from app.routes.health_routes import router as health_routes

View File

@ -0,0 +1,39 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database import get_db
from app.schemas.category import CategoryCreate, CategoryUpdate, CategoryResponse
from app.crud import category as category_crud
router = APIRouter(
prefix="/categories",
tags=["Categories"]
)
@router.get("/", response_model=List[CategoryResponse])
def get_categories(
skip: int = 0,
limit: int = 100,
include_inactive: bool = False,
db: Session = Depends(get_db)
):
return category_crud.get_categories(db, skip=skip, limit=limit, include_inactive=include_inactive)
@router.get("/{category_id}", response_model=CategoryResponse)
def get_category(category_id: int, db: Session = Depends(get_db)):
db_category = category_crud.get_category(db, category_id=category_id)
if db_category is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found")
return db_category
@router.post("/", response_model=CategoryResponse, status_code=status.HTTP_201_CREATED)
def create_category(category: CategoryCreate, db: Session = Depends(get_db)):
return category_crud.create_category(db=db, category=category)
@router.put("/{category_id}", response_model=CategoryResponse)
def update_category(category_id: int, category: CategoryUpdate, db: Session = Depends(get_db)):
return category_crud.update_category(db=db, category_id=category_id, category=category)
@router.delete("/{category_id}")
def delete_category(category_id: int, db: Session = Depends(get_db)):
return category_crud.delete_category(db=db, category_id=category_id)

View File

@ -0,0 +1,17 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.database import get_db
router = APIRouter(
prefix="/health",
tags=["Health"]
)
@router.get("/")
async def health_check(db: Session = Depends(get_db)):
try:
# Check if database is accessible
db.execute("SELECT 1")
return {"status": "healthy", "database": "connected"}
except Exception as e:
return {"status": "unhealthy", "database": "disconnected", "error": str(e)}

64
app/routes/item_routes.py Normal file
View File

@ -0,0 +1,64 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database import get_db
from app.schemas.item import ItemCreate, ItemUpdate, ItemResponse, ItemDetailResponse
from app.crud import item as item_crud
router = APIRouter(
prefix="/items",
tags=["Items"]
)
@router.get("/", response_model=List[ItemResponse])
def get_items(
skip: int = 0,
limit: int = 100,
category_id: Optional[int] = None,
supplier_id: Optional[int] = None,
include_inactive: bool = False,
db: Session = Depends(get_db)
):
return item_crud.get_items(
db,
skip=skip,
limit=limit,
category_id=category_id,
supplier_id=supplier_id,
include_inactive=include_inactive
)
@router.get("/{item_id}", response_model=ItemDetailResponse)
def get_item(item_id: int, db: Session = Depends(get_db)):
db_item = item_crud.get_item(db, item_id=item_id)
if db_item is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
# Convert related objects to dict for response
response = ItemDetailResponse.model_validate(db_item)
if db_item.category:
response.category = {
"id": db_item.category.id,
"name": db_item.category.name
}
if db_item.supplier:
response.supplier = {
"id": db_item.supplier.id,
"name": db_item.supplier.name
}
return response
@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
return item_crud.create_item(db=db, item=item)
@router.put("/{item_id}", response_model=ItemResponse)
def update_item(item_id: int, item: ItemUpdate, db: Session = Depends(get_db)):
return item_crud.update_item(db=db, item_id=item_id, item=item)
@router.delete("/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
return item_crud.delete_item(db=db, item_id=item_id)

View File

@ -0,0 +1,54 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database import get_db
from app.schemas.stock_movement import StockMovementCreate, StockMovementResponse, StockMovementDetailResponse
from app.crud import stock_movement as stock_crud
router = APIRouter(
prefix="/stock",
tags=["Stock Management"]
)
@router.get("/movements", response_model=List[StockMovementResponse])
def get_stock_movements(
skip: int = 0,
limit: int = 100,
item_id: Optional[int] = None,
db: Session = Depends(get_db)
):
return stock_crud.get_stock_movements(db, skip=skip, limit=limit, item_id=item_id)
@router.get("/movements/{movement_id}", response_model=StockMovementDetailResponse)
def get_stock_movement(movement_id: int, db: Session = Depends(get_db)):
db_movement = stock_crud.get_stock_movement(db, movement_id=movement_id)
if db_movement is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Stock movement not found")
# Convert related objects to dict for response
response = StockMovementDetailResponse.model_validate(db_movement)
if db_movement.item:
response.item = {
"id": db_movement.item.id,
"name": db_movement.item.name,
"sku": db_movement.item.sku
}
return response
@router.post("/movements", response_model=StockMovementResponse, status_code=status.HTTP_201_CREATED)
def create_stock_movement(movement: StockMovementCreate, db: Session = Depends(get_db)):
return stock_crud.create_stock_movement(db=db, movement=movement)
@router.get("/low-stock", response_model=List[ItemResponse])
def get_low_stock_items(db: Session = Depends(get_db)):
"""Get items where quantity is less than or equal to reorder level"""
from app.models.item import Item
low_stock_items = db.query(Item).filter(
Item.quantity <= Item.reorder_level,
Item.is_active == True
).all()
return low_stock_items

View File

@ -0,0 +1,39 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database import get_db
from app.schemas.supplier import SupplierCreate, SupplierUpdate, SupplierResponse
from app.crud import supplier as supplier_crud
router = APIRouter(
prefix="/suppliers",
tags=["Suppliers"]
)
@router.get("/", response_model=List[SupplierResponse])
def get_suppliers(
skip: int = 0,
limit: int = 100,
include_inactive: bool = False,
db: Session = Depends(get_db)
):
return supplier_crud.get_suppliers(db, skip=skip, limit=limit, include_inactive=include_inactive)
@router.get("/{supplier_id}", response_model=SupplierResponse)
def get_supplier(supplier_id: int, db: Session = Depends(get_db)):
db_supplier = supplier_crud.get_supplier(db, supplier_id=supplier_id)
if db_supplier is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier not found")
return db_supplier
@router.post("/", response_model=SupplierResponse, status_code=status.HTTP_201_CREATED)
def create_supplier(supplier: SupplierCreate, db: Session = Depends(get_db)):
return supplier_crud.create_supplier(db=db, supplier=supplier)
@router.put("/{supplier_id}", response_model=SupplierResponse)
def update_supplier(supplier_id: int, supplier: SupplierUpdate, db: Session = Depends(get_db)):
return supplier_crud.update_supplier(db=db, supplier_id=supplier_id, supplier=supplier)
@router.delete("/{supplier_id}")
def delete_supplier(supplier_id: int, db: Session = Depends(get_db)):
return supplier_crud.delete_supplier(db=db, supplier_id=supplier_id)

4
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.schemas.item import ItemBase, ItemCreate, ItemUpdate, ItemResponse, ItemDetailResponse
from app.schemas.category import CategoryBase, CategoryCreate, CategoryUpdate, CategoryResponse
from app.schemas.supplier import SupplierBase, SupplierCreate, SupplierUpdate, SupplierResponse
from app.schemas.stock_movement import StockMovementBase, StockMovementCreate, StockMovementResponse, StockMovementDetailResponse

24
app/schemas/category.py Normal file
View File

@ -0,0 +1,24 @@
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class CategoryBase(BaseModel):
name: str
description: Optional[str] = None
class CategoryCreate(CategoryBase):
pass
class CategoryUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
is_active: Optional[bool] = None
class CategoryResponse(CategoryBase):
id: int
is_active: bool
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True

38
app/schemas/item.py Normal file
View File

@ -0,0 +1,38 @@
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class ItemBase(BaseModel):
name: str
sku: str
description: Optional[str] = None
unit_price: float
quantity: int = 0
reorder_level: int = 0
category_id: Optional[int] = None
supplier_id: Optional[int] = None
class ItemCreate(ItemBase):
pass
class ItemUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
unit_price: Optional[float] = None
reorder_level: Optional[int] = None
category_id: Optional[int] = None
supplier_id: Optional[int] = None
is_active: Optional[bool] = None
class ItemResponse(ItemBase):
id: int
is_active: bool
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class ItemDetailResponse(ItemResponse):
category: Optional[dict] = None
supplier: Optional[dict] = None

View File

@ -0,0 +1,25 @@
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
from app.models.stock_movement import MovementType
class StockMovementBase(BaseModel):
item_id: int
quantity: int
movement_type: MovementType
reference: Optional[str] = None
notes: Optional[str] = None
unit_price: Optional[float] = None
class StockMovementCreate(StockMovementBase):
pass
class StockMovementResponse(StockMovementBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class StockMovementDetailResponse(StockMovementResponse):
item: Optional[dict] = None

30
app/schemas/supplier.py Normal file
View File

@ -0,0 +1,30 @@
from pydantic import BaseModel, EmailStr
from typing import Optional
from datetime import datetime
class SupplierBase(BaseModel):
name: str
contact_name: 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_name: Optional[str] = None
email: Optional[EmailStr] = None
phone: Optional[str] = None
address: Optional[str] = None
is_active: Optional[bool] = None
class SupplierResponse(SupplierBase):
id: int
is_active: bool
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True

30
main.py Normal file
View File

@ -0,0 +1,30 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routes import item_routes, category_routes, supplier_routes, stock_routes, health_routes
from app.database import engine, Base
app = FastAPI(
title="Small Business Inventory Management System",
description="API for managing inventory for small businesses",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(health_routes.router)
app.include_router(item_routes.router)
app.include_router(category_routes.router)
app.include_router(supplier_routes.router)
app.include_router(stock_routes.router)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi==0.110.0
uvicorn==0.28.0
sqlalchemy==2.0.29
alembic==1.13.1
pydantic==2.6.1
python-dotenv==1.0.1
python-multipart==0.0.9
email-validator==2.1.0