77 lines
2.6 KiB
Python
77 lines
2.6 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status, Request, Query
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import func
|
|
from typing import List, Union, Optional
|
|
from slowapi import Limiter
|
|
from slowapi.util import get_remote_address
|
|
from database import get_db, Transaction
|
|
from schemas import TransactionCreate, Transaction as TransactionSchema
|
|
from auth import verify_token
|
|
import json
|
|
|
|
# Create rate limiter instance
|
|
limiter = Limiter(key_func=get_remote_address)
|
|
|
|
router = APIRouter(prefix="/shared", tags=["shared"])
|
|
|
|
@router.get("", response_model=List[TransactionSchema])
|
|
@router.get("/", response_model=List[TransactionSchema])
|
|
@limiter.limit("30/minute")
|
|
def get_transactions(
|
|
request: Request,
|
|
search: Optional[str] = Query(None, description="Search term for item names"),
|
|
token: str = Depends(verify_token),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Get all bank transactions, optionally filtered by search term"""
|
|
query = db.query(Transaction)
|
|
|
|
# Apply search filter if provided
|
|
if search and search.strip():
|
|
search_term = f"%{search.strip().lower()}%"
|
|
query = query.filter(func.lower(Transaction.item).like(search_term))
|
|
|
|
# Get all transactions ordered by user first, then by created_at
|
|
# This ensures all transactions for the same user are grouped together
|
|
transactions = query.order_by(Transaction.user.asc(), Transaction.created_at.asc()).all()
|
|
return transactions
|
|
|
|
@router.post("", response_model=List[TransactionSchema])
|
|
@router.post("/", response_model=List[TransactionSchema])
|
|
@limiter.limit("20/minute")
|
|
async def create_transaction(
|
|
request: Request,
|
|
token: str = Depends(verify_token),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Create one or more bank transactions"""
|
|
# Get raw JSON data
|
|
body = await request.body()
|
|
data = json.loads(body.decode('utf-8'))
|
|
|
|
# Handle both single transaction and array of transactions
|
|
if isinstance(data, dict):
|
|
transactions_data = [data]
|
|
else:
|
|
transactions_data = data
|
|
|
|
created_transactions = []
|
|
|
|
for transaction_data in transactions_data:
|
|
db_transaction = Transaction(
|
|
item_id=transaction_data.get('item_id'),
|
|
item=transaction_data.get('item'),
|
|
user=transaction_data.get('user'),
|
|
amount=transaction_data.get('amount')
|
|
)
|
|
db.add(db_transaction)
|
|
created_transactions.append(db_transaction)
|
|
|
|
db.commit()
|
|
|
|
# Refresh all transactions
|
|
for transaction in created_transactions:
|
|
db.refresh(transaction)
|
|
|
|
return created_transactions
|