service with accrual interest and loan update tested
All checks were successful
Backend CI / unit-test (push) Successful in 48s
All checks were successful
Backend CI / unit-test (push) Successful in 48s
This commit is contained in:
@@ -56,9 +56,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AuthMiddleWare(BaseHTTPMiddleware):
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response: # noqa: PLR0911
|
||||
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: # noqa: PLR0911
|
||||
if request.url.path in EXCEPT_PATHS:
|
||||
return await call_next(request)
|
||||
|
||||
@@ -84,21 +82,15 @@ class AuthMiddleWare(BaseHTTPMiddleware):
|
||||
with db_factory.get_session_ctx_manager() as request_session:
|
||||
hashed_token = security.hash_session_token_sha256(token)
|
||||
request.state.db_session = request_session
|
||||
login_session: Sessions | None = crud.get_login_session_by_token_hash(
|
||||
request_session, hashed_token
|
||||
)
|
||||
login_session: Sessions | None = crud.get_login_session_by_token_hash(request_session, hashed_token)
|
||||
if not login_session:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
content={"detail": "Unauthorized"},
|
||||
)
|
||||
session_expires_utc = login_session.expires_at.replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
session_expires_utc = login_session.expires_at.replace(tzinfo=timezone.utc)
|
||||
if session_expires_utc < datetime.now(timezone.utc):
|
||||
crud.delete_login_session(
|
||||
request_session, login_session.session_token_hash
|
||||
)
|
||||
crud.delete_login_session(request_session, login_session.session_token_hash)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
content={"detail": "Unauthorized"},
|
||||
@@ -108,12 +100,8 @@ class AuthMiddleWare(BaseHTTPMiddleware):
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
content={"detail": "Unauthorized"},
|
||||
)
|
||||
if session_expires_utc - datetime.now(timezone.utc) < timedelta(
|
||||
seconds=3600
|
||||
):
|
||||
updated_expiry = datetime.now(timezone.utc) + timedelta(
|
||||
seconds=settings.settings.session_expiry_seconds
|
||||
)
|
||||
if session_expires_utc - datetime.now(timezone.utc) < timedelta(seconds=3600):
|
||||
updated_expiry = datetime.now(timezone.utc) + timedelta(seconds=settings.settings.session_expiry_seconds)
|
||||
else:
|
||||
updated_expiry = session_expires_utc
|
||||
updated_session: SessionsUpdate = SessionsUpdate(
|
||||
@@ -124,9 +112,7 @@ class AuthMiddleWare(BaseHTTPMiddleware):
|
||||
)
|
||||
user_id = login_session.user_id
|
||||
request.state.user_id = user_id
|
||||
crud.update_login_session(
|
||||
request_session, hashed_token, update_session=updated_session
|
||||
)
|
||||
crud.update_login_session(request_session, hashed_token, update_session=updated_session)
|
||||
except Exception:
|
||||
logger.exception("Failed to authenticate user: \n")
|
||||
return JSONResponse(
|
||||
@@ -160,9 +146,7 @@ def register_user_service(db_session: Session, user_in: UserCreate) -> UserRead:
|
||||
return user
|
||||
|
||||
|
||||
def authenticate_user_service(
|
||||
db_session: Session, user_in: UserLogin
|
||||
) -> tuple[SessionsCreate, str] | None:
|
||||
def authenticate_user_service(db_session: Session, user_in: UserLogin) -> tuple[SessionsCreate, str] | None:
|
||||
user = crud.get_user_by_username(db_session, user_in.username)
|
||||
if not user:
|
||||
return None
|
||||
@@ -187,14 +171,10 @@ def authenticate_user_service(
|
||||
|
||||
|
||||
# Exchanges service
|
||||
def create_exchange_service(
|
||||
db_session: Session, user_id: int, name: str, notes: str | None
|
||||
) -> ExchangesCreate:
|
||||
def create_exchange_service(db_session: Session, user_id: int, name: str, notes: str | None) -> ExchangesCreate:
|
||||
existing_exchange = crud.get_exchange_by_name_and_user_id(db_session, name, user_id)
|
||||
if existing_exchange:
|
||||
raise ExchangeAlreadyExistsError(
|
||||
"Exchange with the same name already exists for this user"
|
||||
)
|
||||
raise ExchangeAlreadyExistsError("Exchange with the same name already exists for this user")
|
||||
exchange_data = ExchangesCreate(
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
@@ -213,9 +193,7 @@ def create_exchange_service(
|
||||
return exchange_dto
|
||||
|
||||
|
||||
def get_exchanges_by_user_service(
|
||||
db_session: Session, user_id: int
|
||||
) -> list[ExchangesRead]:
|
||||
def get_exchanges_by_user_service(db_session: Session, user_id: int) -> list[ExchangesRead]:
|
||||
exchanges = crud.get_all_exchanges_by_user_id(db_session, user_id)
|
||||
return [ExchangesRead.model_validate(exchange) for exchange in exchanges]
|
||||
|
||||
@@ -234,22 +212,16 @@ def update_exchanges_service(
|
||||
raise ExchangeNotFoundError("Exchange not found")
|
||||
|
||||
if name:
|
||||
other_exchange = crud.get_exchange_by_name_and_user_id(
|
||||
db_session, name, user_id
|
||||
)
|
||||
other_exchange = crud.get_exchange_by_name_and_user_id(db_session, name, user_id)
|
||||
if other_exchange and other_exchange.id != existing_exchange.id:
|
||||
raise ExchangeAlreadyExistsError(
|
||||
"Another exchange with the same name already exists for this user"
|
||||
)
|
||||
raise ExchangeAlreadyExistsError("Another exchange with the same name already exists for this user")
|
||||
|
||||
exchange_data = ExchangesBase(
|
||||
name=name or existing_exchange.name,
|
||||
notes=notes or existing_exchange.notes,
|
||||
)
|
||||
try:
|
||||
exchange = crud.update_exchange(
|
||||
db_session, cast("int", existing_exchange.id), update_data=exchange_data
|
||||
)
|
||||
exchange = crud.update_exchange(db_session, cast("int", existing_exchange.id), update_data=exchange_data)
|
||||
except Exception as e:
|
||||
logger.exception("Failed to update exchange: \n")
|
||||
raise ServiceError("Failed to update exchange") from e
|
||||
@@ -257,9 +229,7 @@ def update_exchanges_service(
|
||||
|
||||
|
||||
# Cycle Service
|
||||
def create_cycle_service(
|
||||
db_session: Session, user_id: int, cycle_data: CycleBase
|
||||
) -> CycleRead:
|
||||
def create_cycle_service(db_session: Session, user_id: int, cycle_data: CycleBase) -> CycleRead:
|
||||
raise NotImplementedError("Cycle creation not implemented")
|
||||
cycle_data_dict = cycle_data.model_dump()
|
||||
cycle_data_dict["user_id"] = user_id
|
||||
@@ -268,9 +238,7 @@ def create_cycle_service(
|
||||
return CycleRead.model_validate(created_cycle)
|
||||
|
||||
|
||||
def get_cycle_by_id_service(
|
||||
db_session: Session, user_id: int, cycle_id: int
|
||||
) -> CycleRead:
|
||||
def get_cycle_by_id_service(db_session: Session, user_id: int, cycle_id: int) -> CycleRead:
|
||||
cycle = crud.get_cycle_by_id(db_session, cycle_id)
|
||||
if not cycle:
|
||||
raise CycleNotFoundError("Cycle not found")
|
||||
@@ -289,18 +257,12 @@ def _validate_cycle_update_data(cycle_data: CycleUpdate) -> tuple[bool, str]: #
|
||||
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"
|
||||
if (
|
||||
cycle_data.capital_exposure_cents is not None
|
||||
and cycle_data.capital_exposure_cents < 0
|
||||
):
|
||||
if cycle_data.capital_exposure_cents is not None and cycle_data.capital_exposure_cents < 0:
|
||||
return False, "capital_exposure_cents must be non-negative"
|
||||
if (
|
||||
cycle_data.funding_source is not None
|
||||
and cycle_data.funding_source != "CASH"
|
||||
and (
|
||||
cycle_data.loan_amount_cents is None
|
||||
or cycle_data.loan_interest_rate_tenth_bps is None
|
||||
)
|
||||
and (cycle_data.loan_amount_cents is None or cycle_data.loan_interest_rate_tenth_bps is None)
|
||||
):
|
||||
return (
|
||||
False,
|
||||
@@ -308,10 +270,7 @@ def _validate_cycle_update_data(cycle_data: CycleUpdate) -> tuple[bool, str]: #
|
||||
)
|
||||
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"
|
||||
if (
|
||||
cycle_data.loan_interest_rate_tenth_bps is not None
|
||||
and cycle_data.loan_interest_rate_tenth_bps < 0
|
||||
):
|
||||
if cycle_data.loan_interest_rate_tenth_bps is not None and cycle_data.loan_interest_rate_tenth_bps < 0:
|
||||
return False, "loan_interest_rate_tenth_bps must be non-negative"
|
||||
return True, ""
|
||||
|
||||
@@ -324,13 +283,9 @@ def _create_cycle_loan_event(
|
||||
) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
today = now.date()
|
||||
existing_loan_event = crud.get_loan_event_by_cycle_id_and_effective_date(
|
||||
db_session, cycle_id, today
|
||||
)
|
||||
existing_loan_event = crud.get_loan_event_by_cycle_id_and_effective_date(db_session, cycle_id, today)
|
||||
if existing_loan_event:
|
||||
raise CycleLoanEventExistsError(
|
||||
"A loan event with the same effective_date already exists for this cycle."
|
||||
)
|
||||
raise CycleLoanEventExistsError("A loan event with the same effective_date already exists for this cycle.")
|
||||
loan_event_data = CycleLoanChangeEventBase(
|
||||
cycle_id=cycle_id,
|
||||
effective_date=today,
|
||||
@@ -345,9 +300,7 @@ def _create_cycle_loan_event(
|
||||
raise ServiceError("Failed to create cycle loan event") from e
|
||||
|
||||
|
||||
def update_cycle_service(
|
||||
db_session: Session, user_id: int, cycle_data: CycleUpdate
|
||||
) -> CycleRead:
|
||||
def update_cycle_service(db_session: Session, user_id: int, cycle_data: CycleUpdate) -> CycleRead:
|
||||
is_valid, err_msg = _validate_cycle_update_data(cycle_data)
|
||||
if not is_valid:
|
||||
raise InvalidCycleDataError(err_msg)
|
||||
@@ -357,10 +310,7 @@ def update_cycle_service(
|
||||
raise CycleNotFoundError("Cycle not found")
|
||||
if existing_cycle.user_id != user_id:
|
||||
raise CycleNotFoundError("Cycle not found")
|
||||
if (
|
||||
cycle_data.loan_amount_cents is not None
|
||||
or cycle_data.loan_interest_rate_tenth_bps is not None
|
||||
):
|
||||
if cycle_data.loan_amount_cents is not None or cycle_data.loan_interest_rate_tenth_bps is not None:
|
||||
_create_cycle_loan_event(
|
||||
db_session,
|
||||
cycle_id,
|
||||
@@ -372,16 +322,14 @@ def update_cycle_service(
|
||||
cycle_data_with_user_id: CycleBase = CycleBase.model_validate(provided_data_dict)
|
||||
|
||||
try:
|
||||
updated_cycle = crud.update_cycle(
|
||||
db_session, cycle_id, update_data=cycle_data_with_user_id
|
||||
)
|
||||
updated_cycle = crud.update_cycle(db_session, cycle_id, update_data=cycle_data_with_user_id)
|
||||
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)
|
||||
|
||||
|
||||
def accural_interest_service(db_session: Session, cycle_id: int) -> None:
|
||||
def accrual_interest_service(db_session: Session, cycle_id: int) -> None:
|
||||
cycle = crud.get_cycle_by_id(db_session, cycle_id)
|
||||
if not cycle:
|
||||
logger.exception("Cycle not found for interest accrual")
|
||||
@@ -390,9 +338,7 @@ def accural_interest_service(db_session: Session, cycle_id: int) -> None:
|
||||
logger.info("Cycle has no loan, skipping interest accrual")
|
||||
return
|
||||
today = datetime.now(timezone.utc).date()
|
||||
amount_cents = round(
|
||||
cycle.loan_amount_cents * cycle.loan_interest_rate_tenth_bps / 100000 / 365
|
||||
)
|
||||
amount_cents = round(cycle.loan_amount_cents * cycle.loan_interest_rate_tenth_bps / 100000 / 365)
|
||||
try:
|
||||
crud.create_cycle_daily_accrual(
|
||||
db_session,
|
||||
@@ -432,18 +378,13 @@ def _append_cashflows(trade_data: TradeCreate) -> TradeCreate:
|
||||
|
||||
def _validate_trade_data(trade_data: TradeCreate) -> bool:
|
||||
return not (
|
||||
trade_data.trade_type in ("SELL_PUT", "SELL_CALL")
|
||||
and (trade_data.expiry_date is None or trade_data.strike_price_cents is None)
|
||||
trade_data.trade_type in ("SELL_PUT", "SELL_CALL") and (trade_data.expiry_date is None or trade_data.strike_price_cents is None)
|
||||
)
|
||||
|
||||
|
||||
def create_trade_service(
|
||||
db_session: Session, user_id: int, trade_data: TradeCreate
|
||||
) -> TradeRead:
|
||||
def create_trade_service(db_session: Session, user_id: int, trade_data: TradeCreate) -> TradeRead:
|
||||
if not _validate_trade_data(trade_data):
|
||||
raise InvalidTradeDataError(
|
||||
"Invalid trade data: expiry_date and strike_price_cents are required for SELL_PUT and SELL_CALL trades"
|
||||
)
|
||||
raise InvalidTradeDataError("Invalid trade data: expiry_date and strike_price_cents are required for SELL_PUT and SELL_CALL trades")
|
||||
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)
|
||||
@@ -452,9 +393,7 @@ def create_trade_service(
|
||||
return TradeRead.model_validate(created_trade)
|
||||
|
||||
|
||||
def get_trade_by_id_service(
|
||||
db_session: Session, user_id: int, trade_id: int
|
||||
) -> TradeRead:
|
||||
def get_trade_by_id_service(db_session: Session, user_id: int, trade_id: int) -> TradeRead:
|
||||
trade = crud.get_trade_by_id(db_session, trade_id)
|
||||
if not trade:
|
||||
raise TradeNotFoundError("Trade not found")
|
||||
@@ -463,27 +402,21 @@ def get_trade_by_id_service(
|
||||
return TradeRead.model_validate(trade)
|
||||
|
||||
|
||||
def update_trade_friendly_name_service(
|
||||
db_session: Session, user_id: int, trade_id: int, friendly_name: str
|
||||
) -> TradeRead:
|
||||
def update_trade_friendly_name_service(db_session: Session, user_id: int, trade_id: int, friendly_name: str) -> TradeRead:
|
||||
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:
|
||||
updated_trade = crud.update_trade_friendly_name(
|
||||
db_session, trade_id, friendly_name
|
||||
)
|
||||
updated_trade = crud.update_trade_friendly_name(db_session, trade_id, friendly_name)
|
||||
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)
|
||||
|
||||
|
||||
def update_trade_note_service(
|
||||
db_session: Session, user_id: int, trade_id: int, note: str | None
|
||||
) -> TradeRead:
|
||||
def update_trade_note_service(db_session: Session, user_id: int, trade_id: int, note: str | None) -> TradeRead:
|
||||
existing_trade = crud.get_trade_by_id(db_session, trade_id)
|
||||
if not existing_trade:
|
||||
raise TradeNotFoundError("Trade not found")
|
||||
|
||||
Reference in New Issue
Block a user