Implement invoice generation service
- Create FastAPI app structure - Set up SQLAlchemy with SQLite for database management - Implement invoice and invoice item models - Add Alembic for database migrations - Create invoice generation and retrieval API endpoints - Add health check endpoint - Set up Ruff for linting - Update README with project details
This commit is contained in:
parent
d085417d94
commit
0a65bff5f3
97
README.md
97
README.md
@ -1,3 +1,96 @@
|
|||||||
# FastAPI Application
|
# Invoice Generation Service
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
This is a FastAPI application for generating and managing invoices. It allows you to create, read, update, and delete invoices without requiring user signup.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Generate invoices with automatic invoice number generation
|
||||||
|
- Store invoice details in SQLite database
|
||||||
|
- Retrieve invoice information by ID or invoice number
|
||||||
|
- Update invoice details and status
|
||||||
|
- Delete invoices
|
||||||
|
- Health check endpoint
|
||||||
|
|
||||||
|
## Technical Stack
|
||||||
|
|
||||||
|
- **Framework**: FastAPI
|
||||||
|
- **Database**: SQLite with SQLAlchemy ORM
|
||||||
|
- **Migrations**: Alembic
|
||||||
|
- **Validation**: Pydantic
|
||||||
|
- **Linting**: Ruff
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── alembic.ini # Alembic configuration file
|
||||||
|
├── app # Application package
|
||||||
|
│ ├── api # API routes
|
||||||
|
│ │ └── routes # API route modules
|
||||||
|
│ │ ├── __init__.py # Routes initialization
|
||||||
|
│ │ └── invoices.py # Invoice routes
|
||||||
|
│ ├── core # Core functionality
|
||||||
|
│ │ ├── config.py # Application settings
|
||||||
|
│ │ ├── database.py # Database connection setup
|
||||||
|
│ │ └── utils.py # Utility functions
|
||||||
|
│ ├── models # SQLAlchemy models
|
||||||
|
│ │ ├── __init__.py # Models initialization
|
||||||
|
│ │ └── invoice.py # Invoice and InvoiceItem models
|
||||||
|
│ └── schemas # Pydantic schemas
|
||||||
|
│ ├── __init__.py # Schemas initialization
|
||||||
|
│ └── invoice.py # Invoice-related schemas
|
||||||
|
├── main.py # Application entry point
|
||||||
|
├── migrations # Alembic migrations
|
||||||
|
│ ├── env.py # Alembic environment
|
||||||
|
│ ├── script.py.mako # Migration script template
|
||||||
|
│ └── versions # Migration scripts
|
||||||
|
│ └── ef0aaab3a275_initial_database_tables.py # Initial migration
|
||||||
|
├── requirements.txt # Project dependencies
|
||||||
|
└── pyproject.toml # Ruff configuration
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
|
||||||
|
- `GET /health`: Check if the service is running
|
||||||
|
|
||||||
|
### Invoice Management
|
||||||
|
|
||||||
|
- `POST /api/v1/invoices`: Create a new invoice
|
||||||
|
- `GET /api/v1/invoices`: List all invoices (with pagination)
|
||||||
|
- `GET /api/v1/invoices/{invoice_id}`: Get a specific invoice by ID
|
||||||
|
- `POST /api/v1/invoices/find`: Find an invoice by invoice number
|
||||||
|
- `PATCH /api/v1/invoices/{invoice_id}`: Update an invoice
|
||||||
|
- `PATCH /api/v1/invoices/{invoice_id}/status`: Update invoice status
|
||||||
|
- `DELETE /api/v1/invoices/{invoice_id}`: Delete an invoice
|
||||||
|
|
||||||
|
## Setup and Installation
|
||||||
|
|
||||||
|
1. Clone the repository
|
||||||
|
2. Install dependencies:
|
||||||
|
```
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
3. Run migrations:
|
||||||
|
```
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
4. Start the application:
|
||||||
|
```
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Documentation
|
||||||
|
|
||||||
|
Once the application is running, you can access:
|
||||||
|
- Interactive API documentation at `/docs` (Swagger UI)
|
||||||
|
- Alternative API documentation at `/redoc` (ReDoc)
|
||||||
|
|
||||||
|
## Invoice Number Format
|
||||||
|
|
||||||
|
Invoices are automatically assigned a unique invoice number with the format:
|
||||||
|
- `INV-YYYYMM-XXXXXX`, where:
|
||||||
|
- `INV` is a fixed prefix
|
||||||
|
- `YYYYMM` is the year and month (e.g., 202307 for July 2023)
|
||||||
|
- `XXXXXX` is a random alphanumeric string
|
116
alembic.ini
Normal file
116
alembic.ini
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary directly
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||||
|
# ruff.options = --fix 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
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# This file is intentionally left empty to make the directory a Python package
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# This file is intentionally left empty to make the directory a Python package
|
6
app/api/routes/__init__.py
Normal file
6
app/api/routes/__init__.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.routes import invoices
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
api_router.include_router(invoices.router, prefix="/invoices", tags=["invoices"])
|
185
app/api/routes/invoices.py
Normal file
185
app/api/routes/invoices.py
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.core.utils import generate_invoice_number
|
||||||
|
from app.models.invoice import Invoice, InvoiceItem
|
||||||
|
from app.schemas.invoice import (
|
||||||
|
InvoiceCreate,
|
||||||
|
InvoiceDB,
|
||||||
|
InvoiceSearchQuery,
|
||||||
|
InvoiceStatusUpdate,
|
||||||
|
InvoiceUpdate,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=InvoiceDB, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_invoice(invoice_data: InvoiceCreate, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Create a new invoice.
|
||||||
|
"""
|
||||||
|
# Generate unique invoice number
|
||||||
|
invoice_number = generate_invoice_number()
|
||||||
|
|
||||||
|
# Create new invoice
|
||||||
|
db_invoice = Invoice(
|
||||||
|
invoice_number=invoice_number,
|
||||||
|
date_created=datetime.utcnow(),
|
||||||
|
due_date=invoice_data.due_date,
|
||||||
|
customer_name=invoice_data.customer_name,
|
||||||
|
customer_email=invoice_data.customer_email,
|
||||||
|
customer_address=invoice_data.customer_address,
|
||||||
|
notes=invoice_data.notes,
|
||||||
|
status="PENDING",
|
||||||
|
total_amount=0, # Will be calculated from items
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add to DB
|
||||||
|
db.add(db_invoice)
|
||||||
|
db.flush() # Flush to get the ID
|
||||||
|
|
||||||
|
# Create invoice items
|
||||||
|
total_amount = 0
|
||||||
|
for item_data in invoice_data.items:
|
||||||
|
item_amount = item_data.quantity * item_data.unit_price
|
||||||
|
total_amount += item_amount
|
||||||
|
|
||||||
|
db_item = InvoiceItem(
|
||||||
|
invoice_id=db_invoice.id,
|
||||||
|
description=item_data.description,
|
||||||
|
quantity=item_data.quantity,
|
||||||
|
unit_price=item_data.unit_price,
|
||||||
|
amount=item_amount,
|
||||||
|
)
|
||||||
|
db.add(db_item)
|
||||||
|
|
||||||
|
# Update total amount
|
||||||
|
db_invoice.total_amount = total_amount
|
||||||
|
|
||||||
|
# Commit the transaction
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_invoice)
|
||||||
|
|
||||||
|
return db_invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[InvoiceDB])
|
||||||
|
def get_invoices(
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Retrieve a list of invoices.
|
||||||
|
"""
|
||||||
|
invoices = db.query(Invoice).offset(skip).limit(limit).all()
|
||||||
|
return invoices
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{invoice_id}", response_model=InvoiceDB)
|
||||||
|
def get_invoice(invoice_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Retrieve a specific invoice by ID.
|
||||||
|
"""
|
||||||
|
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||||
|
if invoice is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Invoice with ID {invoice_id} not found",
|
||||||
|
)
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/find", response_model=InvoiceDB)
|
||||||
|
def find_invoice_by_number(query: InvoiceSearchQuery, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Find an invoice by its invoice number.
|
||||||
|
"""
|
||||||
|
invoice = db.query(Invoice).filter(Invoice.invoice_number == query.invoice_number).first()
|
||||||
|
if invoice is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Invoice with number {query.invoice_number} not found",
|
||||||
|
)
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{invoice_id}", response_model=InvoiceDB)
|
||||||
|
def update_invoice(
|
||||||
|
invoice_id: int,
|
||||||
|
invoice_update: InvoiceUpdate,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update an existing invoice.
|
||||||
|
"""
|
||||||
|
# Get the invoice
|
||||||
|
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||||
|
if invoice is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Invoice with ID {invoice_id} not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update invoice fields
|
||||||
|
update_data = invoice_update.dict(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(invoice, field, value)
|
||||||
|
|
||||||
|
# Commit changes
|
||||||
|
db.commit()
|
||||||
|
db.refresh(invoice)
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{invoice_id}/status", response_model=InvoiceDB)
|
||||||
|
def update_invoice_status(
|
||||||
|
invoice_id: int,
|
||||||
|
status_update: InvoiceStatusUpdate,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update the status of an invoice.
|
||||||
|
"""
|
||||||
|
# Get the invoice
|
||||||
|
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||||
|
if invoice is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Invoice with ID {invoice_id} not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update status
|
||||||
|
invoice.status = status_update.status
|
||||||
|
|
||||||
|
# Commit changes
|
||||||
|
db.commit()
|
||||||
|
db.refresh(invoice)
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{invoice_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
def delete_invoice(invoice_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Delete an invoice.
|
||||||
|
"""
|
||||||
|
# Get the invoice
|
||||||
|
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
|
||||||
|
if invoice is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Invoice with ID {invoice_id} not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Delete the invoice
|
||||||
|
db.delete(invoice)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return None
|
1
app/core/__init__.py
Normal file
1
app/core/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# This file is intentionally left empty to make the directory a Python package
|
29
app/core/config.py
Normal file
29
app/core/config.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
from typing import List, Union
|
||||||
|
|
||||||
|
from pydantic import AnyHttpUrl, validator
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
# API config
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
PROJECT_NAME: str = "Invoice Generation Service"
|
||||||
|
|
||||||
|
# CORS settings
|
||||||
|
BACKEND_CORS_ORIGINS: List[Union[str, AnyHttpUrl]] = []
|
||||||
|
|
||||||
|
@validator("BACKEND_CORS_ORIGINS", pre=True)
|
||||||
|
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[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
|
||||||
|
env_file = ".env"
|
||||||
|
|
||||||
|
|
||||||
|
# Create settings instance
|
||||||
|
settings = Settings()
|
29
app/core/database.py
Normal file
29
app/core/database.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
# Setup database directory
|
||||||
|
DB_DIR = Path("/app") / "storage" / "db"
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
engine = create_engine(
|
||||||
|
SQLALCHEMY_DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
# Dependency
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
49
app/core/utils.py
Normal file
49
app/core/utils.py
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import datetime
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
|
||||||
|
|
||||||
|
def generate_invoice_number(prefix="INV", length=6):
|
||||||
|
"""
|
||||||
|
Generate a unique invoice number.
|
||||||
|
|
||||||
|
Format: INV-{YEAR}{MONTH}-{RANDOM_ALPHANUMERIC}
|
||||||
|
Example: INV-202307-A1B2C3
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prefix (str): Prefix for the invoice number
|
||||||
|
length (int): Length of the random string
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Generated invoice number
|
||||||
|
"""
|
||||||
|
# Get current date for year-month part
|
||||||
|
today = datetime.datetime.now()
|
||||||
|
year_month = today.strftime("%Y%m")
|
||||||
|
|
||||||
|
# Generate random alphanumeric string
|
||||||
|
characters = string.ascii_uppercase + string.digits
|
||||||
|
random_str = ''.join(random.choice(characters) for _ in range(length))
|
||||||
|
|
||||||
|
# Combine to form invoice number
|
||||||
|
invoice_number = f"{prefix}-{year_month}-{random_str}"
|
||||||
|
|
||||||
|
return invoice_number
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_total_amount(items):
|
||||||
|
"""
|
||||||
|
Calculate the total amount of an invoice based on its items.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
items (list): List of invoice items, each with quantity and unit_price
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
float: Total amount
|
||||||
|
"""
|
||||||
|
total = 0.0
|
||||||
|
for item in items:
|
||||||
|
item_amount = item.quantity * item.unit_price
|
||||||
|
total += item_amount
|
||||||
|
|
||||||
|
return total
|
1
app/models/__init__.py
Normal file
1
app/models/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
from app.models.invoice import Invoice, InvoiceItem # noqa: F401
|
46
app/models/invoice.py
Normal file
46
app/models/invoice.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
Column,
|
||||||
|
String,
|
||||||
|
Integer,
|
||||||
|
Float,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Invoice(Base):
|
||||||
|
__tablename__ = "invoices"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
invoice_number = Column(String(255), unique=True, index=True, nullable=False)
|
||||||
|
date_created = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
|
||||||
|
due_date = Column(DateTime, nullable=False)
|
||||||
|
customer_name = Column(String(255), nullable=False)
|
||||||
|
customer_email = Column(String(255), nullable=True)
|
||||||
|
customer_address = Column(Text, nullable=True)
|
||||||
|
total_amount = Column(Float, nullable=False)
|
||||||
|
status = Column(String(50), default="PENDING", nullable=False)
|
||||||
|
notes = Column(Text, nullable=True)
|
||||||
|
|
||||||
|
# Relationship with invoice items
|
||||||
|
items = relationship("InvoiceItem", back_populates="invoice", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItem(Base):
|
||||||
|
__tablename__ = "invoice_items"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
invoice_id = Column(Integer, ForeignKey("invoices.id"), nullable=False)
|
||||||
|
description = Column(String(255), nullable=False)
|
||||||
|
quantity = Column(Float, nullable=False)
|
||||||
|
unit_price = Column(Float, nullable=False)
|
||||||
|
amount = Column(Float, nullable=False)
|
||||||
|
|
||||||
|
# Relationship with invoice
|
||||||
|
invoice = relationship("Invoice", back_populates="items")
|
11
app/schemas/__init__.py
Normal file
11
app/schemas/__init__.py
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
from app.schemas.invoice import ( # noqa: F401
|
||||||
|
InvoiceBase,
|
||||||
|
InvoiceCreate,
|
||||||
|
InvoiceDB,
|
||||||
|
InvoiceUpdate,
|
||||||
|
InvoiceItemBase,
|
||||||
|
InvoiceItemCreate,
|
||||||
|
InvoiceItemDB,
|
||||||
|
InvoiceSearchQuery,
|
||||||
|
InvoiceStatusUpdate
|
||||||
|
)
|
77
app/schemas/invoice.py
Normal file
77
app/schemas/invoice.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, validator
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItemBase(BaseModel):
|
||||||
|
description: str
|
||||||
|
quantity: float
|
||||||
|
unit_price: float
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItemCreate(InvoiceItemBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceItemDB(InvoiceItemBase):
|
||||||
|
id: int
|
||||||
|
invoice_id: int
|
||||||
|
amount: float
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceBase(BaseModel):
|
||||||
|
customer_name: str
|
||||||
|
customer_email: Optional[str] = None
|
||||||
|
customer_address: Optional[str] = None
|
||||||
|
due_date: datetime
|
||||||
|
notes: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceCreate(InvoiceBase):
|
||||||
|
items: List[InvoiceItemCreate]
|
||||||
|
|
||||||
|
@validator("items")
|
||||||
|
def validate_items(cls, v):
|
||||||
|
if not v or len(v) == 0:
|
||||||
|
raise ValueError("Invoice must have at least one item")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceUpdate(BaseModel):
|
||||||
|
customer_name: Optional[str] = None
|
||||||
|
customer_email: Optional[str] = None
|
||||||
|
customer_address: Optional[str] = None
|
||||||
|
due_date: Optional[datetime] = None
|
||||||
|
status: Optional[str] = None
|
||||||
|
notes: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceDB(InvoiceBase):
|
||||||
|
id: int
|
||||||
|
invoice_number: str
|
||||||
|
date_created: datetime
|
||||||
|
total_amount: float
|
||||||
|
status: str
|
||||||
|
items: List[InvoiceItemDB]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceSearchQuery(BaseModel):
|
||||||
|
invoice_number: str
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceStatusUpdate(BaseModel):
|
||||||
|
status: str = Field(..., description="New status for the invoice")
|
||||||
|
|
||||||
|
@validator("status")
|
||||||
|
def validate_status(cls, v):
|
||||||
|
allowed_statuses = ["PENDING", "PAID", "CANCELLED"]
|
||||||
|
if v not in allowed_statuses:
|
||||||
|
raise ValueError(f"Status must be one of {', '.join(allowed_statuses)}")
|
||||||
|
return v
|
37
main.py
Normal file
37
main.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.api.routes import api_router
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
description="Invoice Generation Service API",
|
||||||
|
version="0.1.0",
|
||||||
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set all CORS enabled origins
|
||||||
|
if settings.BACKEND_CORS_ORIGINS:
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Include API router
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", status_code=200)
|
||||||
|
def health():
|
||||||
|
"""Health check endpoint"""
|
||||||
|
return {"status": "healthy"}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
78
migrations/env.py
Normal file
78
migrations/env.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
import sys
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
|
# Add the project base directory to the Python path
|
||||||
|
sys.path.append("")
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# Import your models here to auto-generate migrations
|
||||||
|
from app.core.database import Base # noqa: E402
|
||||||
|
|
||||||
|
# Set up target metadata
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
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, # For SQLite batch mode
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
58
migrations/versions/ef0aaab3a275_initial_database_tables.py
Normal file
58
migrations/versions/ef0aaab3a275_initial_database_tables.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
"""Initial database tables
|
||||||
|
|
||||||
|
Revision ID: ef0aaab3a275
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-07-20 10:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'ef0aaab3a275'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('invoices',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('invoice_number', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('date_created', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('due_date', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('customer_name', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('customer_email', sa.String(length=255), nullable=True),
|
||||||
|
sa.Column('customer_address', sa.Text(), nullable=True),
|
||||||
|
sa.Column('total_amount', sa.Float(), nullable=False),
|
||||||
|
sa.Column('status', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('notes', sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_invoices_id'), 'invoices', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_invoices_invoice_number'), 'invoices', ['invoice_number'], unique=True)
|
||||||
|
|
||||||
|
op.create_table('invoice_items',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('invoice_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('description', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('quantity', sa.Float(), nullable=False),
|
||||||
|
sa.Column('unit_price', sa.Float(), nullable=False),
|
||||||
|
sa.Column('amount', sa.Float(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['invoice_id'], ['invoices.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_invoice_items_id'), 'invoice_items', ['id'], unique=False)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(op.f('ix_invoice_items_id'), table_name='invoice_items')
|
||||||
|
op.drop_table('invoice_items')
|
||||||
|
op.drop_index(op.f('ix_invoices_invoice_number'), table_name='invoices')
|
||||||
|
op.drop_index(op.f('ix_invoices_id'), table_name='invoices')
|
||||||
|
op.drop_table('invoices')
|
||||||
|
# ### end Alembic commands ###
|
26
pyproject.toml
Normal file
26
pyproject.toml
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
[tool.ruff]
|
||||||
|
# Enable flake8-bugbear (`B`) rules.
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
# Exclude a variety of commonly ignored directories.
|
||||||
|
exclude = [
|
||||||
|
".git",
|
||||||
|
".env",
|
||||||
|
".venv",
|
||||||
|
"__pycache__",
|
||||||
|
".pytest_cache",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Allow imports relative to the "app" directory to support absolute imports
|
||||||
|
src = ["app"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "B"]
|
||||||
|
ignore = ["E501", "B008"] # Ignore line length violations and function calls in defaults
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"__init__.py" = ["F401"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.isort]
|
||||||
|
# Only known first party imports.
|
||||||
|
known-first-party = ["app"]
|
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
fastapi>=0.100.0
|
||||||
|
uvicorn>=0.22.0
|
||||||
|
sqlalchemy>=2.0.0
|
||||||
|
alembic>=1.11.1
|
||||||
|
pydantic>=2.0.0
|
||||||
|
pydantic-settings>=2.0.0
|
||||||
|
python-dateutil>=2.8.2
|
||||||
|
typing-extensions>=4.7.1
|
||||||
|
ruff>=0.0.292
|
||||||
|
python-dotenv>=1.0.0
|
Loading…
x
Reference in New Issue
Block a user