Create backend scaffold for freelancer invoicing API
- Set up FastAPI application with CORS support - Configure SQLite database connection - Create database models for users, clients, invoices, and line items - Set up Alembic for database migrations - Implement JWT-based authentication system - Create basic CRUD endpoints for users, clients, and invoices - Add PDF generation functionality - Implement activity logging - Update README with project information
This commit is contained in:
parent
92cde10974
commit
b51b13eb3e
154
README.md
154
README.md
@ -1,3 +1,153 @@
|
|||||||
# FastAPI Application
|
# Freelancer Invoicing API
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A professional invoicing API for freelancers and small businesses built with FastAPI and SQLite.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Secure authentication system with JWT tokens
|
||||||
|
- Client management (CRUD operations)
|
||||||
|
- Invoice management with line items
|
||||||
|
- Automatic total calculation
|
||||||
|
- PDF generation for invoices
|
||||||
|
- Activity logging
|
||||||
|
- Data protection (users can only access their own data)
|
||||||
|
- CORS support for all domains
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
freelancerinvoicingapi/
|
||||||
|
├── app/
|
||||||
|
│ ├── api/
|
||||||
|
│ │ ├── endpoints/ # API route handlers
|
||||||
|
│ │ │ ├── auth.py # Authentication endpoints
|
||||||
|
│ │ │ ├── clients.py # Client management endpoints
|
||||||
|
│ │ │ ├── invoices.py # Invoice management endpoints
|
||||||
|
│ │ │ └── users.py # User endpoints
|
||||||
|
│ │ ├── deps.py # Dependencies for routes
|
||||||
|
│ │ ├── health.py # Health check endpoint
|
||||||
|
│ │ └── routes.py # Route registration
|
||||||
|
│ ├── core/
|
||||||
|
│ │ ├── config.py # Application configuration
|
||||||
|
│ │ ├── logging.py # Logging setup
|
||||||
|
│ │ └── security.py # Security utilities
|
||||||
|
│ ├── crud/
|
||||||
|
│ │ ├── crud_client.py # Client CRUD operations
|
||||||
|
│ │ ├── crud_invoice.py # Invoice CRUD operations
|
||||||
|
│ │ └── crud_user.py # User CRUD operations
|
||||||
|
│ ├── db/
|
||||||
|
│ │ ├── base.py # Database models import
|
||||||
|
│ │ ├── base_class.py # Base class for models
|
||||||
|
│ │ └── session.py # Database session
|
||||||
|
│ ├── models/
|
||||||
|
│ │ ├── client.py # Client model
|
||||||
|
│ │ ├── invoice.py # Invoice and InvoiceItem models
|
||||||
|
│ │ └── user.py # User model
|
||||||
|
│ ├── schemas/
|
||||||
|
│ │ ├── client.py # Client schemas
|
||||||
|
│ │ ├── invoice.py # Invoice schemas
|
||||||
|
│ │ ├── token.py # Token schemas
|
||||||
|
│ │ └── user.py # User schemas
|
||||||
|
│ ├── services/ # Business logic services
|
||||||
|
│ └── utils/
|
||||||
|
│ └── pdf.py # PDF generation utility
|
||||||
|
├── migrations/ # Alembic migrations
|
||||||
|
│ ├── versions/ # Migration scripts
|
||||||
|
│ ├── env.py # Alembic environment
|
||||||
|
│ └── script.py.mako # Migration script template
|
||||||
|
├── storage/ # Storage directory
|
||||||
|
│ ├── db/ # Database files
|
||||||
|
│ ├── logs/ # Log files
|
||||||
|
│ └── pdfs/ # Generated PDFs
|
||||||
|
├── alembic.ini # Alembic configuration
|
||||||
|
├── main.py # Application entry point
|
||||||
|
└── requirements.txt # Dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
- `POST /api/v1/auth/register` - Register a new user
|
||||||
|
- `POST /api/v1/auth/login` - Login to get access token
|
||||||
|
|
||||||
|
### Users
|
||||||
|
|
||||||
|
- `GET /api/v1/users/me` - Get current user info
|
||||||
|
- `PUT /api/v1/users/me` - Update current user
|
||||||
|
|
||||||
|
### Clients
|
||||||
|
|
||||||
|
- `GET /api/v1/clients` - List all clients
|
||||||
|
- `POST /api/v1/clients` - Create a new client
|
||||||
|
- `GET /api/v1/clients/{client_id}` - Get a client
|
||||||
|
- `PUT /api/v1/clients/{client_id}` - Update a client
|
||||||
|
- `DELETE /api/v1/clients/{client_id}` - Delete a client
|
||||||
|
|
||||||
|
### Invoices
|
||||||
|
|
||||||
|
- `GET /api/v1/invoices` - List all invoices
|
||||||
|
- `POST /api/v1/invoices` - Create a new invoice
|
||||||
|
- `GET /api/v1/invoices/{invoice_id}` - Get an invoice
|
||||||
|
- `PUT /api/v1/invoices/{invoice_id}` - Update an invoice
|
||||||
|
- `DELETE /api/v1/invoices/{invoice_id}` - Delete an invoice
|
||||||
|
- `POST /api/v1/invoices/{invoice_id}/items` - Add an item to an invoice
|
||||||
|
- `DELETE /api/v1/invoices/{invoice_id}/items/{item_id}` - Remove an item from an invoice
|
||||||
|
- `GET /api/v1/invoices/{invoice_id}/pdf` - Generate and download a PDF for an invoice
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
|
||||||
|
- `GET /health` - Check API health
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8+
|
||||||
|
- pip
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone the repository
|
||||||
|
2. Install dependencies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run the migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Start the application:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000.
|
||||||
|
|
||||||
|
API documentation is available at:
|
||||||
|
- Swagger UI: http://localhost:8000/docs
|
||||||
|
- ReDoc: http://localhost:8000/redoc
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite as its database. The database file is stored in the `/app/storage/db` directory.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- JWT token-based authentication
|
||||||
|
- Password hashing with bcrypt
|
||||||
|
- User-specific data isolation
|
||||||
|
- HTTPS recommended for production
|
||||||
|
|
||||||
|
## PDF Generation
|
||||||
|
|
||||||
|
The application uses ReportLab to generate PDF invoices, which can be downloaded by clients.
|
||||||
|
|
||||||
|
## Logging
|
||||||
|
|
||||||
|
Activity logs are stored in the `/app/storage/logs` directory.
|
106
alembic.ini
Normal file
106
alembic.ini
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = migrations
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the python-dateutil library that can be
|
||||||
|
# installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to dateutil.tz.gettz()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the
|
||||||
|
# "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to migrations/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||||
|
|
||||||
|
# version path separator; As mentioned above, this is the character used to split
|
||||||
|
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||||
|
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||||
|
# Valid values for version_path_separator are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# SQLite URL
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
41
app/api/deps.py
Normal file
41
app/api/deps.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
|
from jose import jwt, JWTError
|
||||||
|
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.core.security import ALGORITHM
|
||||||
|
from app.schemas.token import TokenPayload
|
||||||
|
|
||||||
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
||||||
|
) -> User:
|
||||||
|
"""
|
||||||
|
Get the current user based on the 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=[ALGORITHM]
|
||||||
|
)
|
||||||
|
user_id: str = payload.get("sub")
|
||||||
|
if user_id is None:
|
||||||
|
raise credentials_exception
|
||||||
|
token_data = TokenPayload(sub=user_id, exp=payload.get("exp"))
|
||||||
|
except JWTError:
|
||||||
|
raise credentials_exception
|
||||||
|
|
||||||
|
user = db.query(User).filter(User.id == token_data.sub).first()
|
||||||
|
if user is None:
|
||||||
|
raise credentials_exception
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
return user
|
65
app/api/endpoints/auth.py
Normal file
65
app/api/endpoints/auth.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.core.security import create_access_token
|
||||||
|
from app.api.deps import get_db
|
||||||
|
from app.schemas.user import UserCreate, User
|
||||||
|
from app.schemas.token import Token
|
||||||
|
from app.crud import crud_user
|
||||||
|
from app.core.logging import logger
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=Token)
|
||||||
|
async def login(
|
||||||
|
db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
OAuth2 compatible token login, get an access token for future requests.
|
||||||
|
"""
|
||||||
|
user = crud_user.authenticate(
|
||||||
|
db, email=form_data.username, password=form_data.password
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
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"},
|
||||||
|
)
|
||||||
|
elif not user.is_active:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create access token
|
||||||
|
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
access_token = create_access_token(
|
||||||
|
subject=user.id, expires_delta=access_token_expires
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"User {user.id} logged in")
|
||||||
|
return {"access_token": access_token, "token_type": "bearer"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", response_model=User, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def register(user_in: UserCreate, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Register a new user.
|
||||||
|
"""
|
||||||
|
# Check if the user already exists
|
||||||
|
user = crud_user.get_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",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create new user
|
||||||
|
user = crud_user.create(db, obj_in=user_in)
|
||||||
|
logger.info(f"New user registered: {user.id}")
|
||||||
|
|
||||||
|
return user
|
101
app/api/endpoints/clients.py
Normal file
101
app/api/endpoints/clients.py
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from typing import List
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.api.deps import get_db, get_current_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.client import Client, ClientCreate, ClientUpdate
|
||||||
|
from app.crud import crud_client
|
||||||
|
from app.core.logging import log_activity
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[Client])
|
||||||
|
async def get_clients(
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Get all clients for the current user.
|
||||||
|
"""
|
||||||
|
clients = crud_client.get_multi_by_user(
|
||||||
|
db, user_id=current_user.id, skip=skip, limit=limit
|
||||||
|
)
|
||||||
|
return clients
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=Client, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_client(
|
||||||
|
client_in: ClientCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Create a new client.
|
||||||
|
"""
|
||||||
|
client = crud_client.create(db, obj_in=client_in, user_id=current_user.id)
|
||||||
|
log_activity(current_user.id, "create", "client", client.id)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{client_id}", response_model=Client)
|
||||||
|
async def get_client(
|
||||||
|
client_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Get a client by ID.
|
||||||
|
"""
|
||||||
|
client = crud_client.get_by_id(db, client_id=client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{client_id}", response_model=Client)
|
||||||
|
async def update_client(
|
||||||
|
client_id: str,
|
||||||
|
client_in: ClientUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update a client.
|
||||||
|
"""
|
||||||
|
client = crud_client.get_by_id(db, client_id=client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
client = crud_client.update(db, db_obj=client, obj_in=client_in)
|
||||||
|
log_activity(current_user.id, "update", "client", client.id)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{client_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
async def delete_client(
|
||||||
|
client_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Delete a client.
|
||||||
|
"""
|
||||||
|
client = crud_client.get_by_id(db, client_id=client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
crud_client.remove(db, client_id=client_id, user_id=current_user.id)
|
||||||
|
log_activity(current_user.id, "delete", "client", client_id)
|
||||||
|
return None
|
230
app/api/endpoints/invoices.py
Normal file
230
app/api/endpoints/invoices.py
Normal file
@ -0,0 +1,230 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from typing import List
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.api.deps import get_db, get_current_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.invoice import Invoice, InvoiceCreate, InvoiceUpdate, InvoiceItem, InvoiceItemCreate
|
||||||
|
from app.crud import crud_invoice, crud_client
|
||||||
|
from app.core.logging import log_activity
|
||||||
|
from app.utils.pdf import generate_invoice_pdf
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[Invoice])
|
||||||
|
async def get_invoices(
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Get all invoices for the current user.
|
||||||
|
"""
|
||||||
|
invoices = crud_invoice.get_multi_by_user(
|
||||||
|
db, user_id=current_user.id, skip=skip, limit=limit
|
||||||
|
)
|
||||||
|
|
||||||
|
# Calculate total for each invoice
|
||||||
|
for invoice in invoices:
|
||||||
|
total = sum(item.quantity * item.unit_price for item in invoice.items)
|
||||||
|
invoice.total = total
|
||||||
|
|
||||||
|
return invoices
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=Invoice, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_invoice(
|
||||||
|
invoice_in: InvoiceCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Create a new invoice.
|
||||||
|
"""
|
||||||
|
# Check if client exists and belongs to user
|
||||||
|
client = crud_client.get_by_id(db, client_id=invoice_in.client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
invoice = crud_invoice.create(db, obj_in=invoice_in, user_id=current_user.id)
|
||||||
|
log_activity(current_user.id, "create", "invoice", invoice.id)
|
||||||
|
|
||||||
|
# Calculate total
|
||||||
|
total = sum(item.quantity * item.unit_price for item in invoice.items)
|
||||||
|
invoice.total = total
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{invoice_id}", response_model=Invoice)
|
||||||
|
async def get_invoice(
|
||||||
|
invoice_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Get an invoice by ID.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Calculate total
|
||||||
|
total = sum(item.quantity * item.unit_price for item in invoice.items)
|
||||||
|
invoice.total = total
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{invoice_id}", response_model=Invoice)
|
||||||
|
async def update_invoice(
|
||||||
|
invoice_id: str,
|
||||||
|
invoice_in: InvoiceUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update an invoice.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# If client_id is changed, check if the new client exists and belongs to user
|
||||||
|
if invoice_in.client_id and invoice_in.client_id != invoice.client_id:
|
||||||
|
client = crud_client.get_by_id(db, client_id=invoice_in.client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
invoice = crud_invoice.update(db, db_obj=invoice, obj_in=invoice_in)
|
||||||
|
log_activity(current_user.id, "update", "invoice", invoice.id)
|
||||||
|
|
||||||
|
# Calculate total
|
||||||
|
total = sum(item.quantity * item.unit_price for item in invoice.items)
|
||||||
|
invoice.total = total
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{invoice_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
async def delete_invoice(
|
||||||
|
invoice_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Delete an invoice.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
crud_invoice.remove(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
log_activity(current_user.id, "delete", "invoice", invoice_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{invoice_id}/items", response_model=InvoiceItem, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def add_invoice_item(
|
||||||
|
invoice_id: str,
|
||||||
|
item_in: InvoiceItemCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Add an item to an invoice.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
item = crud_invoice.add_item(db, invoice_id=invoice_id, user_id=current_user.id, obj_in=item_in)
|
||||||
|
log_activity(current_user.id, "create", "invoice item", item.id)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{invoice_id}/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
async def delete_invoice_item(
|
||||||
|
invoice_id: str,
|
||||||
|
item_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Delete an item from an invoice.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
item = crud_invoice.remove_item(db, item_id=item_id, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice item not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
log_activity(current_user.id, "delete", "invoice item", item_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{invoice_id}/pdf")
|
||||||
|
async def get_invoice_pdf(
|
||||||
|
invoice_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Generate and download a PDF for an invoice.
|
||||||
|
"""
|
||||||
|
invoice = crud_invoice.get_by_id(db, invoice_id=invoice_id, user_id=current_user.id)
|
||||||
|
if not invoice:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Invoice not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
client = crud_client.get_by_id(db, client_id=invoice.client_id, user_id=current_user.id)
|
||||||
|
if not client:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
pdf_path = generate_invoice_pdf(invoice, client)
|
||||||
|
log_activity(current_user.id, "generate", "invoice PDF", invoice_id)
|
||||||
|
|
||||||
|
return FileResponse(
|
||||||
|
path=pdf_path,
|
||||||
|
filename=f"invoice_{invoice.invoice_number}.pdf",
|
||||||
|
media_type="application/pdf",
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
detail=f"Error generating PDF: {str(e)}",
|
||||||
|
)
|
31
app/api/endpoints/users.py
Normal file
31
app/api/endpoints/users.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.api.deps import get_db, get_current_user
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.user import User as UserSchema, UserUpdate
|
||||||
|
from app.crud import crud_user
|
||||||
|
from app.core.logging import log_activity
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserSchema)
|
||||||
|
async def read_users_me(current_user: User = Depends(get_current_user)):
|
||||||
|
"""
|
||||||
|
Get current user information.
|
||||||
|
"""
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/me", response_model=UserSchema)
|
||||||
|
async def update_user_me(
|
||||||
|
user_in: UserUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update current user information.
|
||||||
|
"""
|
||||||
|
user = crud_user.update(db, db_obj=current_user, obj_in=user_in)
|
||||||
|
log_activity(user.id, "update", "user profile")
|
||||||
|
return user
|
13
app/api/health.py
Normal file
13
app/api/health.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from app.db.session import get_db
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", tags=["health"])
|
||||||
|
async def health_check(db: AsyncSession = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Health check endpoint to verify the API is running and database connection is working.
|
||||||
|
"""
|
||||||
|
return {"status": "ok", "message": "API is running"}
|
10
app/api/routes.py
Normal file
10
app/api/routes.py
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
from app.api.endpoints import users, clients, invoices, auth
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Include API endpoints
|
||||||
|
router.include_router(auth.router, prefix="/auth", tags=["authentication"])
|
||||||
|
router.include_router(users.router, prefix="/users", tags=["users"])
|
||||||
|
router.include_router(clients.router, prefix="/clients", tags=["clients"])
|
||||||
|
router.include_router(invoices.router, prefix="/invoices", tags=["invoices"])
|
28
app/core/config.py
Normal file
28
app/core/config.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
from typing import List
|
||||||
|
import secrets
|
||||||
|
from pydantic import AnyHttpUrl, validator
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
# Secret key for JWT token generation
|
||||||
|
SECRET_KEY: str = secrets.token_urlsafe(32)
|
||||||
|
# 60 minutes * 24 hours * 8 days = 8 days
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
|
||||||
|
# CORS allowed origins
|
||||||
|
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||||
|
|
||||||
|
@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)
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
case_sensitive = True
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
34
app/core/logging.py
Normal file
34
app/core/logging.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
LOG_DIR = Path("/app") / "storage" / "logs"
|
||||||
|
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
LOG_FILE = LOG_DIR / "app.log"
|
||||||
|
|
||||||
|
# Configure loguru logger
|
||||||
|
logger.remove() # Remove default handler
|
||||||
|
logger.add(sys.stderr, level="INFO") # Add stderr handler
|
||||||
|
logger.add(
|
||||||
|
LOG_FILE,
|
||||||
|
rotation="10 MB", # Rotate when file reaches 10 MB
|
||||||
|
retention="30 days", # Keep logs for 30 days
|
||||||
|
compression="zip", # Compress rotated logs
|
||||||
|
level="DEBUG",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create a function to log user activity
|
||||||
|
def log_activity(user_id: str, action: str, object_type: str, object_id: str = None):
|
||||||
|
"""
|
||||||
|
Log user activity.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
user_id: ID of the user performing the action
|
||||||
|
action: The action performed (e.g., "create", "update", "delete")
|
||||||
|
object_type: The type of object the action was performed on (e.g., "invoice", "client")
|
||||||
|
object_id: The ID of the object the action was performed on (optional)
|
||||||
|
"""
|
||||||
|
if object_id:
|
||||||
|
logger.info(f"User {user_id} {action}d {object_type} {object_id}")
|
||||||
|
else:
|
||||||
|
logger.info(f"User {user_id} {action}d {object_type}")
|
40
app/core/security.py
Normal file
40
app/core/security.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any, Union
|
||||||
|
from jose import jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(
|
||||||
|
subject: Union[str, Any], expires_delta: 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=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)
|
66
app/crud/crud_client.py
Normal file
66
app/crud/crud_client.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
from typing import List, Optional, Dict, Any, Union
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.models.client import Client
|
||||||
|
from app.schemas.client import ClientCreate, ClientUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def get_by_id(db: Session, client_id: str, user_id: str) -> Optional[Client]:
|
||||||
|
"""
|
||||||
|
Get a client by ID, ensuring it belongs to the specified user.
|
||||||
|
"""
|
||||||
|
return db.query(Client).filter(
|
||||||
|
Client.id == client_id, Client.user_id == user_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
|
||||||
|
def get_multi_by_user(
|
||||||
|
db: Session, user_id: str, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[Client]:
|
||||||
|
"""
|
||||||
|
Get multiple clients for a user.
|
||||||
|
"""
|
||||||
|
return db.query(Client).filter(Client.user_id == user_id).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
|
||||||
|
def create(db: Session, *, obj_in: ClientCreate, user_id: str) -> Client:
|
||||||
|
"""
|
||||||
|
Create a new client.
|
||||||
|
"""
|
||||||
|
db_obj = Client(
|
||||||
|
**obj_in.dict(),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def update(
|
||||||
|
db: Session, *, db_obj: Client, obj_in: Union[ClientUpdate, Dict[str, Any]]
|
||||||
|
) -> Client:
|
||||||
|
"""
|
||||||
|
Update a client.
|
||||||
|
"""
|
||||||
|
update_data = obj_in if isinstance(obj_in, dict) else obj_in.dict(exclude_unset=True)
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
if hasattr(db_obj, field) and value is not None:
|
||||||
|
setattr(db_obj, field, value)
|
||||||
|
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def remove(db: Session, *, client_id: str, user_id: str) -> Optional[Client]:
|
||||||
|
"""
|
||||||
|
Delete a client.
|
||||||
|
"""
|
||||||
|
client = get_by_id(db, client_id=client_id, user_id=user_id)
|
||||||
|
if not client:
|
||||||
|
return None
|
||||||
|
db.delete(client)
|
||||||
|
db.commit()
|
||||||
|
return client
|
121
app/crud/crud_invoice.py
Normal file
121
app/crud/crud_invoice.py
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
from typing import List, Optional, Dict, Any, Union
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.models.invoice import Invoice, InvoiceItem
|
||||||
|
from app.schemas.invoice import InvoiceCreate, InvoiceUpdate, InvoiceItemCreate
|
||||||
|
|
||||||
|
|
||||||
|
def get_by_id(db: Session, invoice_id: str, user_id: str) -> Optional[Invoice]:
|
||||||
|
"""
|
||||||
|
Get an invoice by ID, ensuring it belongs to the specified user.
|
||||||
|
"""
|
||||||
|
return db.query(Invoice).filter(
|
||||||
|
Invoice.id == invoice_id, Invoice.user_id == user_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
|
||||||
|
def get_multi_by_user(
|
||||||
|
db: Session, user_id: str, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[Invoice]:
|
||||||
|
"""
|
||||||
|
Get multiple invoices for a user.
|
||||||
|
"""
|
||||||
|
return db.query(Invoice).filter(Invoice.user_id == user_id).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
|
||||||
|
def create(db: Session, *, obj_in: InvoiceCreate, user_id: str) -> Invoice:
|
||||||
|
"""
|
||||||
|
Create a new invoice with items.
|
||||||
|
"""
|
||||||
|
# Extract items from input
|
||||||
|
items_data = obj_in.items
|
||||||
|
obj_data = obj_in.dict(exclude={"items"})
|
||||||
|
|
||||||
|
# Create invoice
|
||||||
|
db_obj = Invoice(
|
||||||
|
**obj_data,
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.flush() # Flush to get the invoice ID
|
||||||
|
|
||||||
|
# Create invoice items
|
||||||
|
for item_data in items_data:
|
||||||
|
db_item = InvoiceItem(
|
||||||
|
**item_data.dict(),
|
||||||
|
invoice_id=db_obj.id,
|
||||||
|
)
|
||||||
|
db.add(db_item)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def update(
|
||||||
|
db: Session, *, db_obj: Invoice, obj_in: Union[InvoiceUpdate, Dict[str, Any]]
|
||||||
|
) -> Invoice:
|
||||||
|
"""
|
||||||
|
Update an invoice.
|
||||||
|
"""
|
||||||
|
update_data = obj_in if isinstance(obj_in, dict) else obj_in.dict(exclude_unset=True)
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
if hasattr(db_obj, field) and value is not None:
|
||||||
|
setattr(db_obj, field, value)
|
||||||
|
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def remove(db: Session, *, invoice_id: str, user_id: str) -> Optional[Invoice]:
|
||||||
|
"""
|
||||||
|
Delete an invoice.
|
||||||
|
"""
|
||||||
|
invoice = get_by_id(db, invoice_id=invoice_id, user_id=user_id)
|
||||||
|
if not invoice:
|
||||||
|
return None
|
||||||
|
db.delete(invoice)
|
||||||
|
db.commit()
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
def add_item(db: Session, *, invoice_id: str, user_id: str, obj_in: InvoiceItemCreate) -> Optional[InvoiceItem]:
|
||||||
|
"""
|
||||||
|
Add an item to an invoice.
|
||||||
|
"""
|
||||||
|
invoice = get_by_id(db, invoice_id=invoice_id, user_id=user_id)
|
||||||
|
if not invoice:
|
||||||
|
return None
|
||||||
|
|
||||||
|
db_obj = InvoiceItem(
|
||||||
|
**obj_in.dict(),
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def remove_item(db: Session, *, item_id: str, invoice_id: str, user_id: str) -> Optional[InvoiceItem]:
|
||||||
|
"""
|
||||||
|
Remove an item from an invoice.
|
||||||
|
"""
|
||||||
|
# First check if the invoice belongs to the user
|
||||||
|
invoice = get_by_id(db, invoice_id=invoice_id, user_id=user_id)
|
||||||
|
if not invoice:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Then get the item
|
||||||
|
item = db.query(InvoiceItem).filter(
|
||||||
|
InvoiceItem.id == item_id, InvoiceItem.invoice_id == invoice_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not item:
|
||||||
|
return None
|
||||||
|
|
||||||
|
db.delete(item)
|
||||||
|
db.commit()
|
||||||
|
return item
|
68
app/crud/crud_user.py
Normal file
68
app/crud/crud_user.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
from typing import Any, Dict, Optional, Union
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.user import UserCreate, UserUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def get(db: Session, user_id: str) -> Optional[User]:
|
||||||
|
"""
|
||||||
|
Get a user by ID.
|
||||||
|
"""
|
||||||
|
return db.query(User).filter(User.id == user_id).first()
|
||||||
|
|
||||||
|
|
||||||
|
def get_by_email(db: Session, email: str) -> Optional[User]:
|
||||||
|
"""
|
||||||
|
Get a user by email.
|
||||||
|
"""
|
||||||
|
return db.query(User).filter(User.email == email).first()
|
||||||
|
|
||||||
|
|
||||||
|
def create(db: Session, *, obj_in: UserCreate) -> User:
|
||||||
|
"""
|
||||||
|
Create a new user.
|
||||||
|
"""
|
||||||
|
db_obj = User(
|
||||||
|
email=obj_in.email,
|
||||||
|
hashed_password=get_password_hash(obj_in.password),
|
||||||
|
full_name=obj_in.full_name,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def update(
|
||||||
|
db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
|
||||||
|
) -> User:
|
||||||
|
"""
|
||||||
|
Update a user.
|
||||||
|
"""
|
||||||
|
update_data = obj_in if isinstance(obj_in, dict) else obj_in.dict(exclude_unset=True)
|
||||||
|
if "password" in update_data and update_data["password"]:
|
||||||
|
update_data["hashed_password"] = get_password_hash(update_data["password"])
|
||||||
|
del update_data["password"]
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
if hasattr(db_obj, field) and value is not None:
|
||||||
|
setattr(db_obj, field, value)
|
||||||
|
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate(db: Session, *, email: str, password: str) -> Optional[User]:
|
||||||
|
"""
|
||||||
|
Authenticate a user by email and password.
|
||||||
|
"""
|
||||||
|
user = get_by_email(db, email=email)
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, user.hashed_password):
|
||||||
|
return None
|
||||||
|
return user
|
1
app/db/base.py
Normal file
1
app/db/base.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Import all models here for Alembic to detect them
|
13
app/db/base_class.py
Normal file
13
app/db/base_class.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
from typing import Any
|
||||||
|
from sqlalchemy.ext.declarative import declared_attr
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
id: Any
|
||||||
|
__name__: str
|
||||||
|
|
||||||
|
# Generate __tablename__ automatically
|
||||||
|
@declared_attr.directive
|
||||||
|
def __tablename__(cls) -> str:
|
||||||
|
return cls.__name__.lower()
|
27
app/db/session.py
Normal file
27
app/db/session.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
# Create storage 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 function that yields db sessions.
|
||||||
|
"""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
18
app/models/client.py
Normal file
18
app/models/client.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from sqlalchemy import Column, String, ForeignKey
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
import uuid
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Client(Base):
|
||||||
|
id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
name = Column(String, index=True, nullable=False)
|
||||||
|
email = Column(String, index=True, nullable=False)
|
||||||
|
company = Column(String, nullable=True)
|
||||||
|
address = Column(String, nullable=True)
|
||||||
|
phone = Column(String, nullable=True)
|
||||||
|
user_id = Column(String, ForeignKey("user.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
user = relationship("User", back_populates="clients")
|
||||||
|
invoices = relationship("Invoice", back_populates="client", cascade="all, delete-orphan")
|
43
app/models/invoice.py
Normal file
43
app/models/invoice.py
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
from sqlalchemy import Column, String, Float, ForeignKey, Date, Enum, DateTime, func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
import uuid
|
||||||
|
import enum
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceStatus(str, enum.Enum):
|
||||||
|
DRAFT = "draft"
|
||||||
|
SENT = "sent"
|
||||||
|
PAID = "paid"
|
||||||
|
OVERDUE = "overdue"
|
||||||
|
CANCELLED = "cancelled"
|
||||||
|
|
||||||
|
|
||||||
|
class Invoice(Base):
|
||||||
|
id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
invoice_number = Column(String, index=True, nullable=False)
|
||||||
|
status = Column(Enum(InvoiceStatus), default=InvoiceStatus.DRAFT, nullable=False)
|
||||||
|
issued_date = Column(Date, default=datetime.utcnow().date, nullable=False)
|
||||||
|
due_date = Column(Date, default=lambda: (datetime.utcnow() + timedelta(days=30)).date(), nullable=False)
|
||||||
|
client_id = Column(String, ForeignKey("client.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
user_id = Column(String, ForeignKey("user.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
notes = Column(String, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=func.now(), nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
client = relationship("Client", back_populates="invoices")
|
||||||
|
user = relationship("User", back_populates="invoices")
|
||||||
|
items = relationship("InvoiceItem", back_populates="invoice", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItem(Base):
|
||||||
|
id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
description = Column(String, nullable=False)
|
||||||
|
quantity = Column(Float, nullable=False, default=1.0)
|
||||||
|
unit_price = Column(Float, nullable=False)
|
||||||
|
invoice_id = Column(String, ForeignKey("invoice.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
invoice = relationship("Invoice", back_populates="items")
|
16
app/models/user.py
Normal file
16
app/models/user.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
from sqlalchemy import Column, String, Boolean
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
import uuid
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
clients = relationship("Client", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
invoices = relationship("Invoice", back_populates="user", cascade="all, delete-orphan")
|
31
app/schemas/client.py
Normal file
31
app/schemas/client.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
from pydantic import BaseModel, EmailStr
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ClientBase(BaseModel):
|
||||||
|
name: str
|
||||||
|
email: EmailStr
|
||||||
|
company: Optional[str] = None
|
||||||
|
address: Optional[str] = None
|
||||||
|
phone: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ClientCreate(ClientBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ClientUpdate(ClientBase):
|
||||||
|
name: Optional[str] = None
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ClientInDBBase(ClientBase):
|
||||||
|
id: str
|
||||||
|
user_id: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class Client(ClientInDBBase):
|
||||||
|
pass
|
69
app/schemas/invoice.py
Normal file
69
app/schemas/invoice.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from typing import Optional, List
|
||||||
|
from datetime import date
|
||||||
|
from app.models.invoice import InvoiceStatus
|
||||||
|
|
||||||
|
|
||||||
|
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] = Field(None, gt=0)
|
||||||
|
unit_price: Optional[float] = Field(None, ge=0)
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItemInDBBase(InvoiceItemBase):
|
||||||
|
id: str
|
||||||
|
invoice_id: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItem(InvoiceItemInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceBase(BaseModel):
|
||||||
|
invoice_number: str
|
||||||
|
status: InvoiceStatus = InvoiceStatus.DRAFT
|
||||||
|
issued_date: date
|
||||||
|
due_date: date
|
||||||
|
notes: Optional[str] = None
|
||||||
|
client_id: str
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceCreate(InvoiceBase):
|
||||||
|
items: List[InvoiceItemCreate]
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceUpdate(BaseModel):
|
||||||
|
invoice_number: Optional[str] = None
|
||||||
|
status: Optional[InvoiceStatus] = None
|
||||||
|
issued_date: Optional[date] = None
|
||||||
|
due_date: Optional[date] = None
|
||||||
|
notes: Optional[str] = None
|
||||||
|
client_id: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceInDBBase(InvoiceBase):
|
||||||
|
id: str
|
||||||
|
user_id: str
|
||||||
|
created_at: date
|
||||||
|
updated_at: date
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class Invoice(InvoiceInDBBase):
|
||||||
|
items: List[InvoiceItem] = []
|
||||||
|
total: float = 0.0
|
11
app/schemas/token.py
Normal file
11
app/schemas/token.py
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class Token(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: str
|
||||||
|
|
||||||
|
|
||||||
|
class TokenPayload(BaseModel):
|
||||||
|
sub: str
|
||||||
|
exp: int
|
33
app/schemas/user.py
Normal file
33
app/schemas/user.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class UserBase(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str = Field(..., min_length=8)
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
password: Optional[str] = Field(None, min_length=8)
|
||||||
|
|
||||||
|
|
||||||
|
class UserInDBBase(UserBase):
|
||||||
|
id: str
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class User(UserInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UserInDB(UserInDBBase):
|
||||||
|
hashed_password: str
|
93
app/utils/pdf.py
Normal file
93
app/utils/pdf.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from reportlab.lib.pagesizes import letter
|
||||||
|
from reportlab.pdfgen import canvas
|
||||||
|
from app.models.invoice import Invoice
|
||||||
|
from app.models.client import Client
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
PDF_DIR = Path("/app") / "storage" / "pdfs"
|
||||||
|
PDF_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_invoice_pdf(invoice: Invoice, client: Client) -> str:
|
||||||
|
"""
|
||||||
|
Generate a PDF for an invoice and return the path to the PDF file.
|
||||||
|
"""
|
||||||
|
# Create a unique filename for the PDF
|
||||||
|
filename = f"invoice_{invoice.invoice_number}_{datetime.now().strftime('%Y%m%d%H%M%S')}.pdf"
|
||||||
|
pdf_path = PDF_DIR / filename
|
||||||
|
|
||||||
|
# Create a PDF using ReportLab
|
||||||
|
c = canvas.Canvas(str(pdf_path), pagesize=letter)
|
||||||
|
|
||||||
|
# Add invoice information to the PDF
|
||||||
|
c.setFont("Helvetica-Bold", 18)
|
||||||
|
c.drawString(50, 750, f"Invoice #{invoice.invoice_number}")
|
||||||
|
|
||||||
|
c.setFont("Helvetica", 12)
|
||||||
|
c.drawString(50, 730, f"Status: {invoice.status}")
|
||||||
|
c.drawString(50, 715, f"Issued Date: {invoice.issued_date}")
|
||||||
|
c.drawString(50, 700, f"Due Date: {invoice.due_date}")
|
||||||
|
|
||||||
|
# Add client information
|
||||||
|
c.setFont("Helvetica-Bold", 14)
|
||||||
|
c.drawString(50, 670, "Client Information")
|
||||||
|
|
||||||
|
c.setFont("Helvetica", 12)
|
||||||
|
c.drawString(50, 655, f"Name: {client.name}")
|
||||||
|
c.drawString(50, 640, f"Email: {client.email}")
|
||||||
|
if client.company:
|
||||||
|
c.drawString(50, 625, f"Company: {client.company}")
|
||||||
|
if client.address:
|
||||||
|
c.drawString(50, 610, f"Address: {client.address}")
|
||||||
|
if client.phone:
|
||||||
|
c.drawString(50, 595, f"Phone: {client.phone}")
|
||||||
|
|
||||||
|
# Add invoice items
|
||||||
|
c.setFont("Helvetica-Bold", 14)
|
||||||
|
c.drawString(50, 560, "Invoice Items")
|
||||||
|
|
||||||
|
c.setFont("Helvetica", 12)
|
||||||
|
y = 540
|
||||||
|
c.drawString(50, y, "Description")
|
||||||
|
c.drawString(300, y, "Quantity")
|
||||||
|
c.drawString(370, y, "Unit Price")
|
||||||
|
c.drawString(450, y, "Total")
|
||||||
|
|
||||||
|
y -= 20
|
||||||
|
total = 0
|
||||||
|
|
||||||
|
for item in invoice.items:
|
||||||
|
item_total = item.quantity * item.unit_price
|
||||||
|
total += item_total
|
||||||
|
|
||||||
|
c.drawString(50, y, item.description)
|
||||||
|
c.drawString(300, y, str(item.quantity))
|
||||||
|
c.drawString(370, y, f"${item.unit_price:.2f}")
|
||||||
|
c.drawString(450, y, f"${item_total:.2f}")
|
||||||
|
|
||||||
|
y -= 15
|
||||||
|
|
||||||
|
# Add a page break if needed
|
||||||
|
if y < 50:
|
||||||
|
c.showPage()
|
||||||
|
c.setFont("Helvetica-Bold", 14)
|
||||||
|
c.drawString(50, 750, "Invoice Items (continued)")
|
||||||
|
c.setFont("Helvetica", 12)
|
||||||
|
y = 730
|
||||||
|
|
||||||
|
# Add total
|
||||||
|
c.setFont("Helvetica-Bold", 14)
|
||||||
|
c.drawString(370, y - 20, "Total:")
|
||||||
|
c.drawString(450, y - 20, f"${total:.2f}")
|
||||||
|
|
||||||
|
# Add footer with notes
|
||||||
|
if invoice.notes:
|
||||||
|
c.setFont("Helvetica-Bold", 12)
|
||||||
|
c.drawString(50, 50, "Notes:")
|
||||||
|
c.setFont("Helvetica", 10)
|
||||||
|
c.drawString(50, 35, invoice.notes)
|
||||||
|
|
||||||
|
c.save()
|
||||||
|
|
||||||
|
return str(pdf_path)
|
30
main.py
Normal file
30
main.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.api.routes import router as api_router
|
||||||
|
from app.api.health import router as health_router
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Freelancer Invoicing API",
|
||||||
|
description="API for managing clients and invoices for freelancers",
|
||||||
|
version="0.1.0",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add CORS middleware
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"], # Allow all origins
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"], # Allow all methods
|
||||||
|
allow_headers=["*"], # Allow all headers
|
||||||
|
)
|
||||||
|
|
||||||
|
# Include routers
|
||||||
|
app.include_router(health_router)
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
80
migrations/env.py
Normal file
80
migrations/env.py
Normal file
@ -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.base 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.
|
||||||
|
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() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""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, # Key configuration for SQLite
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
26
migrations/script.py.mako
Normal file
26
migrations/script.py.mako
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
98
migrations/versions/initial_migration.py
Normal file
98
migrations/versions/initial_migration.py
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 1a2b3c4d5e6f
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-11-01 00:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = '1a2b3c4d5e6f'
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create user table
|
||||||
|
op.create_table(
|
||||||
|
'user',
|
||||||
|
sa.Column('id', sa.String(), 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.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.String(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(), nullable=False),
|
||||||
|
sa.Column('company', sa.String(), nullable=True),
|
||||||
|
sa.Column('address', sa.String(), nullable=True),
|
||||||
|
sa.Column('phone', sa.String(), nullable=True),
|
||||||
|
sa.Column('user_id', sa.String(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_client_email'), 'client', ['email'], unique=False)
|
||||||
|
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.String(), nullable=False),
|
||||||
|
sa.Column('invoice_number', sa.String(), nullable=False),
|
||||||
|
sa.Column('status', sa.Enum('DRAFT', 'SENT', 'PAID', 'OVERDUE', 'CANCELLED', name='invoicestatus'), nullable=False),
|
||||||
|
sa.Column('issued_date', sa.Date(), nullable=False),
|
||||||
|
sa.Column('due_date', sa.Date(), nullable=False),
|
||||||
|
sa.Column('client_id', sa.String(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.String(), nullable=False),
|
||||||
|
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(['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.String(), 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('invoice_id', sa.String(), 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)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
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_index(op.f('ix_client_email'), table_name='client')
|
||||||
|
op.drop_table('client')
|
||||||
|
op.drop_index(op.f('ix_user_id'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_email'), table_name='user')
|
||||||
|
op.drop_table('user')
|
14
requirements.txt
Normal file
14
requirements.txt
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
fastapi>=0.104.1
|
||||||
|
uvicorn>=0.24.0
|
||||||
|
sqlalchemy>=2.0.23
|
||||||
|
alembic>=1.12.1
|
||||||
|
python-jose[cryptography]>=3.3.0
|
||||||
|
passlib[bcrypt]>=1.7.4
|
||||||
|
python-multipart>=0.0.6
|
||||||
|
pydantic>=2.4.2
|
||||||
|
pydantic-settings>=2.0.3
|
||||||
|
reportlab>=4.0.7
|
||||||
|
loguru>=0.7.2
|
||||||
|
ruff>=0.1.3
|
||||||
|
python-dateutil>=2.8.2
|
||||||
|
email-validator>=2.1.0
|
Loading…
x
Reference in New Issue
Block a user