diff --git a/README.md b/README.md index e8acfba..5ade8d0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,141 @@ -# FastAPI Application +# Small Business Inventory System -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A comprehensive inventory management system built with FastAPI and SQLite, designed for small businesses. + +## Features + +- **User Authentication**: Secure login and user management system +- **Item Management**: Create, read, update, and delete inventory items +- **Category Management**: Organize items by categories +- **Supplier Management**: Keep track of item suppliers +- **Transaction Management**: Record stock movements (in/out/adjustments) +- **API Documentation**: Interactive API documentation with Swagger UI + +## Technology Stack + +- **Backend**: FastAPI (Python) +- **Database**: SQLite with SQLAlchemy ORM +- **Migration**: Alembic for database migrations +- **Authentication**: JWT token-based authentication +- **Documentation**: Swagger UI and ReDoc + +## Project Structure + +``` +. +├── app/ +│ ├── api/ +│ │ ├── deps.py # API dependencies +│ │ └── v1/ # API v1 endpoints +│ │ ├── endpoints/ # Individual endpoint modules +│ │ └── api.py # API router +│ ├── core/ # Core modules +│ │ ├── config.py # Settings and configuration +│ │ └── security.py # Security utilities +│ ├── db/ # Database utilities +│ │ ├── base.py # SQLAlchemy declarative base +│ │ └── session.py # Database session management +│ ├── models/ # SQLAlchemy models +│ └── schemas/ # Pydantic schemas +├── migrations/ # Alembic migrations +├── alembic.ini # Alembic configuration +├── main.py # Application entry point +└── requirements.txt # Project dependencies +``` + +## Setup and Installation + +### Prerequisites + +- Python 3.8 or higher + +### Installation + +1. Clone the repository: + ``` + git clone https://github.com/yourusername/smallbusinessinventorysystem.git + cd smallbusinessinventorysystem + ``` + +2. Install dependencies: + ``` + pip install -r requirements.txt + ``` + +3. Set up environment variables: + ``` + # Create a .env file with the following variables (optional) + SECRET_KEY=your-secret-key + ``` + +4. Initialize the database: + ``` + alembic upgrade head + ``` + +5. Run the application: + ``` + uvicorn main:app --reload + ``` + +## API Documentation + +Once the application is running, you can access: + +- Interactive API documentation: [http://localhost:8000/docs](http://localhost:8000/docs) +- Alternative documentation: [http://localhost:8000/redoc](http://localhost:8000/redoc) + +## Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| PROJECT_NAME | Name of the project | Small Business Inventory System | +| SECRET_KEY | Secret key for JWT encoding | supersecretkey (change in production!) | +| ACCESS_TOKEN_EXPIRE_MINUTES | JWT token expiration time | 30 | + +## Database + +The application uses SQLite as the database, stored at `/app/storage/db/db.sqlite`. This location can be configured through environment variables if needed. + +## API Endpoints + +### Authentication +- `POST /api/v1/login/access-token` - Get access token + +### Users +- `GET /api/v1/users/` - List users (admin only) +- `POST /api/v1/users/` - Create user (admin only) +- `GET /api/v1/users/me` - Get current user +- `PUT /api/v1/users/me` - Update current user +- `GET /api/v1/users/{user_id}` - Get user by ID +- `PUT /api/v1/users/{user_id}` - Update user (admin only) + +### Categories +- `GET /api/v1/categories/` - List categories +- `POST /api/v1/categories/` - Create category +- `GET /api/v1/categories/{category_id}` - Get category by ID +- `PUT /api/v1/categories/{category_id}` - Update category +- `DELETE /api/v1/categories/{category_id}` - Delete category + +### Suppliers +- `GET /api/v1/suppliers/` - List suppliers +- `POST /api/v1/suppliers/` - Create supplier +- `GET /api/v1/suppliers/{supplier_id}` - Get supplier by ID +- `PUT /api/v1/suppliers/{supplier_id}` - Update supplier +- `DELETE /api/v1/suppliers/{supplier_id}` - Delete supplier + +### Items +- `GET /api/v1/items/` - List items +- `POST /api/v1/items/` - Create item +- `GET /api/v1/items/{item_id}` - Get item by ID +- `PUT /api/v1/items/{item_id}` - Update item +- `DELETE /api/v1/items/{item_id}` - Delete item + +### Transactions +- `GET /api/v1/transactions/` - List transactions +- `POST /api/v1/transactions/` - Create transaction +- `GET /api/v1/transactions/{transaction_id}` - Get transaction by ID + +## Health Check +- `GET /health` - Check system health +- `GET /` - Basic service information \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..e85c93d --- /dev/null +++ b/alembic.ini @@ -0,0 +1,74 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# 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 +# version_locations = %(here)s/bar %(here)s/bat alembic/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite database URL +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +# 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 \ 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/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..e50208b --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,62 @@ +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import jwt, JWTError +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.models.user import User +from app.core.config import settings +from app.schemas.token import TokenPayload + +oauth2_scheme = OAuth2PasswordBearer( + tokenUrl=f"{settings.API_V1_STR}/login/access-token" +) + + +def get_current_user( + db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) +) -> User: + """ + Validate and decode token to get current user. + """ + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = TokenPayload(**payload) + except (JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Could not validate credentials", + ) + user = db.query(User).filter(User.id == token_data.sub).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + if not user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + return user + + +def get_current_active_user( + current_user: User = Depends(get_current_user), +) -> User: + """ + Get current active user. + """ + if not current_user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + return current_user + + +def get_current_active_superuser( + current_user: User = Depends(get_current_user), +) -> User: + """ + Get current active superuser. + """ + if not current_user.is_superuser: + raise HTTPException( + status_code=403, detail="The user doesn't have enough privileges" + ) + return current_user \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..868b9e4 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,11 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import items, categories, suppliers, transactions, login, users + +api_router = APIRouter() +api_router.include_router(login.router, tags=["login"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(items.router, prefix="/items", tags=["items"]) +api_router.include_router(categories.router, prefix="/categories", tags=["categories"]) +api_router.include_router(suppliers.router, prefix="/suppliers", tags=["suppliers"]) +api_router.include_router(transactions.router, prefix="/transactions", tags=["transactions"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/categories.py b/app/api/v1/endpoints/categories.py new file mode 100644 index 0000000..be1ce5f --- /dev/null +++ b/app/api/v1/endpoints/categories.py @@ -0,0 +1,110 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user, get_db +from app.models.category import Category +from app.models.user import User +from app.schemas.category import Category as CategorySchema, CategoryCreate, CategoryUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[CategorySchema]) +def read_categories( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Retrieve categories. + """ + categories = db.query(Category).offset(skip).limit(limit).all() + return categories + + +@router.post("/", response_model=CategorySchema) +def create_category( + *, + db: Session = Depends(get_db), + category_in: CategoryCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new category. + """ + category = Category(**category_in.dict()) + db.add(category) + db.commit() + db.refresh(category) + return category + + +@router.put("/{category_id}", response_model=CategorySchema) +def update_category( + *, + db: Session = Depends(get_db), + category_id: int, + category_in: CategoryUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update a category. + """ + category = db.query(Category).filter(Category.id == category_id).first() + if not category: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Category not found", + ) + + update_data = category_in.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(category, field, value) + + db.add(category) + db.commit() + db.refresh(category) + return category + + +@router.get("/{category_id}", response_model=CategorySchema) +def read_category( + *, + db: Session = Depends(get_db), + category_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get category by ID. + """ + category = db.query(Category).filter(Category.id == category_id).first() + if not category: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Category not found", + ) + return category + + +@router.delete("/{category_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_category( + *, + db: Session = Depends(get_db), + category_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Delete a category. + """ + category = db.query(Category).filter(Category.id == category_id).first() + if not category: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Category not found", + ) + db.delete(category) + db.commit() + return None \ No newline at end of file diff --git a/app/api/v1/endpoints/items.py b/app/api/v1/endpoints/items.py new file mode 100644 index 0000000..024d13c --- /dev/null +++ b/app/api/v1/endpoints/items.py @@ -0,0 +1,126 @@ +from typing import Any, List, Optional + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user, get_db +from app.models.item import Item +from app.models.user import User +from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[ItemSchema]) +def read_items( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + category_id: Optional[int] = None, + supplier_id: Optional[int] = None, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Retrieve inventory items. + """ + query = db.query(Item) + + # Filter by owner + query = query.filter(Item.owner_id == current_user.id) + + # Apply additional filters if provided + if category_id: + query = query.filter(Item.category_id == category_id) + if supplier_id: + query = query.filter(Item.supplier_id == supplier_id) + + items = query.offset(skip).limit(limit).all() + return items + + +@router.post("/", response_model=ItemSchema) +def create_item( + *, + db: Session = Depends(get_db), + item_in: ItemCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new item. + """ + item = Item( + **item_in.dict(), + owner_id=current_user.id + ) + db.add(item) + db.commit() + db.refresh(item) + return item + + +@router.put("/{item_id}", response_model=ItemSchema) +def update_item( + *, + db: Session = Depends(get_db), + item_id: int, + item_in: ItemUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update an item. + """ + item = db.query(Item).filter(Item.id == item_id, Item.owner_id == current_user.id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + + update_data = item_in.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(item, field, value) + + db.add(item) + db.commit() + db.refresh(item) + return item + + +@router.get("/{item_id}", response_model=ItemSchema) +def read_item( + *, + db: Session = Depends(get_db), + item_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get item by ID. + """ + item = db.query(Item).filter(Item.id == item_id, Item.owner_id == current_user.id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + return item + + +@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_item( + *, + db: Session = Depends(get_db), + item_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Delete an item. + """ + item = db.query(Item).filter(Item.id == item_id, Item.owner_id == current_user.id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + db.delete(item) + db.commit() + return None \ No newline at end of file diff --git a/app/api/v1/endpoints/login.py b/app/api/v1/endpoints/login.py new file mode 100644 index 0000000..583d909 --- /dev/null +++ b/app/api/v1/endpoints/login.py @@ -0,0 +1,40 @@ +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session + +from app.api.deps import get_db +from app.core.config import settings +from app.core.security import create_access_token, verify_password +from app.schemas.token import Token +from app.models.user import User + +router = APIRouter() + + +@router.post("/login/access-token", response_model=Token) +def login_access_token( + db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends() +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests + """ + user = db.query(User).filter(User.email == form_data.username).first() + if not user or not verify_password(form_data.password, user.hashed_password): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Incorrect email or password", + ) + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user" + ) + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + return { + "access_token": create_access_token( + user.id, expires_delta=access_token_expires + ), + "token_type": "bearer", + } \ No newline at end of file diff --git a/app/api/v1/endpoints/suppliers.py b/app/api/v1/endpoints/suppliers.py new file mode 100644 index 0000000..521dc9d --- /dev/null +++ b/app/api/v1/endpoints/suppliers.py @@ -0,0 +1,110 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user, get_db +from app.models.supplier import Supplier +from app.models.user import User +from app.schemas.supplier import Supplier as SupplierSchema, SupplierCreate, SupplierUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[SupplierSchema]) +def read_suppliers( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Retrieve suppliers. + """ + suppliers = db.query(Supplier).offset(skip).limit(limit).all() + return suppliers + + +@router.post("/", response_model=SupplierSchema) +def create_supplier( + *, + db: Session = Depends(get_db), + supplier_in: SupplierCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new supplier. + """ + supplier = Supplier(**supplier_in.dict()) + db.add(supplier) + db.commit() + db.refresh(supplier) + return supplier + + +@router.put("/{supplier_id}", response_model=SupplierSchema) +def update_supplier( + *, + db: Session = Depends(get_db), + supplier_id: int, + supplier_in: SupplierUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update a supplier. + """ + supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first() + if not supplier: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Supplier not found", + ) + + update_data = supplier_in.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(supplier, field, value) + + db.add(supplier) + db.commit() + db.refresh(supplier) + return supplier + + +@router.get("/{supplier_id}", response_model=SupplierSchema) +def read_supplier( + *, + db: Session = Depends(get_db), + supplier_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get supplier by ID. + """ + supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first() + if not supplier: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Supplier not found", + ) + return supplier + + +@router.delete("/{supplier_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_supplier( + *, + db: Session = Depends(get_db), + supplier_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Delete a supplier. + """ + supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first() + if not supplier: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Supplier not found", + ) + db.delete(supplier) + db.commit() + return None \ No newline at end of file diff --git a/app/api/v1/endpoints/transactions.py b/app/api/v1/endpoints/transactions.py new file mode 100644 index 0000000..8e8dbe6 --- /dev/null +++ b/app/api/v1/endpoints/transactions.py @@ -0,0 +1,107 @@ +from typing import Any, List, Optional + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user, get_db +from app.models.transaction import Transaction, TransactionType +from app.models.item import Item +from app.models.user import User +from app.schemas.transaction import Transaction as TransactionSchema, TransactionCreate + +router = APIRouter() + + +@router.get("/", response_model=List[TransactionSchema]) +def read_transactions( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + item_id: Optional[int] = None, + transaction_type: Optional[TransactionType] = None, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Retrieve transactions. + """ + query = db.query(Transaction).filter(Transaction.user_id == current_user.id) + + if item_id: + query = query.filter(Transaction.item_id == item_id) + if transaction_type: + query = query.filter(Transaction.transaction_type == transaction_type) + + transactions = query.order_by(Transaction.created_at.desc()).offset(skip).limit(limit).all() + return transactions + + +@router.post("/", response_model=TransactionSchema) +def create_transaction( + *, + db: Session = Depends(get_db), + transaction_in: TransactionCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new transaction and update item quantity. + """ + # Check if item exists + item = db.query(Item).filter( + Item.id == transaction_in.item_id, + Item.owner_id == current_user.id + ).first() + + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + + # Update item quantity based on transaction type + if transaction_in.transaction_type == TransactionType.STOCK_IN: + item.quantity += transaction_in.quantity + elif transaction_in.transaction_type == TransactionType.STOCK_OUT: + if item.quantity < transaction_in.quantity: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Not enough stock available", + ) + item.quantity -= transaction_in.quantity + elif transaction_in.transaction_type == TransactionType.ADJUSTMENT: + item.quantity = transaction_in.quantity + + # Create transaction record + transaction = Transaction( + **transaction_in.dict(), + user_id=current_user.id + ) + + db.add(transaction) + db.add(item) + db.commit() + db.refresh(transaction) + + return transaction + + +@router.get("/{transaction_id}", response_model=TransactionSchema) +def read_transaction( + *, + db: Session = Depends(get_db), + transaction_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get transaction by ID. + """ + transaction = db.query(Transaction).filter( + Transaction.id == transaction_id, + Transaction.user_id == current_user.id + ).first() + + if not transaction: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Transaction not found", + ) + return transaction \ No newline at end of file diff --git a/app/api/v1/endpoints/users.py b/app/api/v1/endpoints/users.py new file mode 100644 index 0000000..215873e --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,154 @@ +from typing import Any, List + +from fastapi import APIRouter, Body, Depends, HTTPException, status +from fastapi.encoders import jsonable_encoder +from pydantic import EmailStr +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_superuser, get_current_active_user, get_db +from app.core.security import get_password_hash +from app.models.user import User +from app.schemas.user import User as UserSchema, UserCreate, UserUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[UserSchema]) +def read_users( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Retrieve users. + """ + users = db.query(User).offset(skip).limit(limit).all() + return users + + +@router.post("/", response_model=UserSchema) +def create_user( + *, + db: Session = Depends(get_db), + user_in: UserCreate, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Create new user. + """ + user = db.query(User).filter(User.email == user_in.email).first() + if user: + raise HTTPException( + status_code=400, + detail="The user with this email already exists in the system.", + ) + user = User( + email=user_in.email, + hashed_password=get_password_hash(user_in.password), + full_name=user_in.full_name, + is_superuser=user_in.is_superuser, + is_active=user_in.is_active, + ) + db.add(user) + db.commit() + db.refresh(user) + return user + + +@router.put("/me", response_model=UserSchema) +def update_user_me( + *, + db: Session = Depends(get_db), + password: str = Body(None), + full_name: str = Body(None), + email: EmailStr = Body(None), + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update own user. + """ + current_user_data = jsonable_encoder(current_user) + user_in = UserUpdate(**current_user_data) + if password is not None: + user_in.password = password + if full_name is not None: + user_in.full_name = full_name + if email is not None: + user_in.email = email + user = current_user + if password is not None: + user.hashed_password = get_password_hash(password) + if full_name is not None: + user.full_name = full_name + if email is not None: + user.email = email + db.add(user) + db.commit() + db.refresh(user) + return user + + +@router.get("/me", response_model=UserSchema) +def read_user_me( + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get current user. + """ + return current_user + + +@router.get("/{user_id}", response_model=UserSchema) +def read_user_by_id( + user_id: int, + current_user: User = Depends(get_current_active_user), + db: Session = Depends(get_db), +) -> Any: + """ + Get a specific user by id. + """ + user = db.query(User).filter(User.id == user_id).first() + if user == current_user: + return user + if not current_user.is_superuser: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="The user doesn't have enough privileges", + ) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="The user with this id does not exist in the system", + ) + return user + + +@router.put("/{user_id}", response_model=UserSchema) +def update_user( + *, + db: Session = Depends(get_db), + user_id: int, + user_in: UserUpdate, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Update a user. + """ + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException( + status_code=404, + detail="The user with this id does not exist in the system", + ) + user_data = jsonable_encoder(user) + update_data = user_in.dict(exclude_unset=True) + for field in user_data: + if field in update_data: + setattr(user, field, update_data[field]) + if user_in.password: + user.hashed_password = get_password_hash(user_in.password) + db.add(user) + db.commit() + db.refresh(user) + return user \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..df466ed --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,22 @@ +from pydantic_settings import BaseSettings +from pathlib import Path + + +class Settings(BaseSettings): + PROJECT_NAME: str = "Small Business Inventory System" + API_V1_STR: str = "/api/v1" + + # Security + SECRET_KEY: str = "supersecretkey" # Change in production + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 + + # Base directory + BASE_DIR: Path = Path(__file__).resolve().parent.parent.parent + + class Config: + env_file = ".env" + case_sensitive = True + + +settings = Settings() \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..75985ff --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,40 @@ +from datetime import datetime, timedelta +from typing import Optional, Union, Any + +from jose import jwt +from passlib.context import CryptContext + +from app.core.config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def create_access_token( + subject: Union[str, Any], expires_delta: Optional[timedelta] = None +) -> str: + """ + Create a JWT token. + """ + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta( + minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES + ) + to_encode = {"exp": expire, "sub": str(subject)} + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return encoded_jwt + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify a password against a hash. + """ + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """ + Hash a password. + """ + return pwd_context.hash(password) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..a533e1f --- /dev/null +++ b/app/db/__init__.py @@ -0,0 +1,7 @@ +# Import all models to ensure they are registered with SQLAlchemy +from app.db.base import Base # noqa +from app.models.user import User # noqa +from app.models.item import Item # noqa +from app.models.category import Category # noqa +from app.models.supplier import Supplier # noqa +from app.models.transaction import Transaction # noqa \ No newline at end of file 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/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..7fae141 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,9 @@ +from sqlalchemy import Column, Integer, DateTime +from sqlalchemy.sql import func + + +class BaseModel: + """Base class for all models with common fields.""" + id = Column(Integer, primary_key=True, index=True) + created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False) \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..47343aa --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,25 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from pathlib import Path + +# Create the storage/db directory if it doesn't exist +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(): + """Dependency for getting DB session.""" + 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..c4da820 --- /dev/null +++ b/app/models/category.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, String, Text +from sqlalchemy.orm import relationship + +from app.db.base import Base +from app.db.base_class import BaseModel + + +class Category(Base, BaseModel): + """Category model for organizing inventory items.""" + __tablename__ = "categories" + + name = Column(String, index=True, nullable=False) + description = Column(Text, nullable=True) + + # Relationships + items = relationship("Item", back_populates="category") \ No newline at end of file diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..fe7ad62 --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,30 @@ +from sqlalchemy import Column, String, Text, Integer, Float, ForeignKey +from sqlalchemy.orm import relationship + +from app.db.base import Base +from app.db.base_class import BaseModel + + +class Item(Base, BaseModel): + """Inventory item model.""" + __tablename__ = "items" + + name = Column(String, index=True, nullable=False) + description = Column(Text, nullable=True) + sku = Column(String, index=True, unique=True, nullable=True) + barcode = Column(String, index=True, unique=True, nullable=True) + quantity = Column(Integer, default=0, nullable=False) + unit_price = Column(Float, nullable=True) + reorder_level = Column(Integer, default=0, nullable=True) + location = Column(String, nullable=True) + + # Foreign keys + category_id = Column(Integer, ForeignKey("categories.id"), nullable=True) + supplier_id = Column(Integer, ForeignKey("suppliers.id"), nullable=True) + owner_id = Column(Integer, ForeignKey("users.id"), nullable=False) + + # Relationships + category = relationship("Category", back_populates="items") + supplier = relationship("Supplier", back_populates="items") + owner = relationship("User", back_populates="items") + transactions = relationship("Transaction", back_populates="item") \ No newline at end of file diff --git a/app/models/supplier.py b/app/models/supplier.py new file mode 100644 index 0000000..a6b2780 --- /dev/null +++ b/app/models/supplier.py @@ -0,0 +1,20 @@ +from sqlalchemy import Column, String, Text +from sqlalchemy.orm import relationship + +from app.db.base import Base +from app.db.base_class import BaseModel + + +class Supplier(Base, BaseModel): + """Supplier model for inventory item sources.""" + __tablename__ = "suppliers" + + name = Column(String, index=True, nullable=False) + contact_name = Column(String, nullable=True) + email = Column(String, nullable=True) + phone = Column(String, nullable=True) + address = Column(Text, nullable=True) + notes = Column(Text, nullable=True) + + # Relationships + items = relationship("Item", back_populates="supplier") \ No newline at end of file diff --git a/app/models/transaction.py b/app/models/transaction.py new file mode 100644 index 0000000..2602767 --- /dev/null +++ b/app/models/transaction.py @@ -0,0 +1,32 @@ +from sqlalchemy import Column, String, Text, Integer, Float, ForeignKey, Enum +from sqlalchemy.orm import relationship +import enum + +from app.db.base import Base +from app.db.base_class import BaseModel + + +class TransactionType(str, enum.Enum): + """Enum for transaction types.""" + STOCK_IN = "stock_in" + STOCK_OUT = "stock_out" + ADJUSTMENT = "adjustment" + + +class Transaction(Base, BaseModel): + """Transaction model for inventory movements.""" + __tablename__ = "transactions" + + transaction_type = Column(Enum(TransactionType), nullable=False) + quantity = Column(Integer, nullable=False) + unit_price = Column(Float, nullable=True) + reference = Column(String, nullable=True) # Invoice/PO number + notes = Column(Text, nullable=True) + + # Foreign keys + item_id = Column(Integer, ForeignKey("items.id"), nullable=False) + user_id = Column(Integer, ForeignKey("users.id"), nullable=False) + + # Relationships + item = relationship("Item", back_populates="transactions") + user = relationship("User", back_populates="transactions") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..e6df28f --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,20 @@ +from sqlalchemy import Column, String, Boolean +from sqlalchemy.orm import relationship + +from app.db.base import Base +from app.db.base_class import BaseModel + + +class User(Base, BaseModel): + """User model for authentication and authorization.""" + __tablename__ = "users" + + email = Column(String, unique=True, index=True, nullable=False) + hashed_password = Column(String, nullable=False) + full_name = Column(String, nullable=True) + is_active = Column(Boolean, default=True) + is_superuser = Column(Boolean, default=False) + + # Relationships + items = relationship("Item", back_populates="owner") + transactions = relationship("Transaction", back_populates="user") \ 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..4c3123b --- /dev/null +++ b/app/schemas/category.py @@ -0,0 +1,30 @@ +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 + + +class CategoryInDBBase(CategoryBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class Category(CategoryInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..5ae9219 --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,47 @@ +from pydantic import BaseModel +from typing import Optional +from datetime import datetime + + +class ItemBase(BaseModel): + name: str + description: Optional[str] = None + sku: Optional[str] = None + barcode: Optional[str] = None + quantity: int = 0 + unit_price: Optional[float] = None + reorder_level: Optional[int] = None + location: Optional[str] = None + 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 + sku: Optional[str] = None + barcode: Optional[str] = None + quantity: Optional[int] = None + unit_price: Optional[float] = None + reorder_level: Optional[int] = None + location: Optional[str] = None + category_id: Optional[int] = None + supplier_id: Optional[int] = None + + +class ItemInDBBase(ItemBase): + id: int + owner_id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class Item(ItemInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/supplier.py b/app/schemas/supplier.py new file mode 100644 index 0000000..681d840 --- /dev/null +++ b/app/schemas/supplier.py @@ -0,0 +1,38 @@ +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 + notes: 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 + notes: Optional[str] = None + + +class SupplierInDBBase(SupplierBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class Supplier(SupplierInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..e78453f --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,10 @@ +from pydantic import BaseModel + + +class Token(BaseModel): + access_token: str + token_type: str + + +class TokenPayload(BaseModel): + sub: str = None \ No newline at end of file diff --git a/app/schemas/transaction.py b/app/schemas/transaction.py new file mode 100644 index 0000000..d7d75ca --- /dev/null +++ b/app/schemas/transaction.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel +from typing import Optional +from datetime import datetime +from enum import Enum + + +class TransactionType(str, Enum): + STOCK_IN = "stock_in" + STOCK_OUT = "stock_out" + ADJUSTMENT = "adjustment" + + +class TransactionBase(BaseModel): + transaction_type: TransactionType + quantity: int + unit_price: Optional[float] = None + reference: Optional[str] = None + notes: Optional[str] = None + item_id: int + + +class TransactionCreate(TransactionBase): + pass + + +class TransactionUpdate(BaseModel): + transaction_type: Optional[TransactionType] = None + quantity: Optional[int] = None + unit_price: Optional[float] = None + reference: Optional[str] = None + notes: Optional[str] = None + item_id: Optional[int] = None + + +class TransactionInDBBase(TransactionBase): + id: int + user_id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class Transaction(TransactionInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..942d951 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,36 @@ +from pydantic import BaseModel, EmailStr +from typing import Optional + + +class UserBase(BaseModel): + email: EmailStr + full_name: Optional[str] = None + is_active: Optional[bool] = True + is_superuser: bool = False + + +class UserCreate(UserBase): + password: str + + +class UserUpdate(BaseModel): + email: Optional[EmailStr] = None + full_name: Optional[str] = None + password: Optional[str] = None + is_active: Optional[bool] = None + is_superuser: Optional[bool] = None + + +class UserInDBBase(UserBase): + id: int + + class Config: + from_attributes = True + + +class User(UserInDBBase): + pass + + +class UserInDB(UserInDBBase): + hashed_password: str \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..55b2ed5 --- /dev/null +++ b/main.py @@ -0,0 +1,46 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.v1.api import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + description="Small Business Inventory System API", + version="0.1.0", + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc", +) + +# Add CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(api_router, prefix=settings.API_V1_STR) + + +@app.get("/") +async def root(): + """Root endpoint with basic service information.""" + return { + "title": settings.PROJECT_NAME, + "documentation": "/docs", + "health_check": "/health" + } + + +@app.get("/health") +async def health_check(): + """Health check endpoint.""" + return {"status": "healthy"} + + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/__init__.py b/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..c3c4c2f --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,87 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Import Base from app.db.base to get all models registered +import sys +import os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from app.db.base import Base +import app.models # noqa + +# 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. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +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"}, + render_as_batch=True, # For SQLite + ) + + 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: + is_sqlite = connection.dialect.name == 'sqlite' + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite, # For SQLite + ) + + 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/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/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(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/initial_migration.py b/migrations/versions/initial_migration.py new file mode 100644 index 0000000..a03e4ff --- /dev/null +++ b/migrations/versions/initial_migration.py @@ -0,0 +1,129 @@ +"""Initial migration + +Revision ID: 01_initial +Revises: +Create Date: 2023-10-23 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '01_initial' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # Create users table + op.create_table( + 'users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('full_name', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + + # Create categories table + op.create_table( + 'categories', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), 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=False) + + # Create suppliers table + op.create_table( + 'suppliers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), 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.Text(), nullable=True), + sa.Column('notes', sa.Text(), 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=False) + + # Create items table + op.create_table( + 'items', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('sku', sa.String(), nullable=True), + sa.Column('barcode', sa.String(), nullable=True), + sa.Column('quantity', sa.Integer(), nullable=False), + sa.Column('unit_price', sa.Float(), nullable=True), + sa.Column('reorder_level', sa.Integer(), nullable=True), + sa.Column('location', sa.String(), nullable=True), + sa.Column('category_id', sa.Integer(), nullable=True), + sa.Column('supplier_id', sa.Integer(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['supplier_id'], ['suppliers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_items_barcode'), 'items', ['barcode'], unique=True) + op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False) + op.create_index(op.f('ix_items_name'), 'items', ['name'], unique=False) + op.create_index(op.f('ix_items_sku'), 'items', ['sku'], unique=True) + + # Create transactions table + op.create_table( + 'transactions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('transaction_type', sa.Enum('STOCK_IN', 'STOCK_OUT', 'ADJUSTMENT', name='transactiontype'), nullable=False), + sa.Column('quantity', sa.Integer(), nullable=False), + sa.Column('unit_price', sa.Float(), nullable=True), + sa.Column('reference', sa.String(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('item_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['item_id'], ['items.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_transactions_id'), 'transactions', ['id'], unique=False) + + +def downgrade(): + op.drop_index(op.f('ix_transactions_id'), table_name='transactions') + op.drop_table('transactions') + op.drop_index(op.f('ix_items_sku'), table_name='items') + op.drop_index(op.f('ix_items_name'), table_name='items') + op.drop_index(op.f('ix_items_id'), table_name='items') + op.drop_index(op.f('ix_items_barcode'), table_name='items') + op.drop_table('items') + 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') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6ad29f7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +fastapi>=0.104.0 +pydantic>=2.4.2 +pydantic-settings>=2.0.3 +sqlalchemy>=2.0.22 +alembic>=1.12.0 +uvicorn>=0.23.2 +python-jose[cryptography]>=3.3.0 +passlib[bcrypt]>=1.7.4 +python-multipart>=0.0.6 +email-validator>=2.0.0 +ruff>=0.1.1 \ No newline at end of file