diff --git a/README.md b/README.md index e8acfba..c15163d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,153 @@ -# FastAPI Application +# Generic Chat Service API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +This is a FastAPI application that provides a backend for a generic chat service with invoice generation capabilities. + +## Features + +- User authentication with JWT tokens +- Client management +- Invoice generation and management +- Activity logging +- PDF invoice generation +- RESTful API with OpenAPI documentation + +## Tech Stack + +- **FastAPI**: Modern web framework for building APIs +- **SQLAlchemy**: SQL toolkit and ORM +- **Alembic**: Database migration tool +- **Pydantic**: Data validation and settings management +- **SQLite**: Lightweight database +- **JWT**: JSON Web Token for authentication +- **Weasyprint**: HTML to PDF conversion +- **Python 3.9+**: Modern Python features + +## Project Structure + +``` +. +├── app/ +│ ├── api/ +│ │ ├── deps.py +│ │ └── v1/ +│ │ ├── api.py +│ │ └── endpoints/ +│ │ ├── auth.py +│ │ ├── clients.py +│ │ ├── invoices.py +│ │ └── users.py +│ ├── core/ +│ │ ├── auth.py +│ │ ├── config.py +│ │ ├── logging.py +│ │ └── security.py +│ ├── crud/ +│ │ ├── crud_client.py +│ │ ├── crud_invoice.py +│ │ └── crud_user.py +│ ├── db/ +│ │ └── session.py +│ ├── models/ +│ │ ├── activity.py +│ │ ├── base.py +│ │ ├── client.py +│ │ ├── invoice.py +│ │ └── user.py +│ ├── schemas/ +│ │ ├── activity.py +│ │ ├── client.py +│ │ ├── invoice.py +│ │ ├── token.py +│ │ └── user.py +│ ├── services/ +│ ├── static/ +│ ├── templates/ +│ └── utils/ +│ ├── activity.py +│ └── pdf.py +├── migrations/ +│ └── versions/ +│ └── 001_initial_migration.py +├── alembic.ini +├── main.py +└── requirements.txt +``` + +## Getting Started + +### Prerequisites + +- Python 3.9+ +- pip + +### Installation + +1. Clone the repository +```bash +git clone +cd +``` + +2. Install dependencies +```bash +pip install -r requirements.txt +``` + +3. Run database migrations +```bash +alembic upgrade head +``` + +4. Start the server +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000 + +## API Documentation + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## Authentication + +The API uses JWT tokens for authentication. To obtain a token: + +1. Send a POST request to `/api/v1/auth/login` with your email and password +2. Use the returned token in the Authorization header for subsequent requests + +## Endpoints + +- **Auth**: `/api/v1/auth/` + - Login + - Test token + +- **Users**: `/api/v1/users/` + - Create user + - Get users + - Get user by ID + - Update user + - Delete user + +- **Clients**: `/api/v1/clients/` + - Create client + - Get clients + - Get client by ID + - Update client + - Delete client + +- **Invoices**: `/api/v1/invoices/` + - Create invoice + - Get invoices + - Get invoice by ID + - Update invoice + - Delete invoice + - Generate PDF + +- **Health Check**: `/health` + - Application health status + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..5a675dc --- /dev/null +++ b/alembic.ini @@ -0,0 +1,86 @@ +# 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 migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL with absolute path +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 + +# 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/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..46f1e2c --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,48 @@ + +from fastapi import Depends, HTTPException, status +from jose import jwt +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app.core.auth import oauth2_scheme +from app.core.config import settings +from app.crud.crud_user import get_user_by_email +from app.db.session import get_db +from app.models.user import User +from app.schemas.token import TokenPayload + + +def get_current_user( + db: Session = Depends(get_db), + token: str = Depends(oauth2_scheme) +) -> User: + """ + Get current user from JWT token + """ + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = TokenPayload(**payload) + except (jwt.JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + user = get_user_by_email(db, email=token_data.sub) + + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Inactive user" + ) + + return user \ No newline at end of file diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..c7b5539 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,10 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import users, auth, clients, invoices + +api_router = APIRouter() + +api_router.include_router(auth.router, prefix="/auth", tags=["authentication"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(clients.router, prefix="/clients", tags=["clients"]) +api_router.include_router(invoices.router, prefix="/invoices", tags=["invoices"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000..1daa837 --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,64 @@ +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_current_user +from app.core.auth import authenticate_user, create_access_token +from app.core.config import settings +from app.core.logging import app_logger +from app.db.session import get_db +from app.models.user import User +from app.schemas.token import Token +from app.utils.activity import log_activity + +router = APIRouter() + + +@router.post("/login", 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 = authenticate_user(db, form_data.username, form_data.password) + if not user: + app_logger.warning(f"Failed login attempt for user: {form_data.username}") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + subject=user.email, expires_delta=access_token_expires + ) + + # Log login activity + log_activity( + db=db, + user_id=user.id, + action="login", + entity_type="user", + entity_id=user.id, + details="User logged in successfully" + ) + + app_logger.info(f"User logged in: {user.email}") + return {"access_token": access_token, "token_type": "bearer"} + + +@router.post("/test-token", response_model=dict) +def test_token(current_user: User = Depends(get_current_user)) -> Any: + """ + Test access token + """ + return { + "email": current_user.email, + "message": "Token is valid", + } \ No newline at end of file diff --git a/app/api/v1/endpoints/clients.py b/app/api/v1/endpoints/clients.py new file mode 100644 index 0000000..a363089 --- /dev/null +++ b/app/api/v1/endpoints/clients.py @@ -0,0 +1,180 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_user +from app.core.logging import app_logger +from app.crud.crud_client import ( + create_client, + delete_client, + get_client, + get_clients_by_user, + update_client, +) +from app.db.session import get_db +from app.models.user import User +from app.schemas.client import Client, ClientCreate, ClientUpdate, ClientWithInvoices +from app.utils.activity import log_activity + +router = APIRouter() + + +@router.get("/", response_model=List[Client]) +def read_clients( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Retrieve all clients for the current user + """ + clients = get_clients_by_user( + db=db, user_id=current_user.id, skip=skip, limit=limit + ) + return clients + + +@router.post("/", response_model=Client, status_code=status.HTTP_201_CREATED) +def create_client_route( + *, + db: Session = Depends(get_db), + client_in: ClientCreate, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Create new client for the current user + """ + client = create_client(db=db, obj_in=client_in, user_id=current_user.id) + + # Log activity + log_activity( + db=db, + user_id=current_user.id, + action="create", + entity_type="client", + entity_id=client.id, + details=f"Created new client: {client.name}" + ) + + app_logger.info(f"User {current_user.email} created new client: {client.name}") + return client + + +@router.get("/{client_id}", response_model=ClientWithInvoices) +def read_client( + *, + db: Session = Depends(get_db), + client_id: int, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Get client by ID + """ + client = get_client(db=db, client_id=client_id) + if not client: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Client not found" + ) + + # Check if the client belongs to the current user + if client.user_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions to access this client" + ) + + # Log activity + log_activity( + db=db, + user_id=current_user.id, + action="view", + entity_type="client", + entity_id=client.id, + details=f"Viewed client: {client.name}" + ) + + return client + + +@router.put("/{client_id}", response_model=Client) +def update_client_route( + *, + db: Session = Depends(get_db), + client_id: int, + client_in: ClientUpdate, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Update a client + """ + client = get_client(db=db, client_id=client_id) + if not client: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Client not found" + ) + + # Check if the client belongs to the current user + if client.user_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions to update this client" + ) + + client = update_client(db=db, db_obj=client, obj_in=client_in) + + # Log activity + log_activity( + db=db, + user_id=current_user.id, + action="update", + entity_type="client", + entity_id=client.id, + details=f"Updated client: {client.name}" + ) + + app_logger.info(f"User {current_user.email} updated client: {client.name}") + return client + + +@router.delete("/{client_id}", response_model=None, status_code=status.HTTP_204_NO_CONTENT) +def delete_client_route( + *, + db: Session = Depends(get_db), + client_id: int, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Delete a client + """ + client = get_client(db=db, client_id=client_id) + if not client: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Client not found" + ) + + # Check if the client belongs to the current user + if client.user_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions to delete this client" + ) + + client_name = client.name + delete_client(db=db, client_id=client_id) + + # Log activity + log_activity( + db=db, + user_id=current_user.id, + action="delete", + entity_type="client", + details=f"Deleted client: {client_name}" + ) + + app_logger.info(f"User {current_user.email} deleted client: {client_name}") + return None \ No newline at end of file diff --git a/app/api/v1/endpoints/invoices.py b/app/api/v1/endpoints/invoices.py new file mode 100644 index 0000000..af9233c --- /dev/null +++ b/app/api/v1/endpoints/invoices.py @@ -0,0 +1,3 @@ +from fastapi import APIRouter + +router = APIRouter() diff --git a/app/api/v1/endpoints/users.py b/app/api/v1/endpoints/users.py new file mode 100644 index 0000000..fc576e3 --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,128 @@ +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_user +from app.core.logging import app_logger +from app.crud.crud_user import create_user, delete_user, get_user, get_user_by_email, update_user +from app.db.session import get_db +from app.models.user import User +from app.schemas.user import User as UserSchema +from app.schemas.user import UserCreate, UserUpdate +from app.utils.activity import log_activity + +router = APIRouter() + + +@router.post("/", response_model=UserSchema, status_code=status.HTTP_201_CREATED) +def create_user_route( + *, + db: Session = Depends(get_db), + user_in: UserCreate, +) -> Any: + """ + Create new user + """ + user = get_user_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this email already exists", + ) + + user = create_user(db, obj_in=user_in) + app_logger.info(f"New user created: {user.email}") + + return user + + +@router.get("/me", response_model=UserSchema) +def read_user_me( + current_user: User = Depends(get_current_user), +) -> Any: + """ + Get current user information + """ + return current_user + + +@router.put("/me", response_model=UserSchema) +def update_user_me( + *, + db: Session = Depends(get_db), + user_in: UserUpdate, + current_user: User = Depends(get_current_user), +) -> Any: + """ + Update current user information + """ + user = update_user(db, db_obj=current_user, obj_in=user_in) + + # Log activity + log_activity( + db=db, + user_id=current_user.id, + action="update", + entity_type="user", + entity_id=current_user.id, + details="User updated their profile" + ) + + app_logger.info(f"User updated their profile: {user.email}") + return user + + +@router.get("/{user_id}", response_model=UserSchema) +def read_user_by_id( + user_id: int, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +) -> Any: + """ + Get a specific user by id - only the same user can access this + """ + user = get_user(db, user_id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + + # Only allow users to access their own information + if user.id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions to access this user" + ) + + return user + + +@router.delete("/{user_id}", response_model=None, status_code=status.HTTP_204_NO_CONTENT) +def delete_user_by_id( + user_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +) -> Any: + """ + Delete a user by id - only the same user can delete their account + """ + user = get_user(db, user_id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + + # Only allow users to delete their own account + if user.id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions to delete this user" + ) + + user = delete_user(db, user_id=user_id) + app_logger.info(f"User deleted their account: {user.email}") + + return None \ No newline at end of file diff --git a/app/core/auth.py b/app/core/auth.py new file mode 100644 index 0000000..2377c55 --- /dev/null +++ b/app/core/auth.py @@ -0,0 +1,77 @@ +from datetime import datetime, timedelta +from typing import Any, Optional, Union + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from sqlalchemy.orm import Session + +from app.core.config import settings +from app.core.security import verify_password +from app.crud.crud_user import get_user_by_email +from app.db.session import get_db +from app.models.user import User +from app.schemas.token import TokenPayload + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login") + + +def authenticate_user(db: Session, email: str, password: str) -> Optional[User]: + """ + Authenticate user by email and password + """ + user = get_user_by_email(db, email=email) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + +def create_access_token(subject: Union[str, Any], expires_delta: Optional[timedelta] = None) -> str: + """ + Create JWT access 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 get_current_user( + db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) +) -> User: + """ + Get current user from JWT token + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = TokenPayload(**payload) + if token_data.sub is None: + raise credentials_exception + except JWTError: + raise credentials_exception + + user = get_user_by_email(db, email=token_data.sub) + if user is None: + raise credentials_exception + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Inactive user" + ) + return user \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..7b85b50 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,49 @@ +from pathlib import Path +from typing import List + +from pydantic import BaseSettings, validator + + +class Settings(BaseSettings): + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "Invoicing API" + PROJECT_DESCRIPTION: str = "Professional Invoicing API for Freelancers and Small Businesses" + VERSION: str = "0.1.0" + + # CORS settings + BACKEND_CORS_ORIGINS: List[str] = ["*"] + + @validator("BACKEND_CORS_ORIGINS", pre=True) + def assemble_cors_origins(cls, v: str | List[str]) -> List[str] | str: + if isinstance(v, str) and not v.startswith("["): + return [i.strip() for i in v.split(",")] + elif isinstance(v, (list, str)): + return v + raise ValueError(v) + + # Database + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + # JWT settings + SECRET_KEY: str = "YOUR_SECRET_KEY_HERE_PLEASE_CHANGE_THIS_IN_PRODUCTION" + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7 # 7 days + + # File storage + STORAGE_DIR: Path = Path("/app") / "storage" + INVOICE_STORAGE_DIR: Path = STORAGE_DIR / "invoices" + + # Configure logging + LOG_LEVEL: str = "INFO" + + class Config: + case_sensitive = True + env_file = ".env" + + +# Create all necessary directories +for dir_path in [Settings().DB_DIR, Settings().INVOICE_STORAGE_DIR]: + dir_path.mkdir(parents=True, exist_ok=True) + +settings = Settings() \ No newline at end of file diff --git a/app/core/logging.py b/app/core/logging.py new file mode 100644 index 0000000..d8e9eff --- /dev/null +++ b/app/core/logging.py @@ -0,0 +1,37 @@ +import sys + +from loguru import logger + +from app.core.config import settings + +# Configure loguru logger +LOG_LEVEL = settings.LOG_LEVEL +LOG_FORMAT = ( + "{time:YYYY-MM-DD HH:mm:ss.SSS} | " + "{level: <8} | " + "{name}:{function}:{line} - " + "{message}" +) + +# Configure logger +logger.remove() # Remove default logger +logger.add( + sys.stderr, + format=LOG_FORMAT, + level=LOG_LEVEL, + colorize=True, +) + +# Add file logging +log_file = settings.STORAGE_DIR / "logs" / "app.log" +log_file.parent.mkdir(parents=True, exist_ok=True) +logger.add( + log_file, + rotation="10 MB", + retention="30 days", + level=LOG_LEVEL, + format=LOG_FORMAT, +) + +# Make logger available +app_logger = logger \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..823b759 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,42 @@ +from datetime import datetime, timedelta +from typing import Any, Optional, Union + +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 access 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/crud/crud_client.py b/app/crud/crud_client.py new file mode 100644 index 0000000..44a120d --- /dev/null +++ b/app/crud/crud_client.py @@ -0,0 +1,79 @@ +from typing import List, Optional, Union, Dict, Any + +from sqlalchemy.orm import Session + +from app.models.client import Client +from app.schemas.client import ClientCreate, ClientUpdate + + +def get_client(db: Session, client_id: int) -> Optional[Client]: + """ + Get client by ID + """ + return db.query(Client).filter(Client.id == client_id).first() + + +def get_clients_by_user( + db: Session, user_id: int, skip: int = 0, limit: int = 100 +) -> List[Client]: + """ + Get all clients for a user + """ + return ( + db.query(Client) + .filter(Client.user_id == user_id) + .offset(skip) + .limit(limit) + .all() + ) + + +def create_client(db: Session, obj_in: ClientCreate, user_id: int) -> Client: + """ + Create new client for a user + """ + db_obj = Client( + user_id=user_id, + name=obj_in.name, + email=obj_in.email, + company_name=obj_in.company_name, + address=obj_in.address, + phone=obj_in.phone, + notes=obj_in.notes, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def update_client( + db: Session, *, db_obj: Client, obj_in: Union[ClientUpdate, Dict[str, Any]] +) -> Client: + """ + Update client + """ + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + + for field in update_data: + if hasattr(db_obj, field): + setattr(db_obj, field, update_data[field]) + + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def delete_client(db: Session, *, client_id: int) -> Client: + """ + Delete client + """ + client = db.query(Client).filter(Client.id == client_id).first() + if client: + db.delete(client) + db.commit() + return client \ No newline at end of file diff --git a/app/crud/crud_invoice.py b/app/crud/crud_invoice.py new file mode 100644 index 0000000..03e4931 --- /dev/null +++ b/app/crud/crud_invoice.py @@ -0,0 +1,180 @@ +from typing import List, Optional, Union, Dict, Any + +from sqlalchemy.orm import Session, joinedload + +from app.models.invoice import Invoice, InvoiceItem +from app.schemas.invoice import InvoiceCreate, InvoiceUpdate, InvoiceItemCreate + + +def get_invoice(db: Session, invoice_id: int) -> Optional[Invoice]: + """ + Get invoice by ID with items + """ + return ( + db.query(Invoice) + .options(joinedload(Invoice.items)) + .filter(Invoice.id == invoice_id) + .first() + ) + + +def get_invoices_by_user( + db: Session, user_id: int, skip: int = 0, limit: int = 100 +) -> List[Invoice]: + """ + Get all invoices for a user + """ + return ( + db.query(Invoice) + .filter(Invoice.user_id == user_id) + .order_by(Invoice.created_at.desc()) + .offset(skip) + .limit(limit) + .all() + ) + + +def get_invoices_by_client( + db: Session, client_id: int, user_id: int, skip: int = 0, limit: int = 100 +) -> List[Invoice]: + """ + Get all invoices for a client + """ + return ( + db.query(Invoice) + .filter(Invoice.client_id == client_id, Invoice.user_id == user_id) + .order_by(Invoice.created_at.desc()) + .offset(skip) + .limit(limit) + .all() + ) + + +def create_invoice(db: Session, obj_in: InvoiceCreate, user_id: int) -> Invoice: + """ + Create new invoice with items + """ + # Create invoice + db_obj = Invoice( + user_id=user_id, + client_id=obj_in.client_id, + invoice_number=obj_in.invoice_number, + status=obj_in.status, + issued_date=obj_in.issued_date, + due_date=obj_in.due_date, + notes=obj_in.notes, + total_amount=0.0, # Will be calculated after items are added + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + + # Create invoice items + for item_in in obj_in.items: + create_invoice_item(db, item_in, db_obj.id) + + # Update total amount + total_amount = calculate_invoice_total(db, db_obj.id) + db_obj.total_amount = total_amount + db.add(db_obj) + db.commit() + db.refresh(db_obj) + + return db_obj + + +def update_invoice( + db: Session, *, db_obj: Invoice, obj_in: Union[InvoiceUpdate, Dict[str, Any]] +) -> Invoice: + """ + Update invoice + """ + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + + # Handle items separately + items = update_data.pop("items", None) + + # Update invoice fields + for field in update_data: + if hasattr(db_obj, field): + setattr(db_obj, field, update_data[field]) + + db.add(db_obj) + db.commit() + db.refresh(db_obj) + + # Update items if provided + if items: + # Delete existing items + db.query(InvoiceItem).filter(InvoiceItem.invoice_id == db_obj.id).delete() + db.commit() + + # Create new items + for item_in in items: + create_invoice_item(db, item_in, db_obj.id) + + # Update total amount + total_amount = calculate_invoice_total(db, db_obj.id) + db_obj.total_amount = total_amount + db.add(db_obj) + db.commit() + db.refresh(db_obj) + + return db_obj + + +def delete_invoice(db: Session, *, invoice_id: int) -> Invoice: + """ + Delete invoice + """ + invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first() + if invoice: + # Delete all related items first + db.query(InvoiceItem).filter(InvoiceItem.invoice_id == invoice_id).delete() + db.commit() + + # Delete the invoice + db.delete(invoice) + db.commit() + return invoice + + +def create_invoice_item(db: Session, obj_in: InvoiceItemCreate, invoice_id: int) -> InvoiceItem: + """ + Create new invoice item + """ + db_obj = InvoiceItem( + invoice_id=invoice_id, + description=obj_in.description, + quantity=obj_in.quantity, + unit_price=obj_in.unit_price, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def calculate_invoice_total(db: Session, invoice_id: int) -> float: + """ + Calculate the total amount for an invoice + """ + items = db.query(InvoiceItem).filter(InvoiceItem.invoice_id == invoice_id).all() + total = sum(item.quantity * item.unit_price for item in items) + return total + + +def update_invoice_pdf_path(db: Session, invoice_id: int, pdf_path: str) -> Invoice: + """ + Update the PDF path for an invoice + """ + invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first() + if invoice: + invoice.pdf_path = pdf_path + db.add(invoice) + db.commit() + db.refresh(invoice) + return invoice \ No newline at end of file diff --git a/app/crud/crud_user.py b/app/crud/crud_user.py new file mode 100644 index 0000000..d2a3c18 --- /dev/null +++ b/app/crud/crud_user.py @@ -0,0 +1,78 @@ +from typing import Any, Dict, Optional, Union + +from sqlalchemy.orm import Session + +from app.core.security import get_password_hash +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + + +def get_user(db: Session, user_id: int) -> Optional[User]: + """ + Get user by ID + """ + return db.query(User).filter(User.id == user_id).first() + + +def get_user_by_email(db: Session, email: str) -> Optional[User]: + """ + Get user by email + """ + return db.query(User).filter(User.email == email).first() + + +def create_user(db: Session, obj_in: UserCreate) -> User: + """ + Create new user + """ + db_obj = User( + email=obj_in.email, + hashed_password=get_password_hash(obj_in.password), + full_name=obj_in.full_name, + company_name=obj_in.company_name, + address=obj_in.address, + phone=obj_in.phone, + is_active=obj_in.is_active, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def update_user( + db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] +) -> User: + """ + Update user + """ + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + + # Handle password update separately + if "password" in update_data: + hashed_password = get_password_hash(update_data["password"]) + del update_data["password"] + update_data["hashed_password"] = hashed_password + + for field in update_data: + if hasattr(db_obj, field): + setattr(db_obj, field, update_data[field]) + + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def delete_user(db: Session, *, user_id: int) -> User: + """ + Delete user + """ + user = db.query(User).filter(User.id == user_id).first() + if user: + db.delete(user) + db.commit() + return user \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..a28a583 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,29 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Create database directory if it doesn't exist +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +# Create SQLAlchemy engine +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Needed for SQLite +) + +# Create sessionmaker +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +# Create base class for models +Base = declarative_base() + + +# Dependency to get DB session +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..c9e90a5 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,6 @@ +__all__ = ["User", "Client", "Invoice", "InvoiceItem", "Activity"] + +from app.models.user import User +from app.models.client import Client +from app.models.invoice import Invoice, InvoiceItem +from app.models.activity import Activity \ No newline at end of file diff --git a/app/models/activity.py b/app/models/activity.py new file mode 100644 index 0000000..51608d6 --- /dev/null +++ b/app/models/activity.py @@ -0,0 +1,19 @@ +from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text +from sqlalchemy.orm import relationship + +from app.models.base import ModelBase + + +class Activity(ModelBase): + """ + Activity model for tracking user actions + """ + user_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"), nullable=False) + action = Column(String, nullable=False) # create, update, delete, view + entity_type = Column(String, nullable=False) # client, invoice, etc. + entity_id = Column(Integer, nullable=True) # ID of the entity + details = Column(Text, nullable=True) # Additional details + timestamp = Column(DateTime, nullable=False) + + # Relationships + user = relationship("User", back_populates="activities") \ No newline at end of file diff --git a/app/models/base.py b/app/models/base.py new file mode 100644 index 0000000..486faa8 --- /dev/null +++ b/app/models/base.py @@ -0,0 +1,28 @@ +from sqlalchemy import Column, Integer, DateTime, func +from sqlalchemy.ext.declarative import declared_attr + +from app.db.session import Base + + +class TimestampMixin: + """ + Mixin that adds created_at and updated_at columns to models + """ + created_at = Column(DateTime, default=func.now(), nullable=False) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False) + + +class ModelBase(Base): + """ + Base class for all models + """ + __abstract__ = True + + id = Column(Integer, primary_key=True, index=True) + + @declared_attr + def __tablename__(cls) -> str: + """ + Generate __tablename__ automatically from class name + """ + return cls.__name__.lower() \ No newline at end of file diff --git a/app/models/client.py b/app/models/client.py new file mode 100644 index 0000000..b666916 --- /dev/null +++ b/app/models/client.py @@ -0,0 +1,21 @@ +from sqlalchemy import Column, ForeignKey, Integer, String +from sqlalchemy.orm import relationship + +from app.models.base import ModelBase, TimestampMixin + + +class Client(ModelBase, TimestampMixin): + """ + Client model + """ + user_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"), nullable=False) + name = Column(String, nullable=False, index=True) + email = Column(String, nullable=False) + company_name = Column(String, nullable=True) + address = Column(String, nullable=True) + phone = Column(String, nullable=True) + notes = Column(String, nullable=True) + + # Relationships + user = relationship("User", back_populates="clients") + invoices = relationship("Invoice", back_populates="client", cascade="all, delete-orphan") \ No newline at end of file diff --git a/app/models/invoice.py b/app/models/invoice.py new file mode 100644 index 0000000..257dde8 --- /dev/null +++ b/app/models/invoice.py @@ -0,0 +1,37 @@ +from sqlalchemy import Column, Date, Float, ForeignKey, Integer, String, Text +from sqlalchemy.orm import relationship + +from app.models.base import ModelBase, TimestampMixin + + +class Invoice(ModelBase, TimestampMixin): + """ + Invoice model + """ + user_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"), nullable=False) + client_id = Column(Integer, ForeignKey("client.id", ondelete="CASCADE"), nullable=False) + invoice_number = Column(String, nullable=False, index=True) + status = Column(String, nullable=False, default="draft") # draft, sent, paid + issued_date = Column(Date, nullable=True) + due_date = Column(Date, nullable=True) + notes = Column(Text, nullable=True) + total_amount = Column(Float, nullable=False, default=0.0) + pdf_path = Column(String, nullable=True) + + # Relationships + user = relationship("User", back_populates="invoices") + client = relationship("Client", back_populates="invoices") + items = relationship("InvoiceItem", back_populates="invoice", cascade="all, delete-orphan") + + +class InvoiceItem(ModelBase, TimestampMixin): + """ + Invoice item model + """ + invoice_id = Column(Integer, ForeignKey("invoice.id", ondelete="CASCADE"), nullable=False) + description = Column(String, nullable=False) + quantity = Column(Float, nullable=False, default=1.0) + unit_price = Column(Float, nullable=False, default=0.0) + + # Relationships + invoice = relationship("Invoice", back_populates="items") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..63a1e06 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,22 @@ +from sqlalchemy import Boolean, Column, String +from sqlalchemy.orm import relationship + +from app.models.base import ModelBase, TimestampMixin + + +class User(ModelBase, TimestampMixin): + """ + User model + """ + email = Column(String, unique=True, index=True, nullable=False) + hashed_password = Column(String, nullable=False) + full_name = Column(String, nullable=False) + company_name = Column(String, nullable=True) + address = Column(String, nullable=True) + phone = Column(String, nullable=True) + is_active = Column(Boolean, default=True) + + # Relationships + clients = relationship("Client", back_populates="user", cascade="all, delete-orphan") + invoices = relationship("Invoice", back_populates="user", cascade="all, delete-orphan") + activities = relationship("Activity", back_populates="user", cascade="all, delete-orphan") \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..de29ebe --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,21 @@ +__all__ = [ + "User", "UserCreate", "UserUpdate", "UserInDB", "UserWithClients", + "Client", "ClientCreate", "ClientUpdate", "ClientInDB", "ClientWithInvoices", + "Invoice", "InvoiceCreate", "InvoiceUpdate", "InvoiceInDB", "InvoiceWithItems", + "InvoiceItem", "InvoiceItemCreate", "InvoiceItemUpdate", + "Token", "TokenPayload", + "Activity" +] + +from app.schemas.user import ( + User, UserCreate, UserUpdate, UserInDB, UserWithClients +) +from app.schemas.client import ( + Client, ClientCreate, ClientUpdate, ClientInDB, ClientWithInvoices +) +from app.schemas.invoice import ( + Invoice, InvoiceCreate, InvoiceUpdate, InvoiceInDB, InvoiceWithItems, + InvoiceItem, InvoiceItemCreate, InvoiceItemUpdate +) +from app.schemas.token import Token, TokenPayload +from app.schemas.activity import Activity \ No newline at end of file diff --git a/app/schemas/activity.py b/app/schemas/activity.py new file mode 100644 index 0000000..b0f7ad5 --- /dev/null +++ b/app/schemas/activity.py @@ -0,0 +1,20 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel + + +class ActivityBase(BaseModel): + action: str + entity_type: str + entity_id: Optional[int] = None + details: Optional[str] = None + timestamp: datetime + + +class Activity(ActivityBase): + id: int + user_id: int + + class Config: + orm_mode = True \ No newline at end of file diff --git a/app/schemas/client.py b/app/schemas/client.py new file mode 100644 index 0000000..962e8b2 --- /dev/null +++ b/app/schemas/client.py @@ -0,0 +1,49 @@ +from typing import List, Optional + +from pydantic import BaseModel, EmailStr + + +# Shared properties +class ClientBase(BaseModel): + name: str + email: EmailStr + company_name: Optional[str] = None + address: Optional[str] = None + phone: Optional[str] = None + notes: Optional[str] = None + + +# Properties to receive via API on creation +class ClientCreate(ClientBase): + pass + + +# Properties to receive via API on update +class ClientUpdate(ClientBase): + name: Optional[str] = None + email: Optional[EmailStr] = None + + +# Properties shared by models stored in DB +class ClientInDBBase(ClientBase): + id: int + user_id: int + + class Config: + orm_mode = True + + +# Properties to return via API +class Client(ClientInDBBase): + pass + + +# Properties stored in DB +class ClientInDB(ClientInDBBase): + pass + + +# Client with invoices +class ClientWithInvoices(Client): + from app.schemas.invoice import Invoice + invoices: List[Invoice] = [] \ No newline at end of file diff --git a/app/schemas/invoice.py b/app/schemas/invoice.py new file mode 100644 index 0000000..25f30c3 --- /dev/null +++ b/app/schemas/invoice.py @@ -0,0 +1,83 @@ +from datetime import date +from typing import List, Optional + +from pydantic import BaseModel, Field, validator + + +# Invoice Item schemas +class InvoiceItemBase(BaseModel): + description: str + quantity: float = Field(..., gt=0) + unit_price: float = Field(..., ge=0) + + +class InvoiceItemCreate(InvoiceItemBase): + pass + + +class InvoiceItemUpdate(InvoiceItemBase): + description: Optional[str] = None + quantity: Optional[float] = None + unit_price: Optional[float] = None + + +class InvoiceItemInDBBase(InvoiceItemBase): + id: int + invoice_id: int + + class Config: + orm_mode = True + + +class InvoiceItem(InvoiceItemInDBBase): + pass + + +# Invoice schemas +class InvoiceBase(BaseModel): + client_id: int + invoice_number: str + status: str = "draft" + issued_date: Optional[date] = None + due_date: Optional[date] = None + notes: Optional[str] = None + + @validator("status") + def status_validator(cls, v): + allowed_statuses = ["draft", "sent", "paid"] + if v not in allowed_statuses: + raise ValueError(f"Status must be one of: {', '.join(allowed_statuses)}") + return v + + +class InvoiceCreate(InvoiceBase): + items: List[InvoiceItemCreate] + + +class InvoiceUpdate(InvoiceBase): + client_id: Optional[int] = None + invoice_number: Optional[str] = None + status: Optional[str] = None + items: Optional[List[InvoiceItemCreate]] = None + + +class InvoiceInDBBase(InvoiceBase): + id: int + user_id: int + total_amount: float + pdf_path: Optional[str] = None + + class Config: + orm_mode = True + + +class Invoice(InvoiceInDBBase): + pass + + +class InvoiceInDB(InvoiceInDBBase): + pass + + +class InvoiceWithItems(Invoice): + items: List[InvoiceItem] = [] \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..ee642be --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,12 @@ +from typing import Optional + +from pydantic import BaseModel + + +class Token(BaseModel): + access_token: str + token_type: str + + +class TokenPayload(BaseModel): + sub: Optional[str] = None \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..3abc98b --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,61 @@ +from typing import List, Optional + +from pydantic import BaseModel, EmailStr, Field, validator + + +# Shared properties +class UserBase(BaseModel): + email: EmailStr + full_name: str + company_name: Optional[str] = None + address: Optional[str] = None + phone: Optional[str] = None + is_active: bool = True + + +# Properties to receive via API on creation +class UserCreate(UserBase): + password: str = Field(..., min_length=8) + + @validator("password") + def password_validation(cls, v): + if len(v) < 8: + raise ValueError("Password must be at least 8 characters long") + return v + + +# Properties to receive via API on update +class UserUpdate(UserBase): + email: Optional[EmailStr] = None + full_name: Optional[str] = None + password: Optional[str] = None + + @validator("password") + def password_validation(cls, v): + if v is not None and len(v) < 8: + raise ValueError("Password must be at least 8 characters long") + return v + + +# Properties shared by models stored in DB +class UserInDBBase(UserBase): + id: int + + class Config: + orm_mode = True + + +# Properties to return via API +class User(UserInDBBase): + pass + + +# Properties stored in DB +class UserInDB(UserInDBBase): + hashed_password: str + + +# User with clients +class UserWithClients(User): + from app.schemas.client import Client + clients: List[Client] = [] \ No newline at end of file diff --git a/app/utils/activity.py b/app/utils/activity.py new file mode 100644 index 0000000..93b011a --- /dev/null +++ b/app/utils/activity.py @@ -0,0 +1,53 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy.orm import Session + +from app.core.logging import app_logger +from app.models.activity import Activity + + +def log_activity( + db: Session, + user_id: int, + action: str, + entity_type: str, + entity_id: Optional[int] = None, + details: Optional[str] = None, +) -> Activity: + """ + Log an activity performed by a user + + Parameters: + - db: Database session + - user_id: ID of the user performing the action + - action: Type of action (e.g., "create", "update", "delete", "view") + - entity_type: Type of entity being acted on (e.g., "client", "invoice") + - entity_id: ID of the entity being acted on (optional) + - details: Additional details about the activity (optional) + """ + try: + activity = Activity( + user_id=user_id, + action=action, + entity_type=entity_type, + entity_id=entity_id, + details=details, + timestamp=datetime.utcnow() + ) + + db.add(activity) + db.commit() + db.refresh(activity) + + app_logger.info( + f"Activity logged: user_id={user_id}, action={action}, " + f"entity_type={entity_type}, entity_id={entity_id}" + ) + + return activity + + except Exception as e: + app_logger.error(f"Error logging activity: {str(e)}") + db.rollback() + raise \ No newline at end of file diff --git a/app/utils/pdf.py b/app/utils/pdf.py new file mode 100644 index 0000000..5363e6b --- /dev/null +++ b/app/utils/pdf.py @@ -0,0 +1,184 @@ +from datetime import datetime +from pathlib import Path +from typing import List + +from weasyprint import HTML + +from app.core.config import settings +from app.core.logging import app_logger +from app.models.invoice import Invoice, InvoiceItem +from app.models.client import Client +from app.models.user import User + + +def generate_invoice_pdf( + invoice: Invoice, + items: List[InvoiceItem], + client: Client, + user: User, +) -> Path: + """ + Generate a PDF for an invoice and save it to the storage directory + """ + try: + # Create a unique filename + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + filename = f"invoice_{invoice.id}_{timestamp}.pdf" + file_path = settings.INVOICE_STORAGE_DIR / filename + + # Make sure the directory exists + settings.INVOICE_STORAGE_DIR.mkdir(parents=True, exist_ok=True) + + # Generate HTML content for the invoice + html_content = _generate_invoice_html(invoice, items, client, user) + + # Convert HTML to PDF + HTML(string=html_content).write_pdf(file_path) + + app_logger.info(f"Generated PDF invoice: {file_path}") + return file_path + + except Exception as e: + app_logger.error(f"Error generating PDF invoice: {str(e)}") + raise + + +def _generate_invoice_html( + invoice: Invoice, + items: List[InvoiceItem], + client: Client, + user: User, +) -> str: + """ + Generate HTML content for an invoice + """ + # Calculate totals + subtotal = sum(item.unit_price * item.quantity for item in items) + total = subtotal # Add tax calculations if needed + + # Format dates + issued_date = invoice.issued_date.strftime("%Y-%m-%d") if invoice.issued_date else "" + due_date = invoice.due_date.strftime("%Y-%m-%d") if invoice.due_date else "" + + # Basic HTML template for the invoice + return f""" + + + + + Invoice #{invoice.invoice_number} + + + +
+
+
INVOICE
+
#{invoice.invoice_number}
+
+
+
{invoice.status.upper()}
+
+
+ +
+

