From 6f86572c7975aeb2ad68f16170b87183fe5c7228 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Fri, 20 Jun 2025 09:53:25 +0000 Subject: [PATCH] Small Business Inventory System FastAPI implementation --- README.md | 117 +++++++++++++++++++++- alembic.ini | 42 ++++++++ alembic/env.py | 55 ++++++++++ alembic/script.py.mako | 24 +++++ alembic/versions/001_initial_migration.py | 99 ++++++++++++++++++ app/__init__.py | 0 app/db/__init__.py | 0 app/db/base.py | 3 + app/db/session.py | 22 ++++ app/models/__init__.py | 0 app/models/category.py | 15 +++ app/models/product.py | 26 +++++ app/models/stock_movement.py | 23 +++++ app/models/supplier.py | 18 ++++ app/routers/__init__.py | 0 app/routers/categories.py | 52 ++++++++++ app/routers/inventory.py | 89 ++++++++++++++++ app/routers/products.py | 78 +++++++++++++++ app/routers/suppliers.py | 52 ++++++++++ app/schemas/__init__.py | 0 app/schemas/category.py | 22 ++++ app/schemas/product.py | 44 ++++++++ app/schemas/stock_movement.py | 21 ++++ app/schemas/supplier.py | 28 ++++++ main.py | 41 ++++++++ requirements.txt | 7 ++ 26 files changed, 876 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_initial_migration.py create mode 100644 app/__init__.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/category.py create mode 100644 app/models/product.py create mode 100644 app/models/stock_movement.py create mode 100644 app/models/supplier.py create mode 100644 app/routers/__init__.py create mode 100644 app/routers/categories.py create mode 100644 app/routers/inventory.py create mode 100644 app/routers/products.py create mode 100644 app/routers/suppliers.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/category.py create mode 100644 app/schemas/product.py create mode 100644 app/schemas/stock_movement.py create mode 100644 app/schemas/supplier.py create mode 100644 main.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..83ccdd9 100644 --- a/README.md +++ b/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 +``` diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..aab6a65 --- /dev/null +++ b/alembic.ini @@ -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 \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..deb00ed --- /dev/null +++ b/alembic/env.py @@ -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() \ No newline at end of file diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..37d0cac --- /dev/null +++ b/alembic/script.py.mako @@ -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"} \ No newline at end of file diff --git a/alembic/versions/001_initial_migration.py b/alembic/versions/001_initial_migration.py new file mode 100644 index 0000000..bea15bd --- /dev/null +++ b/alembic/versions/001_initial_migration.py @@ -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') \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..7c2377a --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..684d6e7 --- /dev/null +++ b/app/db/session.py @@ -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() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/models/category.py b/app/models/category.py new file mode 100644 index 0000000..11d1402 --- /dev/null +++ b/app/models/category.py @@ -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") \ No newline at end of file diff --git a/app/models/product.py b/app/models/product.py new file mode 100644 index 0000000..c7e74bd --- /dev/null +++ b/app/models/product.py @@ -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") \ No newline at end of file diff --git a/app/models/stock_movement.py b/app/models/stock_movement.py new file mode 100644 index 0000000..10d6b55 --- /dev/null +++ b/app/models/stock_movement.py @@ -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") \ No newline at end of file diff --git a/app/models/supplier.py b/app/models/supplier.py new file mode 100644 index 0000000..9cd1c5d --- /dev/null +++ b/app/models/supplier.py @@ -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") \ No newline at end of file diff --git a/app/routers/__init__.py b/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routers/categories.py b/app/routers/categories.py new file mode 100644 index 0000000..6820ce9 --- /dev/null +++ b/app/routers/categories.py @@ -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"} \ No newline at end of file diff --git a/app/routers/inventory.py b/app/routers/inventory.py new file mode 100644 index 0000000..aeb0774 --- /dev/null +++ b/app/routers/inventory.py @@ -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} \ No newline at end of file diff --git a/app/routers/products.py b/app/routers/products.py new file mode 100644 index 0000000..02a0abc --- /dev/null +++ b/app/routers/products.py @@ -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 \ No newline at end of file diff --git a/app/routers/suppliers.py b/app/routers/suppliers.py new file mode 100644 index 0000000..4c70feb --- /dev/null +++ b/app/routers/suppliers.py @@ -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"} \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/category.py b/app/schemas/category.py new file mode 100644 index 0000000..585791d --- /dev/null +++ b/app/schemas/category.py @@ -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 \ No newline at end of file diff --git a/app/schemas/product.py b/app/schemas/product.py new file mode 100644 index 0000000..0e7eb10 --- /dev/null +++ b/app/schemas/product.py @@ -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 \ No newline at end of file diff --git a/app/schemas/stock_movement.py b/app/schemas/stock_movement.py new file mode 100644 index 0000000..7bbfd3f --- /dev/null +++ b/app/schemas/stock_movement.py @@ -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 \ No newline at end of file diff --git a/app/schemas/supplier.py b/app/schemas/supplier.py new file mode 100644 index 0000000..725cb37 --- /dev/null +++ b/app/schemas/supplier.py @@ -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 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..b719d34 --- /dev/null +++ b/main.py @@ -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"} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..98f9e19 --- /dev/null +++ b/requirements.txt @@ -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 \ No newline at end of file