2025-09-22 22:51:59 +02:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
from datetime import datetime, timedelta, timezone
|
2025-09-23 17:37:14 +02:00
|
|
|
from typing import TYPE_CHECKING, cast
|
2025-09-22 17:35:10 +02:00
|
|
|
|
|
|
|
|
from fastapi import Request, Response, status
|
|
|
|
|
from fastapi.responses import JSONResponse
|
2025-09-23 17:37:14 +02:00
|
|
|
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
2025-09-22 17:35:10 +02:00
|
|
|
|
|
|
|
|
import settings
|
|
|
|
|
from trading_journal import crud, security
|
2025-09-23 23:35:15 +02:00
|
|
|
from trading_journal.dto import (
|
|
|
|
|
CycleBase,
|
|
|
|
|
CycleCreate,
|
2025-10-03 11:55:30 +02:00
|
|
|
CycleLoanChangeEventBase,
|
2025-09-24 17:33:27 +02:00
|
|
|
CycleRead,
|
|
|
|
|
CycleUpdate,
|
2025-09-23 23:35:15 +02:00
|
|
|
ExchangesBase,
|
|
|
|
|
ExchangesCreate,
|
|
|
|
|
ExchangesRead,
|
|
|
|
|
SessionsCreate,
|
|
|
|
|
SessionsUpdate,
|
2025-09-24 17:33:27 +02:00
|
|
|
TradeCreate,
|
|
|
|
|
TradeRead,
|
2025-09-23 23:35:15 +02:00
|
|
|
UserCreate,
|
|
|
|
|
UserLogin,
|
|
|
|
|
UserRead,
|
|
|
|
|
)
|
2025-10-03 11:55:30 +02:00
|
|
|
from trading_journal.service_error import (
|
|
|
|
|
CycleLoanEventExistsError,
|
|
|
|
|
CycleNotFoundError,
|
|
|
|
|
ExchangeAlreadyExistsError,
|
|
|
|
|
ExchangeNotFoundError,
|
|
|
|
|
InvalidCycleDataError,
|
|
|
|
|
InvalidTradeDataError,
|
|
|
|
|
ServiceError,
|
|
|
|
|
TradeNotFoundError,
|
|
|
|
|
UserAlreadyExistsError,
|
|
|
|
|
)
|
2025-09-22 17:35:10 +02:00
|
|
|
|
2025-09-23 17:37:14 +02:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
from sqlmodel import Session
|
|
|
|
|
|
|
|
|
|
from trading_journal.db import Database
|
|
|
|
|
from trading_journal.models import Sessions
|
|
|
|
|
|
2025-09-22 22:51:59 +02:00
|
|
|
|
2025-09-22 17:35:10 +02:00
|
|
|
EXCEPT_PATHS = [
|
|
|
|
|
f"{settings.settings.api_base}/status",
|
|
|
|
|
f"{settings.settings.api_base}/register",
|
2025-09-22 22:51:59 +02:00
|
|
|
f"{settings.settings.api_base}/login",
|
2025-09-22 17:35:10 +02:00
|
|
|
]
|
|
|
|
|
|
2025-09-22 22:51:59 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2025-09-22 17:35:10 +02:00
|
|
|
|
|
|
|
|
class AuthMiddleWare(BaseHTTPMiddleware):
|
2025-10-08 12:34:20 +02:00
|
|
|
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: # noqa: PLR0911
|
2025-09-22 17:35:10 +02:00
|
|
|
if request.url.path in EXCEPT_PATHS:
|
|
|
|
|
return await call_next(request)
|
|
|
|
|
|
|
|
|
|
token = request.cookies.get("session_token")
|
|
|
|
|
if not token:
|
|
|
|
|
auth_header = request.headers.get("Authorization")
|
|
|
|
|
if auth_header and auth_header.startswith("Bearer "):
|
|
|
|
|
token = auth_header[len("Bearer ") :]
|
|
|
|
|
|
|
|
|
|
if not token:
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
content={"detail": "Unauthorized"},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
db_factory: Database | None = getattr(request.app.state, "db_factory", None)
|
|
|
|
|
if db_factory is None:
|
2025-10-03 11:55:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
content={"detail": "db factory not configured"},
|
|
|
|
|
)
|
2025-09-22 17:35:10 +02:00
|
|
|
try:
|
|
|
|
|
with db_factory.get_session_ctx_manager() as request_session:
|
|
|
|
|
hashed_token = security.hash_session_token_sha256(token)
|
|
|
|
|
request.state.db_session = request_session
|
2025-10-08 12:34:20 +02:00
|
|
|
login_session: Sessions | None = crud.get_login_session_by_token_hash(request_session, hashed_token)
|
2025-09-22 22:51:59 +02:00
|
|
|
if not login_session:
|
2025-10-03 11:55:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
content={"detail": "Unauthorized"},
|
|
|
|
|
)
|
2025-10-08 12:34:20 +02:00
|
|
|
session_expires_utc = login_session.expires_at.replace(tzinfo=timezone.utc)
|
2025-09-22 22:51:59 +02:00
|
|
|
if session_expires_utc < datetime.now(timezone.utc):
|
2025-10-08 12:34:20 +02:00
|
|
|
crud.delete_login_session(request_session, login_session.session_token_hash)
|
2025-10-03 11:55:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
content={"detail": "Unauthorized"},
|
|
|
|
|
)
|
2025-09-22 22:51:59 +02:00
|
|
|
if login_session.user.is_active is False:
|
2025-10-03 11:55:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
content={"detail": "Unauthorized"},
|
|
|
|
|
)
|
2025-10-08 12:34:20 +02:00
|
|
|
if session_expires_utc - datetime.now(timezone.utc) < timedelta(seconds=3600):
|
|
|
|
|
updated_expiry = datetime.now(timezone.utc) + timedelta(seconds=settings.settings.session_expiry_seconds)
|
2025-09-22 22:51:59 +02:00
|
|
|
else:
|
|
|
|
|
updated_expiry = session_expires_utc
|
|
|
|
|
updated_session: SessionsUpdate = SessionsUpdate(
|
|
|
|
|
last_seen_at=datetime.now(timezone.utc),
|
|
|
|
|
last_used_ip=request.client.host if request.client else None,
|
|
|
|
|
user_agent=request.headers.get("User-Agent"),
|
|
|
|
|
expires_at=updated_expiry,
|
|
|
|
|
)
|
|
|
|
|
user_id = login_session.user_id
|
|
|
|
|
request.state.user_id = user_id
|
2025-10-08 12:34:20 +02:00
|
|
|
crud.update_login_session(request_session, hashed_token, update_session=updated_session)
|
2025-09-22 22:51:59 +02:00
|
|
|
except Exception:
|
|
|
|
|
logger.exception("Failed to authenticate user: \n")
|
2025-10-03 11:55:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
content={"detail": "Internal server error"},
|
|
|
|
|
)
|
2025-09-22 17:35:10 +02:00
|
|
|
|
2025-09-22 22:51:59 +02:00
|
|
|
return await call_next(request)
|
2025-09-22 17:35:10 +02:00
|
|
|
|
|
|
|
|
|
2025-09-23 23:35:15 +02:00
|
|
|
# User service
|
2025-09-22 17:35:10 +02:00
|
|
|
def register_user_service(db_session: Session, user_in: UserCreate) -> UserRead:
|
|
|
|
|
if crud.get_user_by_username(db_session, user_in.username):
|
|
|
|
|
raise UserAlreadyExistsError("username already exists")
|
|
|
|
|
hashed = security.hash_password(user_in.password)
|
2025-09-22 22:51:59 +02:00
|
|
|
user_data: dict = {
|
|
|
|
|
"username": user_in.username,
|
|
|
|
|
"password_hash": hashed,
|
|
|
|
|
}
|
2025-09-22 17:35:10 +02:00
|
|
|
try:
|
2025-09-22 22:51:59 +02:00
|
|
|
user = crud.create_user(db_session, user_data=user_data)
|
2025-09-22 17:35:10 +02:00
|
|
|
try:
|
|
|
|
|
# prefer pydantic's from_orm if DTO supports orm_mode
|
|
|
|
|
user = UserRead.model_validate(user)
|
|
|
|
|
except Exception as e:
|
2025-09-23 17:37:14 +02:00
|
|
|
logger.exception("Failed to convert user to UserRead: ")
|
2025-09-22 17:35:10 +02:00
|
|
|
raise ServiceError("Failed to convert user to UserRead") from e
|
|
|
|
|
except Exception as e:
|
2025-09-22 22:51:59 +02:00
|
|
|
logger.exception("Failed to create user:")
|
2025-09-22 17:35:10 +02:00
|
|
|
raise ServiceError("Failed to create user") from e
|
|
|
|
|
return user
|
2025-09-22 22:51:59 +02:00
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def authenticate_user_service(db_session: Session, user_in: UserLogin) -> tuple[SessionsCreate, str] | None:
|
2025-09-22 22:51:59 +02:00
|
|
|
user = crud.get_user_by_username(db_session, user_in.username)
|
|
|
|
|
if not user:
|
|
|
|
|
return None
|
2025-09-23 17:37:14 +02:00
|
|
|
user_id_val = cast("int", user.id)
|
2025-09-22 22:51:59 +02:00
|
|
|
|
|
|
|
|
if not security.verify_password(user_in.password, user.password_hash):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
token = security.generate_session_token()
|
|
|
|
|
token_hashed = security.hash_session_token_sha256(token)
|
|
|
|
|
try:
|
|
|
|
|
session = crud.create_login_session(
|
|
|
|
|
session=db_session,
|
2025-09-23 17:37:14 +02:00
|
|
|
user_id=user_id_val,
|
2025-09-22 22:51:59 +02:00
|
|
|
session_token_hash=token_hashed,
|
|
|
|
|
session_length_seconds=settings.settings.session_expiry_seconds,
|
|
|
|
|
)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to create login session: \n")
|
|
|
|
|
raise ServiceError("Failed to create login session") from e
|
|
|
|
|
return SessionsCreate.model_validate(session), token
|
|
|
|
|
|
|
|
|
|
|
2025-09-22 23:07:28 +02:00
|
|
|
# Exchanges service
|
2025-10-08 12:34:20 +02:00
|
|
|
def create_exchange_service(db_session: Session, user_id: int, name: str, notes: str | None) -> ExchangesCreate:
|
2025-09-22 23:07:28 +02:00
|
|
|
existing_exchange = crud.get_exchange_by_name_and_user_id(db_session, name, user_id)
|
|
|
|
|
if existing_exchange:
|
2025-10-08 12:34:20 +02:00
|
|
|
raise ExchangeAlreadyExistsError("Exchange with the same name already exists for this user")
|
2025-09-22 23:07:28 +02:00
|
|
|
exchange_data = ExchangesCreate(
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
name=name,
|
|
|
|
|
notes=notes,
|
|
|
|
|
)
|
|
|
|
|
try:
|
|
|
|
|
exchange = crud.create_exchange(db_session, exchange_data=exchange_data)
|
|
|
|
|
try:
|
|
|
|
|
exchange_dto = ExchangesCreate.model_validate(exchange)
|
|
|
|
|
except Exception as e:
|
2025-09-23 23:35:15 +02:00
|
|
|
logger.exception("Failed to convert exchange to ExchangesCreate:")
|
2025-09-22 23:07:28 +02:00
|
|
|
raise ServiceError("Failed to convert exchange to ExchangesCreate") from e
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to create exchange:")
|
|
|
|
|
raise ServiceError("Failed to create exchange") from e
|
|
|
|
|
return exchange_dto
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def get_exchanges_by_user_service(db_session: Session, user_id: int) -> list[ExchangesRead]:
|
2025-09-22 23:07:28 +02:00
|
|
|
exchanges = crud.get_all_exchanges_by_user_id(db_session, user_id)
|
2025-09-23 23:35:15 +02:00
|
|
|
return [ExchangesRead.model_validate(exchange) for exchange in exchanges]
|
|
|
|
|
|
|
|
|
|
|
2025-10-03 11:55:30 +02:00
|
|
|
def update_exchanges_service(
|
|
|
|
|
db_session: Session,
|
|
|
|
|
user_id: int,
|
|
|
|
|
exchange_id: int,
|
|
|
|
|
name: str | None,
|
|
|
|
|
notes: str | None,
|
|
|
|
|
) -> ExchangesBase:
|
2025-09-23 23:35:15 +02:00
|
|
|
existing_exchange = crud.get_exchange_by_id(db_session, exchange_id)
|
|
|
|
|
if not existing_exchange:
|
|
|
|
|
raise ExchangeNotFoundError("Exchange not found")
|
|
|
|
|
if existing_exchange.user_id != user_id:
|
|
|
|
|
raise ExchangeNotFoundError("Exchange not found")
|
|
|
|
|
|
|
|
|
|
if name:
|
2025-10-08 12:34:20 +02:00
|
|
|
other_exchange = crud.get_exchange_by_name_and_user_id(db_session, name, user_id)
|
2025-09-23 23:35:15 +02:00
|
|
|
if other_exchange and other_exchange.id != existing_exchange.id:
|
2025-10-08 12:34:20 +02:00
|
|
|
raise ExchangeAlreadyExistsError("Another exchange with the same name already exists for this user")
|
2025-09-23 23:35:15 +02:00
|
|
|
|
|
|
|
|
exchange_data = ExchangesBase(
|
|
|
|
|
name=name or existing_exchange.name,
|
|
|
|
|
notes=notes or existing_exchange.notes,
|
|
|
|
|
)
|
|
|
|
|
try:
|
2025-10-08 12:34:20 +02:00
|
|
|
exchange = crud.update_exchange(db_session, cast("int", existing_exchange.id), update_data=exchange_data)
|
2025-09-23 23:35:15 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to update exchange: \n")
|
|
|
|
|
raise ServiceError("Failed to update exchange") from e
|
|
|
|
|
return ExchangesBase.model_validate(exchange)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Cycle Service
|
2025-10-08 12:34:20 +02:00
|
|
|
def create_cycle_service(db_session: Session, user_id: int, cycle_data: CycleBase) -> CycleRead:
|
2025-09-29 16:48:28 +02:00
|
|
|
raise NotImplementedError("Cycle creation not implemented")
|
2025-09-23 23:35:15 +02:00
|
|
|
cycle_data_dict = cycle_data.model_dump()
|
|
|
|
|
cycle_data_dict["user_id"] = user_id
|
|
|
|
|
cycle_data_with_user_id: CycleCreate = CycleCreate.model_validate(cycle_data_dict)
|
2025-09-24 17:33:27 +02:00
|
|
|
created_cycle = crud.create_cycle(db_session, cycle_data=cycle_data_with_user_id)
|
|
|
|
|
return CycleRead.model_validate(created_cycle)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def get_cycle_by_id_service(db_session: Session, user_id: int, cycle_id: int) -> CycleRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
cycle = crud.get_cycle_by_id(db_session, cycle_id)
|
|
|
|
|
if not cycle:
|
|
|
|
|
raise CycleNotFoundError("Cycle not found")
|
|
|
|
|
if cycle.user_id != user_id:
|
|
|
|
|
raise CycleNotFoundError("Cycle not found")
|
|
|
|
|
return CycleRead.model_validate(cycle)
|
2025-09-22 23:07:28 +02:00
|
|
|
|
|
|
|
|
|
2025-09-24 17:33:27 +02:00
|
|
|
def get_cycles_by_user_service(db_session: Session, user_id: int) -> list[CycleRead]:
|
|
|
|
|
cycles = crud.get_cycles_by_user_id(db_session, user_id)
|
|
|
|
|
return [CycleRead.model_validate(cycle) for cycle in cycles]
|
|
|
|
|
|
|
|
|
|
|
2025-09-24 21:02:21 +02:00
|
|
|
def _validate_cycle_update_data(cycle_data: CycleUpdate) -> tuple[bool, str]: # noqa: PLR0911
|
2025-09-24 17:33:27 +02:00
|
|
|
if cycle_data.status == "CLOSED" and cycle_data.end_date is None:
|
|
|
|
|
return False, "end_date is required when status is CLOSED"
|
|
|
|
|
if cycle_data.status == "OPEN" and cycle_data.end_date is not None:
|
|
|
|
|
return False, "end_date must be empty when status is OPEN"
|
2025-10-08 12:34:20 +02:00
|
|
|
if cycle_data.capital_exposure_cents is not None and cycle_data.capital_exposure_cents < 0:
|
2025-09-24 21:02:21 +02:00
|
|
|
return False, "capital_exposure_cents must be non-negative"
|
|
|
|
|
if (
|
|
|
|
|
cycle_data.funding_source is not None
|
|
|
|
|
and cycle_data.funding_source != "CASH"
|
2025-10-08 12:34:20 +02:00
|
|
|
and (cycle_data.loan_amount_cents is None or cycle_data.loan_interest_rate_tenth_bps is None)
|
2025-09-24 21:02:21 +02:00
|
|
|
):
|
2025-10-03 11:55:30 +02:00
|
|
|
return (
|
|
|
|
|
False,
|
|
|
|
|
"loan_amount_cents and loan_interest_rate_tenth_bps are required when funding_source is not CASH",
|
|
|
|
|
)
|
2025-09-24 21:02:21 +02:00
|
|
|
if cycle_data.loan_amount_cents is not None and cycle_data.loan_amount_cents < 0:
|
|
|
|
|
return False, "loan_amount_cents must be non-negative"
|
2025-10-08 12:34:20 +02:00
|
|
|
if cycle_data.loan_interest_rate_tenth_bps is not None and cycle_data.loan_interest_rate_tenth_bps < 0:
|
2025-09-24 21:02:21 +02:00
|
|
|
return False, "loan_interest_rate_tenth_bps must be non-negative"
|
2025-09-24 17:33:27 +02:00
|
|
|
return True, ""
|
|
|
|
|
|
|
|
|
|
|
2025-10-03 11:55:30 +02:00
|
|
|
def _create_cycle_loan_event(
|
|
|
|
|
db_session: Session,
|
|
|
|
|
cycle_id: int,
|
|
|
|
|
loan_amount_cents: int | None,
|
|
|
|
|
loan_interest_rate_tenth_bps: int | None,
|
|
|
|
|
) -> None:
|
|
|
|
|
now = datetime.now(timezone.utc)
|
|
|
|
|
today = now.date()
|
2025-10-08 12:34:20 +02:00
|
|
|
existing_loan_event = crud.get_loan_event_by_cycle_id_and_effective_date(db_session, cycle_id, today)
|
2025-10-03 11:55:30 +02:00
|
|
|
if existing_loan_event:
|
2025-10-08 12:34:20 +02:00
|
|
|
raise CycleLoanEventExistsError("A loan event with the same effective_date already exists for this cycle.")
|
2025-10-03 11:55:30 +02:00
|
|
|
loan_event_data = CycleLoanChangeEventBase(
|
|
|
|
|
cycle_id=cycle_id,
|
|
|
|
|
effective_date=today,
|
|
|
|
|
loan_amount_cents=loan_amount_cents,
|
|
|
|
|
loan_interest_rate_tenth_bps=loan_interest_rate_tenth_bps,
|
|
|
|
|
created_at=now,
|
|
|
|
|
)
|
|
|
|
|
try:
|
|
|
|
|
crud.create_cycle_loan_event(db_session, loan_event_data)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to create cycle loan event: \n")
|
|
|
|
|
raise ServiceError("Failed to create cycle loan event") from e
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def update_cycle_service(db_session: Session, user_id: int, cycle_data: CycleUpdate) -> CycleRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
is_valid, err_msg = _validate_cycle_update_data(cycle_data)
|
|
|
|
|
if not is_valid:
|
|
|
|
|
raise InvalidCycleDataError(err_msg)
|
|
|
|
|
cycle_id = cast("int", cycle_data.id)
|
|
|
|
|
existing_cycle = crud.get_cycle_by_id(db_session, cycle_id)
|
|
|
|
|
if not existing_cycle:
|
|
|
|
|
raise CycleNotFoundError("Cycle not found")
|
|
|
|
|
if existing_cycle.user_id != user_id:
|
|
|
|
|
raise CycleNotFoundError("Cycle not found")
|
2025-10-08 12:34:20 +02:00
|
|
|
if cycle_data.loan_amount_cents is not None or cycle_data.loan_interest_rate_tenth_bps is not None:
|
2025-10-03 11:55:30 +02:00
|
|
|
_create_cycle_loan_event(
|
|
|
|
|
db_session,
|
|
|
|
|
cycle_id,
|
|
|
|
|
cycle_data.loan_amount_cents,
|
|
|
|
|
cycle_data.loan_interest_rate_tenth_bps,
|
|
|
|
|
)
|
2025-09-24 17:33:27 +02:00
|
|
|
|
|
|
|
|
provided_data_dict = cycle_data.model_dump(exclude_unset=True)
|
|
|
|
|
cycle_data_with_user_id: CycleBase = CycleBase.model_validate(provided_data_dict)
|
|
|
|
|
|
|
|
|
|
try:
|
2025-10-08 12:34:20 +02:00
|
|
|
updated_cycle = crud.update_cycle(db_session, cycle_id, update_data=cycle_data_with_user_id)
|
2025-09-24 17:33:27 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to update cycle: \n")
|
|
|
|
|
raise ServiceError("Failed to update cycle") from e
|
|
|
|
|
return CycleRead.model_validate(updated_cycle)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def accrual_interest_service(db_session: Session, cycle_id: int) -> None:
|
2025-10-03 11:55:30 +02:00
|
|
|
cycle = crud.get_cycle_by_id(db_session, cycle_id)
|
|
|
|
|
if not cycle:
|
|
|
|
|
logger.exception("Cycle not found for interest accrual")
|
|
|
|
|
raise CycleNotFoundError("Cycle not found")
|
|
|
|
|
if cycle.loan_amount_cents is None or cycle.loan_interest_rate_tenth_bps is None:
|
|
|
|
|
logger.info("Cycle has no loan, skipping interest accrual")
|
|
|
|
|
return
|
|
|
|
|
today = datetime.now(timezone.utc).date()
|
2025-10-08 12:34:20 +02:00
|
|
|
amount_cents = round(cycle.loan_amount_cents * cycle.loan_interest_rate_tenth_bps / 100000 / 365)
|
2025-10-03 11:55:30 +02:00
|
|
|
try:
|
|
|
|
|
crud.create_cycle_daily_accrual(
|
|
|
|
|
db_session,
|
|
|
|
|
cycle_id=cycle_id,
|
|
|
|
|
accrual_date=today,
|
|
|
|
|
accrual_amount_cents=amount_cents,
|
|
|
|
|
)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to create cycle interest accrual: \n")
|
|
|
|
|
raise ServiceError("Failed to create cycle interest accrual") from e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def flush_interest_accruals_service(db_session: Session) -> None:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2025-09-24 17:33:27 +02:00
|
|
|
# Trades service
|
|
|
|
|
def _append_cashflows(trade_data: TradeCreate) -> TradeCreate:
|
|
|
|
|
sign_multipler: int
|
2025-10-03 11:55:30 +02:00
|
|
|
if trade_data.trade_type in (
|
|
|
|
|
"SELL_PUT",
|
|
|
|
|
"SELL_CALL",
|
|
|
|
|
"EXERCISE_CALL",
|
|
|
|
|
"CLOSE_LONG_SPOT",
|
|
|
|
|
"SHORT_SPOT",
|
|
|
|
|
):
|
2025-09-24 17:33:27 +02:00
|
|
|
sign_multipler = 1
|
|
|
|
|
else:
|
|
|
|
|
sign_multipler = -1
|
|
|
|
|
quantity = trade_data.quantity * trade_data.quantity_multiplier
|
|
|
|
|
gross_cash_flow_cents = quantity * trade_data.price_cents * sign_multipler
|
|
|
|
|
net_cash_flow_cents = gross_cash_flow_cents - trade_data.commission_cents
|
|
|
|
|
trade_data.gross_cash_flow_cents = gross_cash_flow_cents
|
|
|
|
|
trade_data.net_cash_flow_cents = net_cash_flow_cents
|
|
|
|
|
return trade_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _validate_trade_data(trade_data: TradeCreate) -> bool:
|
|
|
|
|
return not (
|
2025-10-08 12:34:20 +02:00
|
|
|
trade_data.trade_type in ("SELL_PUT", "SELL_CALL") and (trade_data.expiry_date is None or trade_data.strike_price_cents is None)
|
2025-09-24 17:33:27 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def create_trade_service(db_session: Session, user_id: int, trade_data: TradeCreate) -> TradeRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
if not _validate_trade_data(trade_data):
|
2025-10-08 12:34:20 +02:00
|
|
|
raise InvalidTradeDataError("Invalid trade data: expiry_date and strike_price_cents are required for SELL_PUT and SELL_CALL trades")
|
2025-09-24 17:33:27 +02:00
|
|
|
trade_data_dict = trade_data.model_dump()
|
|
|
|
|
trade_data_dict["user_id"] = user_id
|
|
|
|
|
trade_data_with_user_id: TradeCreate = TradeCreate.model_validate(trade_data_dict)
|
|
|
|
|
trade_data_with_user_id = _append_cashflows(trade_data_with_user_id)
|
|
|
|
|
created_trade = crud.create_trade(db_session, trade_data=trade_data_with_user_id)
|
|
|
|
|
return TradeRead.model_validate(created_trade)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def get_trade_by_id_service(db_session: Session, user_id: int, trade_id: int) -> TradeRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
trade = crud.get_trade_by_id(db_session, trade_id)
|
|
|
|
|
if not trade:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
if trade.user_id != user_id:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
return TradeRead.model_validate(trade)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def update_trade_friendly_name_service(db_session: Session, user_id: int, trade_id: int, friendly_name: str) -> TradeRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
existing_trade = crud.get_trade_by_id(db_session, trade_id)
|
|
|
|
|
if not existing_trade:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
if existing_trade.user_id != user_id:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
try:
|
2025-10-08 12:34:20 +02:00
|
|
|
updated_trade = crud.update_trade_friendly_name(db_session, trade_id, friendly_name)
|
2025-09-24 17:33:27 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to update trade friendly name: \n")
|
|
|
|
|
raise ServiceError("Failed to update trade friendly name") from e
|
|
|
|
|
return TradeRead.model_validate(updated_trade)
|
|
|
|
|
|
|
|
|
|
|
2025-10-08 12:34:20 +02:00
|
|
|
def update_trade_note_service(db_session: Session, user_id: int, trade_id: int, note: str | None) -> TradeRead:
|
2025-09-24 17:33:27 +02:00
|
|
|
existing_trade = crud.get_trade_by_id(db_session, trade_id)
|
|
|
|
|
if not existing_trade:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
if existing_trade.user_id != user_id:
|
|
|
|
|
raise TradeNotFoundError("Trade not found")
|
|
|
|
|
if note is None:
|
|
|
|
|
note = ""
|
|
|
|
|
try:
|
|
|
|
|
updated_trade = crud.update_trade_note(db_session, trade_id, note)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.exception("Failed to update trade notes: \n")
|
|
|
|
|
raise ServiceError("Failed to update trade notes") from e
|
|
|
|
|
return TradeRead.model_validate(updated_trade)
|