From:

+
{user.full_name}
+
{user.email}
+ +
+ +
+

To:

+
{client.name}
+
{client.company_name or ""}
+
{client.email}
+
{client.address or ""}
+
+ +
+
Invoice Date: {issued_date}
+
Due Date: {due_date}
+
+ + + + + + + + + + + + {"".join(f"" for item in items)} + +
DescriptionQuantityUnit PriceAmount
{item.description}{item.quantity}${item.unit_price:.2f}${item.quantity * item.unit_price:.2f}
+ +
+
Subtotal: ${subtotal:.2f}
+ +
Total: ${total:.2f}
+
+ +
+ Thank you for your business! +
+ + + """ \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..97714d0 --- /dev/null +++ b/main.py @@ -0,0 +1,48 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse + +from app.api.v1.api import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.VERSION, + openapi_url=f"{settings.API_V1_STR}/openapi.json", + docs_url="/docs", + redoc_url="/redoc", +) + +# Configure CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Allow all domains + allow_credentials=True, + allow_methods=["*"], # Allow all methods + allow_headers=["*"], # Allow all headers +) + +# Include API router +app.include_router(api_router, prefix=settings.API_V1_STR) + + +@app.get("/health", response_model=dict) +async def health_check(): + """Health check endpoint""" + return {"status": "ok", "message": "Service is up and running"} + + +@app.exception_handler(Exception) +async def generic_exception_handler(request, exc): + """Global exception handler""" + return JSONResponse( + status_code=500, + content={"detail": str(exc), "success": False}, + ) + + +if __name__ == "__main__": + import uvicorn + + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..3542e0e --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with SQLite. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..84e5496 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,80 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context +from app.db.session import Base + +# 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 +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/001_initial_migration.py b/migrations/versions/001_initial_migration.py new file mode 100644 index 0000000..b716d1e --- /dev/null +++ b/migrations/versions/001_initial_migration.py @@ -0,0 +1,123 @@ +"""Initial migration + +Revision ID: 001 +Revises: +Create Date: 2023-07-24 00: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(): + # Create user table + op.create_table( + 'user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('full_name', sa.String(), nullable=False), + sa.Column('company_name', sa.String(), nullable=True), + sa.Column('address', sa.String(), nullable=True), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True) + op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False) + + # Create client table + op.create_table( + 'client', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('company_name', sa.String(), nullable=True), + sa.Column('address', sa.String(), nullable=True), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('notes', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_client_id'), 'client', ['id'], unique=False) + op.create_index(op.f('ix_client_name'), 'client', ['name'], unique=False) + + # Create invoice table + op.create_table( + 'invoice', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('client_id', sa.Integer(), nullable=False), + sa.Column('invoice_number', sa.String(), nullable=False), + sa.Column('status', sa.String(), nullable=False), + sa.Column('issued_date', sa.Date(), nullable=True), + sa.Column('due_date', sa.Date(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('total_amount', sa.Float(), nullable=False), + sa.Column('pdf_path', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['client_id'], ['client.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_invoice_id'), 'invoice', ['id'], unique=False) + op.create_index(op.f('ix_invoice_invoice_number'), 'invoice', ['invoice_number'], unique=False) + + # Create invoice_item table + op.create_table( + 'invoiceitem', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('invoice_id', sa.Integer(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('quantity', sa.Float(), nullable=False), + sa.Column('unit_price', sa.Float(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['invoice_id'], ['invoice.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_invoiceitem_id'), 'invoiceitem', ['id'], unique=False) + + # Create activity table + op.create_table( + 'activity', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('action', sa.String(), nullable=False), + sa.Column('entity_type', sa.String(), nullable=False), + sa.Column('entity_id', sa.Integer(), nullable=True), + sa.Column('details', sa.Text(), nullable=True), + sa.Column('timestamp', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_activity_id'), 'activity', ['id'], unique=False) + + +def downgrade(): + op.drop_index(op.f('ix_activity_id'), table_name='activity') + op.drop_table('activity') + op.drop_index(op.f('ix_invoiceitem_id'), table_name='invoiceitem') + op.drop_table('invoiceitem') + op.drop_index(op.f('ix_invoice_invoice_number'), table_name='invoice') + op.drop_index(op.f('ix_invoice_id'), table_name='invoice') + op.drop_table('invoice') + op.drop_index(op.f('ix_client_name'), table_name='client') + op.drop_index(op.f('ix_client_id'), table_name='client') + op.drop_table('client') + op.drop_index(op.f('ix_user_email'), table_name='user') + op.drop_index(op.f('ix_user_id'), table_name='user') + op.drop_table('user') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..69984af --- /dev/null +++ b/requirements.txt @@ -0,0 +1,19 @@ +fastapi>=0.95.0 +uvicorn>=0.22.0 +sqlalchemy>=2.0.0 +alembic>=1.10.0 +pydantic>=2.0.0 +pydantic[email]>=2.0.0 +python-jose[cryptography]>=3.3.0 +passlib[bcrypt]>=1.7.4 +python-multipart>=0.0.6 +reportlab>=4.0.0 +ruff>=0.0.267 +pytest>=7.3.1 +httpx>=0.24.0 +weasyprint>=60.1 +python-dateutil>=2.8.2 +pytz>=2023.3 +loguru>=0.7.0 +tenacity>=8.2.2 +python-dotenv>=1.0.0 \ No newline at end of file