init
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# ============ 服务端环境变量示例 ============
|
||||
# 复制本文件为 .env 并填写真实值:.env
|
||||
|
||||
# MySQL 数据库配置
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=root
|
||||
DB_PASSWORD=
|
||||
DB_NAME=jianli_boss
|
||||
|
||||
# JWT 密钥(生产环境务必改成随机长字符串)
|
||||
SECRET_KEY=please-change-this-to-a-long-random-string
|
||||
|
||||
# Token 有效期(天)
|
||||
ACCESS_TOKEN_EXPIRE_DAYS=30
|
||||
|
||||
# 调试模式
|
||||
DEBUG=false
|
||||
@@ -0,0 +1 @@
|
||||
"""服务端包"""
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
JWT 认证工具
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .config import settings
|
||||
from .database import get_db
|
||||
from .models import User
|
||||
|
||||
# 使用 HTTP Bearer Token 认证
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def create_access_token(user_id: int, client_code: str) -> str:
|
||||
"""生成 JWT token"""
|
||||
expire = datetime.utcnow() + timedelta(days=settings.ACCESS_TOKEN_EXPIRE_DAYS)
|
||||
payload = {
|
||||
"sub": str(user_id),
|
||||
"client_code": client_code,
|
||||
"exp": expire,
|
||||
}
|
||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[dict]:
|
||||
"""解码 token,失败返回 None"""
|
||||
try:
|
||||
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""
|
||||
FastAPI 依赖:从请求头解析 token 并返回当前用户。
|
||||
未认证时抛出 401。
|
||||
"""
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="缺少认证 token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
payload = decode_token(credentials.credentials)
|
||||
if payload is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="token 无效或已过期",
|
||||
)
|
||||
user_id = int(payload.get("sub", 0))
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None or not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在或已禁用")
|
||||
return user
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
服务端配置文件
|
||||
使用环境变量或 .env 文件加载敏感配置
|
||||
"""
|
||||
import os
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# -------------------------------------------------------
|
||||
# 应用
|
||||
# -------------------------------------------------------
|
||||
APP_NAME: str = "Boss直聘投递服务端"
|
||||
APP_VERSION: str = "1.0.0"
|
||||
DEBUG: bool = False
|
||||
|
||||
# -------------------------------------------------------
|
||||
# 数据库(MySQL)
|
||||
# -------------------------------------------------------
|
||||
DB_HOST: str = "127.0.0.1"
|
||||
DB_PORT: int = 3306
|
||||
DB_USER: str = "root"
|
||||
DB_PASSWORD: str = ""
|
||||
DB_NAME: str = "jianli_boss"
|
||||
|
||||
@property
|
||||
def DATABASE_URL(self) -> str:
|
||||
return (
|
||||
f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}"
|
||||
f"@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
|
||||
f"?charset=utf8mb4"
|
||||
)
|
||||
|
||||
# -------------------------------------------------------
|
||||
# JWT 认证
|
||||
# -------------------------------------------------------
|
||||
SECRET_KEY: str = "change-this-to-a-random-secret-key-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
# Token 有效期(天)
|
||||
ACCESS_TOKEN_EXPIRE_DAYS: int = 30
|
||||
|
||||
# -------------------------------------------------------
|
||||
# CORS(允许客户端 Web 面板访问)
|
||||
# -------------------------------------------------------
|
||||
CORS_ORIGINS: list[str] = ["*"]
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
env_file_encoding = "utf-8"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
MySQL 数据库连接与 SQLAlchemy 引擎初始化
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
from .config import settings
|
||||
|
||||
# 连接池配置:避免频繁创建连接
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=3600,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
echo=settings.DEBUG,
|
||||
connect_args={"charset": "utf8mb4"},
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# 所有 ORM 模型的基类
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
"""FastAPI 依赖注入:获取数据库会话"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
"""创建所有表(生产环境建议改用 Alembic 迁移)"""
|
||||
from . import models # noqa: F401 确保模型被导入
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
服务端主入口
|
||||
运行方式:uvicorn server.main:app --host 0.0.0.0 --port 8000 --reload
|
||||
"""
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .config import settings
|
||||
from .database import init_db
|
||||
from .routers import register, resumes, sessions, jobs
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# 启动时建表
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
version=settings.APP_VERSION,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# CORS:允许客户端 Web 面板跨域访问
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.CORS_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
app.include_router(register.router)
|
||||
app.include_router(resumes.router)
|
||||
app.include_router(sessions.router)
|
||||
app.include_router(jobs.router)
|
||||
|
||||
|
||||
@app.get("/", tags=["健康检查"])
|
||||
def health_check():
|
||||
return {
|
||||
"name": settings.APP_NAME,
|
||||
"version": settings.APP_VERSION,
|
||||
"status": "ok",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("server.main:app", host="0.0.0.0", port=8000, reload=True)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
SQLAlchemy ORM 模型定义
|
||||
所有业务表均带 user_id 外键,实现用户数据隔离
|
||||
"""
|
||||
from datetime import datetime
|
||||
from sqlalchemy import (
|
||||
Column, Integer, BigInteger, String, Text, Boolean,
|
||||
DateTime, Float, ForeignKey, Index, UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .database import Base
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
客户端用户
|
||||
以机器硬件指纹(client_code)作为唯一标识
|
||||
"""
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
# 机器硬件指纹哈希(唯一)
|
||||
client_code = Column(String(128), unique=True, nullable=False, index=True)
|
||||
# 客户端显示昵称(可选)
|
||||
nickname = Column(String(64), nullable=True)
|
||||
# JWT token 存储(服务端无状态校验,这里仅做记录)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
# Boss直聘 账号标识(登录成功后回填,用于区分同一 Boss 账号)
|
||||
boss_account = Column(String(128), nullable=True)
|
||||
# 登录状态:not_login / logging_in / logged_in
|
||||
login_status = Column(String(20), default="not_login", nullable=False)
|
||||
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||
last_seen_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||
|
||||
# 关联
|
||||
resumes = relationship("Resume", back_populates="user", cascade="all, delete-orphan")
|
||||
applications = relationship("JobApplication", back_populates="user", cascade="all, delete-orphan")
|
||||
sessions = relationship("ApplySession", back_populates="user", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Resume(Base):
|
||||
"""
|
||||
简历
|
||||
一个用户可有多份简历,其中一份标记为主简历
|
||||
"""
|
||||
__tablename__ = "resumes"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
# Boss直聘 简历 ID
|
||||
boss_resume_id = Column(String(64), nullable=True)
|
||||
# 简历标题
|
||||
title = Column(String(128), nullable=False)
|
||||
# 求职意向岗位
|
||||
position = Column(String(128), nullable=True)
|
||||
# 简历全文(结构化或纯文本)
|
||||
content = Column(Text, nullable=True)
|
||||
# 是否为主简历
|
||||
is_primary = Column(Boolean, default=False, nullable=False)
|
||||
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||
|
||||
user = relationship("User", back_populates="resumes")
|
||||
|
||||
|
||||
class ApplySession(Base):
|
||||
"""
|
||||
投递会话
|
||||
记录一次"开始投递 → 结束投递"的完整过程
|
||||
"""
|
||||
__tablename__ = "apply_sessions"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
# 会话状态:running / stopped / finished
|
||||
status = Column(String(20), default="running", nullable=False)
|
||||
# 搜索关键词(逗号分隔)
|
||||
keywords = Column(String(512), nullable=True)
|
||||
# 城市代码
|
||||
city_code = Column(String(20), nullable=True)
|
||||
# 薪资范围
|
||||
salary_min = Column(Integer, nullable=True)
|
||||
salary_max = Column(Integer, nullable=True)
|
||||
# 本次会话投递数量统计
|
||||
applied_count = Column(Integer, default=0)
|
||||
skipped_count = Column(Integer, default=0)
|
||||
started_at = Column(DateTime, default=utcnow, nullable=False)
|
||||
ended_at = Column(DateTime, nullable=True)
|
||||
|
||||
user = relationship("User", back_populates="sessions")
|
||||
applications = relationship("JobApplication", back_populates="session", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class JobApplication(Base):
|
||||
"""
|
||||
投递记录
|
||||
"""
|
||||
__tablename__ = "job_applications"
|
||||
__table_args__ = (
|
||||
# 同一用户不重复投递同一职位
|
||||
UniqueConstraint("user_id", "job_id", name="uq_user_job"),
|
||||
Index("idx_user_session", "user_id", "session_id"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
session_id = Column(Integer, ForeignKey("apply_sessions.id", ondelete="SET NULL"), nullable=True)
|
||||
# Boss直聘 职位 ID
|
||||
job_id = Column(String(64), nullable=False, index=True)
|
||||
job_title = Column(String(128), nullable=True)
|
||||
company = Column(String(128), nullable=True)
|
||||
salary = Column(String(32), nullable=True)
|
||||
location = Column(String(64), nullable=True)
|
||||
# 投递方式:chat=立即沟通 / deliver=投递简历 / skipped=跳过
|
||||
apply_type = Column(String(20), nullable=False)
|
||||
# AI 匹配评分(-1 表示未评分)
|
||||
ai_score = Column(Integer, default=-1)
|
||||
ai_reason = Column(String(255), nullable=True)
|
||||
# 跳过原因
|
||||
skip_reason = Column(String(255), nullable=True)
|
||||
applied_at = Column(DateTime, default=utcnow, nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="applications")
|
||||
session = relationship("ApplySession", back_populates="applications")
|
||||
@@ -0,0 +1,9 @@
|
||||
# 服务端依赖
|
||||
fastapi>=0.111.0
|
||||
uvicorn[standard]>=0.30.0
|
||||
sqlalchemy>=2.0.30
|
||||
pymysql>=1.1.0
|
||||
cryptography>=42.0.0
|
||||
pydantic>=2.7.0
|
||||
pydantic-settings>=2.3.0
|
||||
python-jose[cryptography]>=3.3.0
|
||||
@@ -0,0 +1 @@
|
||||
"""路由包"""
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
投递记录路由:上报投递结果、查询历史、统计
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func
|
||||
|
||||
from ..auth import get_current_user
|
||||
from ..database import get_db
|
||||
from ..models import User, JobApplication
|
||||
from ..schemas import ApplicationIn, ApplicationOut, Message, StatsOut
|
||||
|
||||
router = APIRouter(prefix="/api/jobs", tags=["投递记录"])
|
||||
|
||||
|
||||
@router.post("/report", response_model=ApplicationOut)
|
||||
def report_application(
|
||||
req: ApplicationIn,
|
||||
session_id: Optional[int] = Query(None, description="所属会话 ID"),
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
客户端上报一条投递/跳过记录。
|
||||
同一用户 + 同一职位 ID 去重,已存在则更新。
|
||||
"""
|
||||
existing = db.query(JobApplication).filter(
|
||||
JobApplication.user_id == current_user.id,
|
||||
JobApplication.job_id == req.job_id,
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
existing.apply_type = req.apply_type
|
||||
existing.ai_score = req.ai_score
|
||||
existing.ai_reason = req.ai_reason
|
||||
existing.skip_reason = req.skip_reason
|
||||
if session_id:
|
||||
existing.session_id = session_id
|
||||
record = existing
|
||||
else:
|
||||
record = JobApplication(
|
||||
user_id=current_user.id,
|
||||
session_id=session_id,
|
||||
job_id=req.job_id,
|
||||
job_title=req.job_title,
|
||||
company=req.company,
|
||||
salary=req.salary,
|
||||
location=req.location,
|
||||
apply_type=req.apply_type,
|
||||
ai_score=req.ai_score,
|
||||
ai_reason=req.ai_reason,
|
||||
skip_reason=req.skip_reason,
|
||||
)
|
||||
db.add(record)
|
||||
|
||||
db.commit()
|
||||
db.refresh(record)
|
||||
return record
|
||||
|
||||
|
||||
@router.get("/check/{job_id}", response_model=dict)
|
||||
def check_applied(
|
||||
job_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""检查某职位是否已投递过(用于客户端去重)"""
|
||||
record = db.query(JobApplication).filter(
|
||||
JobApplication.user_id == current_user.id,
|
||||
JobApplication.job_id == job_id,
|
||||
JobApplication.apply_type.in_(["chat", "deliver"]),
|
||||
).first()
|
||||
return {"job_id": job_id, "applied": record is not None}
|
||||
|
||||
|
||||
@router.get("/history", response_model=list[ApplicationOut])
|
||||
def list_applications(
|
||||
apply_type: Optional[str] = Query(None, description="过滤投递类型"),
|
||||
limit: int = Query(50, le=500),
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取投递历史(按时间倒序)"""
|
||||
query = db.query(JobApplication).filter(JobApplication.user_id == current_user.id)
|
||||
if apply_type:
|
||||
query = query.filter(JobApplication.apply_type == apply_type)
|
||||
return query.order_by(JobApplication.applied_at.desc()).limit(limit).all()
|
||||
|
||||
|
||||
@router.get("/stats", response_model=StatsOut)
|
||||
def get_stats(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取投递统计"""
|
||||
base = db.query(JobApplication).filter(JobApplication.user_id == current_user.id)
|
||||
|
||||
def count(**filters):
|
||||
q = base
|
||||
for k, v in filters.items():
|
||||
q = q.filter(getattr(JobApplication, k) == v)
|
||||
return q.count()
|
||||
|
||||
today_str = datetime.utcnow().strftime("%Y-%m-%d")
|
||||
total_applied = base.filter(JobApplication.apply_type.in_(["chat", "deliver"])).count()
|
||||
today_applied = base.filter(
|
||||
JobApplication.apply_type.in_(["chat", "deliver"]),
|
||||
func.date(JobApplication.applied_at) == today_str,
|
||||
).count()
|
||||
|
||||
return StatsOut(
|
||||
total_applied=total_applied,
|
||||
total_chat=count(apply_type="chat"),
|
||||
total_deliver=count(apply_type="deliver"),
|
||||
total_skipped=count(apply_type="skipped"),
|
||||
today_applied=today_applied,
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
客户端注册 / 登录状态 / 用户信息路由
|
||||
"""
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import create_access_token, get_current_user
|
||||
from ..database import get_db
|
||||
from ..models import User
|
||||
from ..schemas import (
|
||||
RegisterRequest, RegisterResponse, UserInfo, LoginStatusUpdate, Message,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["认证与用户"])
|
||||
|
||||
|
||||
@router.post("/register", response_model=RegisterResponse)
|
||||
def register(req: RegisterRequest, db: Session = Depends(get_db)):
|
||||
"""
|
||||
客户端注册/登录。
|
||||
以机器硬件指纹 client_code 作为唯一标识:
|
||||
- 已存在 → 直接返回 token(视为登录)
|
||||
- 不存在 → 创建新用户
|
||||
"""
|
||||
user = db.query(User).filter(User.client_code == req.client_code).first()
|
||||
is_new = user is None
|
||||
|
||||
if is_new:
|
||||
user = User(client_code=req.client_code, nickname=req.nickname)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# 更新最后活跃时间
|
||||
user.last_seen_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
token = create_access_token(user.id, user.client_code)
|
||||
return RegisterResponse(
|
||||
user_id=user.id,
|
||||
token=token,
|
||||
client_code=user.client_code,
|
||||
is_new=is_new,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserInfo)
|
||||
def get_me(current_user: User = Depends(get_current_user)):
|
||||
"""获取当前用户信息"""
|
||||
return UserInfo(
|
||||
id=current_user.id,
|
||||
client_code=current_user.client_code,
|
||||
nickname=current_user.nickname,
|
||||
boss_account=current_user.boss_account,
|
||||
login_status=current_user.login_status,
|
||||
created_at=current_user.created_at,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/login-status", response_model=Message)
|
||||
def update_login_status(
|
||||
req: LoginStatusUpdate,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""更新 Boss直聘 登录状态"""
|
||||
valid_status = {"not_login", "logging_in", "logged_in"}
|
||||
if req.login_status not in valid_status:
|
||||
raise HTTPException(status_code=400, detail=f"登录状态必须是 {valid_status} 之一")
|
||||
current_user.login_status = req.login_status
|
||||
if req.boss_account:
|
||||
current_user.boss_account = req.boss_account
|
||||
db.commit()
|
||||
return Message(msg=f"登录状态已更新为 {req.login_status}")
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
简历管理路由
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import get_current_user
|
||||
from ..database import get_db
|
||||
from ..models import User, Resume
|
||||
from ..schemas import ResumeIn, ResumeOut, ResumeBatchIn, Message
|
||||
|
||||
router = APIRouter(prefix="/api/resumes", tags=["简历管理"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[ResumeOut])
|
||||
def list_resumes(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取当前用户的所有简历"""
|
||||
resumes = db.query(Resume).filter(Resume.user_id == current_user.id).all()
|
||||
return resumes
|
||||
|
||||
|
||||
@router.get("/primary", response_model=ResumeOut)
|
||||
def get_primary_resume(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取当前用户的主简历"""
|
||||
resume = db.query(Resume).filter(
|
||||
Resume.user_id == current_user.id,
|
||||
Resume.is_primary == True,
|
||||
).first()
|
||||
if resume is None:
|
||||
raise HTTPException(status_code=404, detail="尚未设置主简历")
|
||||
return resume
|
||||
|
||||
|
||||
@router.post("/batch", response_model=list[ResumeOut])
|
||||
def upload_resumes_batch(
|
||||
req: ResumeBatchIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
批量上传抓取到的简历。
|
||||
以 boss_resume_id 去重:存在则更新,不存在则新增。
|
||||
第一份简历自动设为主简历(若当前没有主简历)。
|
||||
"""
|
||||
results = []
|
||||
has_primary = db.query(Resume).filter(
|
||||
Resume.user_id == current_user.id, Resume.is_primary == True
|
||||
).first() is not None
|
||||
|
||||
for i, item in enumerate(req.resumes):
|
||||
existing = None
|
||||
if item.boss_resume_id:
|
||||
existing = db.query(Resume).filter(
|
||||
Resume.user_id == current_user.id,
|
||||
Resume.boss_resume_id == item.boss_resume_id,
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
existing.title = item.title
|
||||
existing.position = item.position
|
||||
existing.content = item.content
|
||||
results.append(existing)
|
||||
else:
|
||||
resume = Resume(
|
||||
user_id=current_user.id,
|
||||
boss_resume_id=item.boss_resume_id,
|
||||
title=item.title,
|
||||
position=item.position,
|
||||
content=item.content,
|
||||
)
|
||||
# 若尚无主简历,将第一份设为主简历
|
||||
if not has_primary and i == 0:
|
||||
resume.is_primary = True
|
||||
has_primary = True
|
||||
db.add(resume)
|
||||
results.append(resume)
|
||||
|
||||
db.commit()
|
||||
for r in results:
|
||||
db.refresh(r)
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/{resume_id}/set-primary", response_model=Message)
|
||||
def set_primary(
|
||||
resume_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""将指定简历设为主简历(同时取消其他主简历标记)"""
|
||||
target = db.query(Resume).filter(
|
||||
Resume.id == resume_id,
|
||||
Resume.user_id == current_user.id,
|
||||
).first()
|
||||
if target is None:
|
||||
raise HTTPException(status_code=404, detail="简历不存在")
|
||||
|
||||
# 取消当前主简历标记
|
||||
db.query(Resume).filter(
|
||||
Resume.user_id == current_user.id, Resume.is_primary == True
|
||||
).update({"is_primary": False})
|
||||
target.is_primary = True
|
||||
db.commit()
|
||||
return Message(msg=f"已将《{target.title}》设为主简历")
|
||||
|
||||
|
||||
@router.delete("/{resume_id}", response_model=Message)
|
||||
def delete_resume(
|
||||
resume_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""删除指定简历"""
|
||||
resume = db.query(Resume).filter(
|
||||
Resume.id == resume_id,
|
||||
Resume.user_id == current_user.id,
|
||||
).first()
|
||||
if resume is None:
|
||||
raise HTTPException(status_code=404, detail="简历不存在")
|
||||
db.delete(resume)
|
||||
db.commit()
|
||||
return Message(msg="简历已删除")
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
投递会话路由:开始 / 结束投递、上报统计
|
||||
"""
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import get_current_user
|
||||
from ..database import get_db
|
||||
from ..models import User, ApplySession
|
||||
from ..schemas import SessionStartIn, SessionOut, SessionStatsIn, Message
|
||||
|
||||
router = APIRouter(prefix="/api/sessions", tags=["投递会话"])
|
||||
|
||||
|
||||
@router.post("/start", response_model=SessionOut)
|
||||
def start_session(
|
||||
req: SessionStartIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""开始一次投递会话"""
|
||||
# 若已有进行中的会话,先结束它
|
||||
running = db.query(ApplySession).filter(
|
||||
ApplySession.user_id == current_user.id,
|
||||
ApplySession.status == "running",
|
||||
).first()
|
||||
if running:
|
||||
running.status = "stopped"
|
||||
running.ended_at = datetime.utcnow()
|
||||
|
||||
session = ApplySession(
|
||||
user_id=current_user.id,
|
||||
status="running",
|
||||
keywords=req.keywords,
|
||||
city_code=req.city_code,
|
||||
salary_min=req.salary_min,
|
||||
salary_max=req.salary_max,
|
||||
)
|
||||
db.add(session)
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
return session
|
||||
|
||||
|
||||
@router.get("/current", response_model=SessionOut)
|
||||
def get_current_session(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取当前进行中的会话"""
|
||||
session = db.query(ApplySession).filter(
|
||||
ApplySession.user_id == current_user.id,
|
||||
ApplySession.status == "running",
|
||||
).order_by(ApplySession.started_at.desc()).first()
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="当前没有进行中的会话")
|
||||
return session
|
||||
|
||||
|
||||
@router.post("/{session_id}/stop", response_model=SessionOut)
|
||||
def stop_session(
|
||||
session_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""结束指定会话"""
|
||||
session = db.query(ApplySession).filter(
|
||||
ApplySession.id == session_id,
|
||||
ApplySession.user_id == current_user.id,
|
||||
).first()
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="会话不存在")
|
||||
session.status = "stopped"
|
||||
session.ended_at = datetime.utcnow()
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
return session
|
||||
|
||||
|
||||
@router.post("/{session_id}/stats", response_model=SessionOut)
|
||||
def update_session_stats(
|
||||
session_id: int,
|
||||
req: SessionStatsIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""增量上报投递/跳过数量"""
|
||||
session = db.query(ApplySession).filter(
|
||||
ApplySession.id == session_id,
|
||||
ApplySession.user_id == current_user.id,
|
||||
).first()
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="会话不存在")
|
||||
session.applied_count += req.applied_delta
|
||||
session.skipped_count += req.skipped_delta
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
return session
|
||||
|
||||
|
||||
@router.get("/history", response_model=list[SessionOut])
|
||||
def list_sessions(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取历史会话列表"""
|
||||
return db.query(ApplySession).filter(
|
||||
ApplySession.user_id == current_user.id
|
||||
).order_by(ApplySession.started_at.desc()).limit(50).all()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
Pydantic 请求/响应数据模式
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 认证相关
|
||||
# =======================================================
|
||||
class RegisterRequest(BaseModel):
|
||||
client_code: str = Field(..., min_length=8, max_length=128, description="机器硬件指纹哈希")
|
||||
nickname: Optional[str] = Field(None, max_length=64)
|
||||
|
||||
|
||||
class RegisterResponse(BaseModel):
|
||||
user_id: int
|
||||
token: str
|
||||
client_code: str
|
||||
is_new: bool # 是否为新注册用户
|
||||
|
||||
|
||||
class TokenPayload(BaseModel):
|
||||
sub: int # user_id
|
||||
client_code: str
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 用户状态
|
||||
# =======================================================
|
||||
class UserInfo(BaseModel):
|
||||
id: int
|
||||
client_code: str
|
||||
nickname: Optional[str]
|
||||
boss_account: Optional[str]
|
||||
login_status: str
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class LoginStatusUpdate(BaseModel):
|
||||
login_status: str = Field(..., description="not_login / logging_in / logged_in")
|
||||
boss_account: Optional[str] = None
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 简历相关
|
||||
# =======================================================
|
||||
class ResumeIn(BaseModel):
|
||||
boss_resume_id: Optional[str] = None
|
||||
title: str = Field(..., min_length=1, max_length=128)
|
||||
position: Optional[str] = None
|
||||
content: Optional[str] = None
|
||||
|
||||
|
||||
class ResumeOut(BaseModel):
|
||||
id: int
|
||||
boss_resume_id: Optional[str]
|
||||
title: str
|
||||
position: Optional[str]
|
||||
content: Optional[str]
|
||||
is_primary: bool
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ResumeBatchIn(BaseModel):
|
||||
"""批量上传抓取到的所有简历"""
|
||||
resumes: list[ResumeIn]
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 投递会话
|
||||
# =======================================================
|
||||
class SessionStartIn(BaseModel):
|
||||
keywords: str
|
||||
city_code: str
|
||||
salary_min: Optional[int] = None
|
||||
salary_max: Optional[int] = None
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
id: int
|
||||
status: str
|
||||
keywords: Optional[str]
|
||||
city_code: Optional[str]
|
||||
salary_min: Optional[int]
|
||||
salary_max: Optional[int]
|
||||
applied_count: int
|
||||
skipped_count: int
|
||||
started_at: datetime
|
||||
ended_at: Optional[datetime]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class SessionStatsIn(BaseModel):
|
||||
applied_delta: int = 0
|
||||
skipped_delta: int = 0
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 投递记录
|
||||
# =======================================================
|
||||
class ApplicationIn(BaseModel):
|
||||
job_id: str
|
||||
job_title: Optional[str] = None
|
||||
company: Optional[str] = None
|
||||
salary: Optional[str] = None
|
||||
location: Optional[str] = None
|
||||
apply_type: str # chat / deliver / skipped
|
||||
ai_score: int = -1
|
||||
ai_reason: Optional[str] = None
|
||||
skip_reason: Optional[str] = None
|
||||
|
||||
|
||||
class ApplicationOut(BaseModel):
|
||||
id: int
|
||||
job_id: str
|
||||
job_title: Optional[str]
|
||||
company: Optional[str]
|
||||
salary: Optional[str]
|
||||
location: Optional[str]
|
||||
apply_type: str
|
||||
ai_score: int
|
||||
ai_reason: Optional[str]
|
||||
skip_reason: Optional[str]
|
||||
applied_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
# =======================================================
|
||||
# 通用
|
||||
# =======================================================
|
||||
class Message(BaseModel):
|
||||
msg: str
|
||||
|
||||
|
||||
class StatsOut(BaseModel):
|
||||
total_applied: int
|
||||
total_chat: int
|
||||
total_deliver: int
|
||||
total_skipped: int
|
||||
today_applied: int
|
||||
Reference in New Issue
Block a user