feat(backend): Phase 0 项目骨架完成 — 后端/前端/数据库/Docker

- 后端:FastAPI + SQLAlchemy + Alembic,7 张核心表迁移成功
- 前端:Next.js 16 + TailwindCSS 4 + 三端布局(投资人/创始人/Admin)
- 数据库:PostgreSQL 16,7 张核心实体表(tenants/users/companies/monthly_reports/health_scores/risk_events/audit_logs)
- Docker:docker-compose.yml + 前后端 Dockerfile
- 测试:健康检查 4 个测试全部 GREEN
- 文档:README/run.md/AGENTS.md/docs 体系完整
This commit is contained in:
selfrelease
2026-07-18 21:50:15 +08:00
parent f09aa33589
commit 51feae55ba
72 changed files with 8048 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
FROM python:3.12-slim
WORKDIR /app
COPY pyproject.toml ./
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple \
fastapi uvicorn[standard] sqlalchemy[asyncio] asyncpg alembic \
pydantic pydantic-settings python-jose[cryptography] passlib[bcrypt] \
python-multipart redis httpx structlog
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+149
View File
@@ -0,0 +1,149 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic
# 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
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# 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 <script_location>/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 "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# 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
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = driver://user:pass@localhost/dbname
[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 module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
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
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+77
View File
@@ -0,0 +1,77 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.core.config import settings
from app.core.database import Base
import app.models # noqa: F401 — 导入所有模型以便 Alembic 发现
config = context.config
# 使用项目配置的数据库 URL(同步驱动)
config.set_main_option("sqlalchemy.url", settings.database_url.replace("+asyncpg", "+psycopg2"))
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
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:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,161 @@
"""create core tables: tenants users companies reports health_scores risks audit_logs
Revision ID: 278c8cfa6042
Revises:
Create Date: 2026-07-18 21:49:38.409216
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '278c8cfa6042'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tenants',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False, comment='租户名称'),
sa.Column('type', sa.String(length=50), nullable=False, comment='租户类型:vc/cvc/gov/holdings'),
sa.Column('config_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='租户配置'),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('companies',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('tenant_id', sa.String(length=36), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False, comment='企业名称'),
sa.Column('industry', sa.String(length=100), nullable=True, comment='行业'),
sa.Column('stage', sa.String(length=50), nullable=True, comment='融资阶段:seed/a/b/c/ipo'),
sa.Column('logo_url', sa.String(length=500), nullable=True),
sa.Column('description', sa.Text(), nullable=True, comment='业务描述'),
sa.Column('founded_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('total_funding', sa.String(length=50), nullable=True, comment='累计融资额'),
sa.Column('website', sa.String(length=500), nullable=True),
sa.Column('extra_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='扩展字段'),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_companies_tenant_id'), 'companies', ['tenant_id'], unique=False)
op.create_table('users',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('tenant_id', sa.String(length=36), nullable=False),
sa.Column('email', sa.String(length=255), nullable=False),
sa.Column('password_hash', sa.String(length=255), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('role', sa.String(length=50), nullable=False, comment='角色:gp/partner/post_invest_lead/investor/founder/admin'),
sa.Column('phone', sa.String(length=20), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_tenant_id'), 'users', ['tenant_id'], unique=False)
op.create_table('audit_logs',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('tenant_id', sa.String(length=36), nullable=False),
sa.Column('user_id', sa.String(length=36), nullable=True),
sa.Column('action', sa.String(length=100), nullable=False, comment='操作类型:login/view/create/update/delete/export/ai_call'),
sa.Column('resource_type', sa.String(length=50), nullable=True, comment='资源类型'),
sa.Column('resource_id', sa.String(length=36), nullable=True, comment='资源 ID'),
sa.Column('detail_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='操作详情'),
sa.Column('ip', postgresql.INET(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_audit_logs_tenant_id'), 'audit_logs', ['tenant_id'], unique=False)
op.create_table('health_scores',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('company_id', sa.String(length=36), nullable=False),
sa.Column('total_score', sa.Float(), nullable=False, comment='总分(0-100'),
sa.Column('financial_score', sa.Float(), nullable=True, comment='财务健康度'),
sa.Column('operational_score', sa.Float(), nullable=True, comment='经营健康度'),
sa.Column('ai_commercial_score', sa.Float(), nullable=True, comment='AI+ 商业化健康度'),
sa.Column('ai_cost_score', sa.Float(), nullable=True, comment='AI+ 成本健康度'),
sa.Column('trend', sa.String(length=20), nullable=True, comment='趋势:up/stable/down'),
sa.Column('evidence_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='评分依据'),
sa.Column('recommendations_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='建议动作'),
sa.Column('calculated_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['company_id'], ['companies.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_health_scores_company_id'), 'health_scores', ['company_id'], unique=False)
op.create_table('monthly_reports',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('company_id', sa.String(length=36), nullable=False),
sa.Column('period_year', sa.Integer(), nullable=False, comment='报告年份'),
sa.Column('period_month', sa.Integer(), nullable=False, comment='报告月份(1-12'),
sa.Column('status', sa.String(length=50), nullable=False, comment='状态:draft/submitted/ai_parsed/reviewed'),
sa.Column('raw_content', sa.Text(), nullable=True, comment='原始内容'),
sa.Column('structured_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='结构化指标数据'),
sa.Column('ai_summary', sa.Text(), nullable=True, comment='AI 生成的摘要'),
sa.Column('ai_concerns', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='AI 关注点列表'),
sa.Column('submitted_by', sa.String(length=36), nullable=True),
sa.Column('submitted_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('reviewed_by', sa.String(length=36), nullable=True),
sa.Column('reviewed_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['company_id'], ['companies.id'], ),
sa.ForeignKeyConstraint(['reviewed_by'], ['users.id'], ),
sa.ForeignKeyConstraint(['submitted_by'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_monthly_reports_company_id'), 'monthly_reports', ['company_id'], unique=False)
op.create_table('risk_events',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('company_id', sa.String(length=36), nullable=False),
sa.Column('type', sa.String(length=50), nullable=False, comment='风险类型:financial/operational/org/ai_specific'),
sa.Column('severity', sa.String(length=20), nullable=False, comment='严重程度:low/medium/high/critical'),
sa.Column('status', sa.String(length=20), nullable=False, comment='状态:open/assigned/in_progress/resolved/closed'),
sa.Column('title', sa.String(length=200), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('evidence_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True, comment='证据链'),
sa.Column('suggested_action', sa.Text(), nullable=True, comment='建议动作'),
sa.Column('assigned_to', sa.String(length=36), nullable=True),
sa.Column('due_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('identified_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('closed_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['assigned_to'], ['users.id'], ),
sa.ForeignKeyConstraint(['company_id'], ['companies.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_risk_events_company_id'), 'risk_events', ['company_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_risk_events_company_id'), table_name='risk_events')
op.drop_table('risk_events')
op.drop_index(op.f('ix_monthly_reports_company_id'), table_name='monthly_reports')
op.drop_table('monthly_reports')
op.drop_index(op.f('ix_health_scores_company_id'), table_name='health_scores')
op.drop_table('health_scores')
op.drop_index(op.f('ix_audit_logs_tenant_id'), table_name='audit_logs')
op.drop_table('audit_logs')
op.drop_index(op.f('ix_users_tenant_id'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_companies_tenant_id'), table_name='companies')
op.drop_table('companies')
op.drop_table('tenants')
# ### end Alembic commands ###
+1
View File
@@ -0,0 +1 @@
"""AIPortPilot 后端应用包。"""
+1
View File
@@ -0,0 +1 @@
"""应用配置模块。"""
+36
View File
@@ -0,0 +1,36 @@
"""应用配置。
从环境变量读取配置,支持 .env 文件。
"""
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""应用配置,从环境变量读取。"""
# 应用
app_env: str = "development"
app_debug: bool = True
app_log_level: str = "info"
# 数据库
database_url: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/aiportpilot"
# Redis
redis_url: str = "redis://localhost:6379/0"
# JWT
jwt_secret_key: str = "change-me-in-production"
jwt_algorithm: str = "HS256"
jwt_access_token_ttl_minutes: int = 120
jwt_refresh_token_ttl_days: int = 7
# AI / Ollama
ollama_base_url: str = "http://localhost:11434"
ollama_model: str = "qwen2.5:7b"
model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
settings = Settings()
+43
View File
@@ -0,0 +1,43 @@
"""数据库连接管理。
提供 SQLAlchemy 异步 engine 和 session 工厂。
"""
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.core.config import settings
engine = create_async_engine(
settings.database_url,
echo=settings.app_debug,
pool_size=10,
max_overflow=20,
)
async_session_factory = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
)
class Base(DeclarativeBase):
"""SQLAlchemy ORM 基类。"""
pass
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""获取数据库 session 的依赖注入函数。"""
async with async_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
+46
View File
@@ -0,0 +1,46 @@
"""安全模块:JWT 生成与验证、密码哈希。"""
from datetime import datetime, timedelta, timezone
from typing import Any
from jose import jwt
from passlib.context import CryptContext
from app.core.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
"""密码哈希。"""
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""验证密码。"""
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(subject: str, extra_claims: dict[str, Any] | None = None) -> str:
"""生成 JWT access token。"""
expire = datetime.now(timezone.utc) + timedelta(
minutes=settings.jwt_access_token_ttl_minutes
)
payload: dict[str, Any] = {"sub": subject, "exp": expire, "type": "access"}
if extra_claims:
payload.update(extra_claims)
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
def create_refresh_token(subject: str) -> str:
"""生成 JWT refresh token。"""
expire = datetime.now(timezone.utc) + timedelta(
days=settings.jwt_refresh_token_ttl_days
)
payload = {"sub": subject, "exp": expire, "type": "refresh"}
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
def decode_token(token: str) -> dict[str, Any]:
"""解码 JWT token。"""
return jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
+65
View File
@@ -0,0 +1,65 @@
"""FastAPI 应用入口。
注册中间件、路由、异常处理。
"""
import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.schemas.common import error
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理。"""
# startup
yield
# shutdown
app = FastAPI(
title="AIPortPilot",
description="AI+ Portfolio Operating System — 投后管理与组合协同平台",
version="0.1.0",
lifespan=lifespan,
)
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def trace_id_middleware(request: Request, call_next):
"""为每个请求注入 trace_id。"""
trace_id = request.headers.get("X-Trace-Id", str(uuid.uuid4()))
request.state.trace_id = trace_id
response = await call_next(request)
response.headers["X-Trace-Id"] = trace_id
return response
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""全局异常处理。"""
trace_id = getattr(request.state, "trace_id", str(uuid.uuid4()))
return JSONResponse(
status_code=500,
content=error(code=-1, message="内部服务器错误"),
headers={"X-Trace-Id": trace_id},
)
@app.get("/health")
async def health_check():
"""健康检查端点。"""
return {"status": "ok", "service": "aiportpilot-backend", "version": "0.1.0"}
+22
View File
@@ -0,0 +1,22 @@
"""数据模型模块。
导入所有模型以便 Alembic 自动发现。
"""
from app.models.audit import AuditLog
from app.models.company import Company
from app.models.health_score import HealthScore
from app.models.report import MonthlyReport
from app.models.risk import RiskEvent
from app.models.tenant import Tenant
from app.models.user import User
__all__ = [
"AuditLog",
"Company",
"HealthScore",
"MonthlyReport",
"RiskEvent",
"Tenant",
"User",
]
+31
View File
@@ -0,0 +1,31 @@
"""审计日志模型。
全链路操作记录,保留 ≥ 6 月。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB, INET
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class AuditLog(Base):
"""审计日志。"""
__tablename__ = "audit_logs"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
tenant_id: Mapped[str] = mapped_column(String(36), ForeignKey("tenants.id"), nullable=False, index=True)
user_id: Mapped[str | None] = mapped_column(String(36), ForeignKey("users.id"), nullable=True)
action: Mapped[str] = mapped_column(String(100), nullable=False, comment="操作类型:login/view/create/update/delete/export/ai_call")
resource_type: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="资源类型")
resource_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment="资源 ID")
detail_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="操作详情")
ip: Mapped[str | None] = mapped_column(INET, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
+39
View File
@@ -0,0 +1,39 @@
"""企业模型。
被投企业档案,包含基本信息、业务描述、投资关系等。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class Company(Base):
"""被投企业。"""
__tablename__ = "companies"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
tenant_id: Mapped[str] = mapped_column(String(36), ForeignKey("tenants.id"), nullable=False, index=True)
name: Mapped[str] = mapped_column(String(200), nullable=False, comment="企业名称")
industry: Mapped[str | None] = mapped_column(String(100), nullable=True, comment="行业")
stage: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="融资阶段:seed/a/b/c/ipo")
logo_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True, comment="业务描述")
founded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
total_funding: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="累计融资额")
website: Mapped[str | None] = mapped_column(String(500), nullable=True)
extra_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="扩展字段")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
+33
View File
@@ -0,0 +1,33 @@
"""健康度评分模型。
多维度评分:财务、经营、AI+ 商业化、AI+ 成本。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, Float, ForeignKey, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class HealthScore(Base):
"""健康度评分。"""
__tablename__ = "health_scores"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
company_id: Mapped[str] = mapped_column(String(36), ForeignKey("companies.id"), nullable=False, index=True)
total_score: Mapped[float] = mapped_column(Float, nullable=False, comment="总分(0-100")
financial_score: Mapped[float | None] = mapped_column(Float, nullable=True, comment="财务健康度")
operational_score: Mapped[float | None] = mapped_column(Float, nullable=True, comment="经营健康度")
ai_commercial_score: Mapped[float | None] = mapped_column(Float, nullable=True, comment="AI+ 商业化健康度")
ai_cost_score: Mapped[float | None] = mapped_column(Float, nullable=True, comment="AI+ 成本健康度")
trend: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="趋势:up/stable/down")
evidence_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="评分依据")
recommendations_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="建议动作")
calculated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
+44
View File
@@ -0,0 +1,44 @@
"""月报模型。
被投企业按月提交的经营报告,支持 AI 解析。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class MonthlyReport(Base):
"""月报。"""
__tablename__ = "monthly_reports"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
company_id: Mapped[str] = mapped_column(String(36), ForeignKey("companies.id"), nullable=False, index=True)
period_year: Mapped[int] = mapped_column(Integer, nullable=False, comment="报告年份")
period_month: Mapped[int] = mapped_column(Integer, nullable=False, comment="报告月份(1-12")
status: Mapped[str] = mapped_column(
String(50), nullable=False, default="draft",
comment="状态:draft/submitted/ai_parsed/reviewed",
)
raw_content: Mapped[str | None] = mapped_column(Text, nullable=True, comment="原始内容")
structured_data: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="结构化指标数据")
ai_summary: Mapped[str | None] = mapped_column(Text, nullable=True, comment="AI 生成的摘要")
ai_concerns: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="AI 关注点列表")
submitted_by: Mapped[str | None] = mapped_column(String(36), ForeignKey("users.id"), nullable=True)
submitted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
reviewed_by: Mapped[str | None] = mapped_column(String(36), ForeignKey("users.id"), nullable=True)
reviewed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
+43
View File
@@ -0,0 +1,43 @@
"""风险事件模型。
指标越界自动预警 + 人工处理闭环。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class RiskEvent(Base):
"""风险事件。"""
__tablename__ = "risk_events"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
company_id: Mapped[str] = mapped_column(String(36), ForeignKey("companies.id"), nullable=False, index=True)
type: Mapped[str] = mapped_column(String(50), nullable=False, comment="风险类型:financial/operational/org/ai_specific")
severity: Mapped[str] = mapped_column(String(20), nullable=False, default="medium", comment="严重程度:low/medium/high/critical")
status: Mapped[str] = mapped_column(String(20), nullable=False, default="open", comment="状态:open/assigned/in_progress/resolved/closed")
title: Mapped[str] = mapped_column(String(200), nullable=False)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
evidence_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="证据链")
suggested_action: Mapped[str | None] = mapped_column(Text, nullable=True, comment="建议动作")
assigned_to: Mapped[str | None] = mapped_column(String(36), ForeignKey("users.id"), nullable=True)
due_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
identified_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
+32
View File
@@ -0,0 +1,32 @@
"""租户模型。
投资机构和被投企业都属于某个租户。多租户隔离的基础。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import DateTime, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class Tenant(Base):
"""租户(投资机构)。"""
__tablename__ = "tenants"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name: Mapped[str] = mapped_column(String(200), nullable=False, comment="租户名称")
type: Mapped[str] = mapped_column(String(50), nullable=False, default="vc", comment="租户类型:vc/cvc/gov/holdings")
config_json: Mapped[dict | None] = mapped_column(JSONB, nullable=True, comment="租户配置")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
+38
View File
@@ -0,0 +1,38 @@
"""用户模型。
支持多种角色:GP、投资经理、投后负责人、创始人、管理员等。
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class User(Base):
"""用户。"""
__tablename__ = "users"
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
tenant_id: Mapped[str] = mapped_column(String(36), ForeignKey("tenants.id"), nullable=False, index=True)
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
name: Mapped[str] = mapped_column(String(100), nullable=False)
role: Mapped[str] = mapped_column(
String(50), nullable=False, default="investor",
comment="角色:gp/partner/post_invest_lead/investor/founder/admin",
)
phone: Mapped[str | None] = mapped_column(String(20), nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
+1
View File
@@ -0,0 +1 @@
"""API 路由模块。"""
+1
View File
@@ -0,0 +1 @@
"""Pydantic schema 模块。"""
+35
View File
@@ -0,0 +1,35 @@
"""统一响应模型。
所有 API 返回统一壳:{code, message, data, trace_id, timestamp}
"""
import uuid
from datetime import datetime, timezone
from typing import Any, Generic, TypeVar
from pydantic import BaseModel, Field
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
"""统一 API 响应壳。"""
code: int = Field(default=0, description="业务状态码,0 表示成功")
message: str = Field(default="success", description="提示信息")
data: T | None = Field(default=None, description="业务数据")
trace_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="链路追踪 ID")
timestamp: str = Field(
default_factory=lambda: datetime.now(timezone.utc).isoformat(),
description="响应时间(UTC ISO 8601",
)
def success(data: Any = None, message: str = "success") -> dict[str, Any]:
"""构造成功响应。"""
return ApiResponse(code=0, message=message, data=data).model_dump()
def error(code: int = -1, message: str = "error", data: Any = None) -> dict[str, Any]:
"""构造错误响应。"""
return ApiResponse(code=code, message=message, data=data).model_dump()
+1
View File
@@ -0,0 +1 @@
"""业务服务模块。"""
+50
View File
@@ -0,0 +1,50 @@
[project]
name = "aiportpilot-backend"
version = "0.1.0"
description = "AI+ Portfolio Operating System - 后端"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115.0",
"uvicorn[standard]>=0.34.0",
"sqlalchemy[asyncio]>=2.0.36",
"asyncpg>=0.30.0",
"alembic>=1.14.0",
"pydantic>=2.10.0",
"pydantic-settings>=2.6.0",
"python-jose[cryptography]>=3.3.0",
"passlib[bcrypt]>=1.7.4",
"python-multipart>=0.0.17",
"redis[asyncio]>=5.2.0",
"httpx>=0.28.0",
"pgvector>=0.3.6",
"langchain>=0.3.0",
"langchain-ollama>=0.2.0",
"structlog>=24.4.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.3.0",
"pytest-asyncio>=0.24.0",
"pytest-cov>=6.0.0",
"httpx>=0.28.0",
"testcontainers[postgres]>=4.0.0",
"ruff>=0.8.0",
"mypy>=1.13.0",
]
[tool.ruff]
target-version = "py312"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "N", "W", "UP"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
addopts = "-v --tb=short"
[tool.mypy]
python_version = "3.12"
strict = true
+1
View File
@@ -0,0 +1 @@
"""测试包。"""
+41
View File
@@ -0,0 +1,41 @@
"""健康检查端点测试。"""
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture
def client():
"""创建测试客户端。"""
return TestClient(app)
class TestHealthCheck:
"""健康检查测试。"""
def test_health_returns_ok(self, client: TestClient):
"""RED: 健康检查应返回 200 和 status=ok。"""
response = client.get("/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "ok"
assert data["service"] == "aiportpilot-backend"
def test_health_returns_version(self, client: TestClient):
"""RED: 健康检查应返回版本号。"""
response = client.get("/health")
data = response.json()
assert "version" in data
def test_trace_id_in_response_header(self, client: TestClient):
"""RED: 响应头应包含 X-Trace-Id。"""
response = client.get("/health")
assert "X-Trace-Id" in response.headers
def test_trace_id_echoed_from_request(self, client: TestClient):
"""RED: 请求头传入的 trace_id 应在响应头中原样返回。"""
custom_trace_id = "test-trace-12345"
response = client.get("/health", headers={"X-Trace-Id": custom_trace_id})
assert response.headers["X-Trace-Id"] == custom_trace_id