Добавлены новые модели для интеграционных токенов в bff_models.py и sql_models.py. Реализованы функции для создания, обновления и удаления токенов в main.py, а также обновлено заполнение базы данных в fill_db.py для генерации токенов. Обновлены запросы к базе данных для учета новых полей и логики работы с токенами.
This commit is contained in:
111
main.py
111
main.py
@@ -8,7 +8,7 @@ from fastapi import (
|
||||
Body,
|
||||
)
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlmodel import SQLModel, Session, select
|
||||
from sqlmodel import SQLModel, Session, select, Field
|
||||
from typing import Optional, List, Dict
|
||||
from datetime import timedelta, datetime
|
||||
from bff_models import (
|
||||
@@ -37,7 +37,10 @@ from bff_models import (
|
||||
AutoApproveSettingsRequest,
|
||||
ApproveTransactionsRequest,
|
||||
AgentTransactionResponse,
|
||||
TransactionStatus
|
||||
TransactionStatus,
|
||||
IntegrationTokenResponse,
|
||||
IntegrationTokenCreateRequest,
|
||||
IntegrationTokenUpdateRequest
|
||||
)
|
||||
from tg_models import RefAddRequest, RefResponse, RegisterRequest, RefAddResponse, RefStatResponse, StatResponse
|
||||
from sql_models import (
|
||||
@@ -48,7 +51,8 @@ from sql_models import (
|
||||
AgentTransaction,
|
||||
PartnerTransaction,
|
||||
AgentBalance,
|
||||
Account
|
||||
Account,
|
||||
IntegrationToken
|
||||
)
|
||||
from sqlalchemy import func
|
||||
import hashlib
|
||||
@@ -65,6 +69,7 @@ from helpers_bff import (
|
||||
pwd_context,
|
||||
)
|
||||
|
||||
|
||||
# Создание движка базы данных
|
||||
SQLModel.metadata.create_all(AUTH_DB_ENGINE)
|
||||
|
||||
@@ -236,11 +241,11 @@ def get_dashboard_chart_total(current_account: Account = Depends(get_current_acc
|
||||
# Группируем продажи по дате (день)
|
||||
result = db.exec(
|
||||
select(
|
||||
func.strftime('%Y-%m-%d', Sale.sale_date).label('date'),
|
||||
func.strftime('%Y-%m-%d', Sale.sale_dttm).label('date'),
|
||||
func.sum(Sale.cost).label('revenue'),
|
||||
func.count(Sale.id).label('sales')
|
||||
).where(Sale.company_id == current_account.company_id).group_by(func.strftime('%Y-%m-%d', Sale.sale_date))
|
||||
.order_by(func.strftime('%Y-%m-%d', Sale.sale_date))
|
||||
).where(Sale.company_id == current_account.company_id).group_by(func.strftime('%Y-%m-%d', Sale.sale_dttm))
|
||||
.order_by(func.strftime('%Y-%m-%d', Sale.sale_dttm))
|
||||
).all()
|
||||
# Преобразуем результат в нужный формат
|
||||
data = [
|
||||
@@ -368,9 +373,9 @@ def get_sales_stat(
|
||||
"""
|
||||
sales_query = select(Sale).where(Sale.company_id == current_account.company_id)
|
||||
if date_start:
|
||||
sales_query = sales_query.where(Sale.sale_date >= date_start)
|
||||
sales_query = sales_query.where(Sale.sale_dttm >= date_start)
|
||||
if date_end:
|
||||
sales_query = sales_query.where(Sale.sale_date <= date_end)
|
||||
sales_query = sales_query.where(Sale.sale_dttm <= date_end)
|
||||
sales = db.exec(sales_query).all()
|
||||
ref_ids = list(set(sale.ref for sale in sales))
|
||||
refs = db.exec(select(Ref).where(Ref.id.in_(ref_ids))).all() if ref_ids else []
|
||||
@@ -745,3 +750,93 @@ def approve_agent_transactions(
|
||||
db.commit()
|
||||
|
||||
return {"msg": f"Переведено в статус NEW {approved_count} транзакций", "approved_count": approved_count}
|
||||
|
||||
# --- Новый функционал для интеграционных токенов ---
|
||||
|
||||
@app.get("/account/integration-tokens", tags=["bff", "account"], response_model=List[IntegrationTokenResponse])
|
||||
def get_integration_tokens(
|
||||
current_account: Account = Depends(get_current_account),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Возвращает список интеграционных токенов для компании текущего пользователя.
|
||||
"""
|
||||
tokens = db.exec(select(IntegrationToken).where(IntegrationToken.company_id == current_account.company_id)).all()
|
||||
return tokens # Позволяем FastAPI самостоятельно сериализовать объекты IntegrationToken в IntegrationTokenResponse
|
||||
|
||||
|
||||
@app.post("/account/integration-tokens", tags=["bff", "account"], response_model=IntegrationTokenResponse)
|
||||
def create_integration_token(
|
||||
req: IntegrationTokenCreateRequest,
|
||||
current_account: Account = Depends(get_current_account),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Создает новый интеграционный токен для компании текущего пользователя.
|
||||
Возвращает созданный токен (замаскированный).
|
||||
"""
|
||||
new_token_value = str(uuid.uuid4()) # Генерируем уникальный токен
|
||||
token_hash = hashlib.sha256(new_token_value.encode()).hexdigest() # Хешируем токен для хранения
|
||||
|
||||
# Генерируем замаскированный токен
|
||||
masked_token = new_token_value[:5] + "***********************" + new_token_value[-4:]
|
||||
|
||||
new_integration_token = IntegrationToken(
|
||||
description=req.description,
|
||||
token_hash=token_hash,
|
||||
masked_token=masked_token,
|
||||
company_id=current_account.company_id,
|
||||
)
|
||||
|
||||
db.add(new_integration_token)
|
||||
db.commit()
|
||||
db.refresh(new_integration_token)
|
||||
|
||||
# Создаем объект ответа, используя model_validate для извлечения данных из new_integration_token
|
||||
response_token = IntegrationTokenResponse.model_validate(new_integration_token)
|
||||
response_token.rawToken = new_token_value # Добавляем незамаскированный токен
|
||||
|
||||
return response_token
|
||||
|
||||
@app.post("/account/integration-tokens/update-description", tags=["bff", "account"], response_model=Dict[str, str])
|
||||
def update_integration_token_description(
|
||||
req: IntegrationTokenUpdateRequest,
|
||||
current_account: Account = Depends(get_current_account),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Обновляет описание интеграционного токена по его ID.
|
||||
"""
|
||||
token = db.exec(
|
||||
select(IntegrationToken).where(IntegrationToken.id == req.id).where(IntegrationToken.company_id == current_account.company_id)
|
||||
).first()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(status_code=404, detail="Токен не найден")
|
||||
|
||||
token.description = req.description
|
||||
token.update_dttm = datetime.utcnow() # Обновляем дату изменения, если поле существует
|
||||
db.add(token)
|
||||
db.commit()
|
||||
db.refresh(token)
|
||||
return {"msg": "Описание токена обновлено успешно"}
|
||||
|
||||
@app.delete("/account/integration-tokens/{token_id}", tags=["bff", "account"], response_model=Dict[str, str])
|
||||
def delete_integration_token(
|
||||
token_id: int,
|
||||
current_account: Account = Depends(get_current_account),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Удаляет интеграционный токен по его ID для компании текущего пользователя.
|
||||
"""
|
||||
token = db.exec(
|
||||
select(IntegrationToken).where(IntegrationToken.id == token_id).where(IntegrationToken.company_id == current_account.company_id)
|
||||
).first()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(status_code=404, detail="Токен не найден")
|
||||
|
||||
db.delete(token)
|
||||
db.commit()
|
||||
return {"msg": "Токен удален успешно"}
|
||||
|
||||
Reference in New Issue
Block a user