mirror of
https://github.com/Cccc-owo/CheckInApp.git
synced 2026-06-17 14:06:28 +00:00
refactor(structure): reorganize app layout
BREAKING CHANGE: root backend/frontend directories and old run/manage entrypoints were removed. Use apps/backend, apps/frontend, and python main.py commands instead.
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
from backend.models.database import Base, get_db, init_db
|
||||
from backend.models.user import User
|
||||
from backend.models.check_in_task import CheckInTask
|
||||
from backend.models.check_in_record import CheckInRecord
|
||||
from backend.models.task_template import TaskTemplate
|
||||
|
||||
__all__ = ["Base", "get_db", "init_db", "User", "CheckInTask", "CheckInRecord", "TaskTemplate"]
|
||||
@@ -0,0 +1,31 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Index
|
||||
from sqlalchemy.orm import relationship
|
||||
from datetime import datetime, timezone
|
||||
from backend.models.database import Base
|
||||
|
||||
|
||||
class CheckInRecord(Base):
|
||||
"""打卡记录模型"""
|
||||
|
||||
__tablename__ = "check_in_records"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
||||
task_id = Column(Integer, ForeignKey("check_in_tasks.id", ondelete="CASCADE"), nullable=False, index=True, comment="任务 ID")
|
||||
status = Column(String(20), nullable=False, index=True, comment="状态: success/failure/out_of_time/unknown/pending")
|
||||
response_text = Column(Text, default="", comment="响应文本")
|
||||
error_message = Column(Text, default="", comment="错误信息")
|
||||
location = Column(Text, default="{}", comment="位置信息 JSON")
|
||||
trigger_type = Column(String(50), default="scheduled", comment="触发类型: scheduled/manual/admin")
|
||||
check_in_time = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True, comment="打卡时间(UTC)")
|
||||
|
||||
# 关联任务
|
||||
task = relationship("CheckInTask", back_populates="check_in_records")
|
||||
|
||||
# 添加复合索引:加速常见查询
|
||||
__table_args__ = (
|
||||
Index('ix_record_task_time', 'task_id', 'check_in_time'), # 获取任务的打卡记录(按时间排序)
|
||||
Index('ix_record_status_time', 'status', 'check_in_time'), # 按状态和时间查询
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<CheckInRecord(id={self.id}, task_id={self.task_id}, status={self.status})>"
|
||||
@@ -0,0 +1,39 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, Text, DateTime, ForeignKey, Index
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from backend.models.database import Base
|
||||
|
||||
|
||||
class CheckInTask(Base):
|
||||
"""打卡任务模型"""
|
||||
|
||||
__tablename__ = "check_in_tasks"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True, comment="用户 ID")
|
||||
payload_config = Column(Text, default="{}", nullable=False, comment="完整的 payload 配置 JSON(从模板生成,包含 ThreadId 和所有字段)")
|
||||
name = Column(String(100), default="", comment="任务名称(用户自定义)")
|
||||
is_active = Column(Boolean, default=True, comment="是否启用自动打卡(不影响手动打卡)")
|
||||
cron_expression = Column(String(100), default="0 20 * * *", nullable=True, comment="Crontab 表达式(NULL 表示禁用自动打卡,否则按表达式执行)")
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
# 关联用户
|
||||
user = relationship("User", back_populates="tasks")
|
||||
|
||||
# 关联打卡记录
|
||||
check_in_records = relationship("CheckInRecord", back_populates="task", cascade="all, delete-orphan")
|
||||
|
||||
# 添加索引:加速查询
|
||||
__table_args__ = (
|
||||
Index('ix_task_user_active', 'user_id', 'is_active'),
|
||||
Index('ix_task_cron', 'cron_expression'), # 加速查询启用了定时打卡的任务
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<CheckInTask(id={self.id}, user_id={self.user_id}, name={self.name}, cron={self.cron_expression})>"
|
||||
|
||||
@property
|
||||
def is_scheduled_enabled(self) -> bool:
|
||||
"""判断是否启用了自动打卡(is_active 为 True 且 cron_expression 不为空)"""
|
||||
return bool(self.is_active) and bool(self.cron_expression)
|
||||
@@ -0,0 +1,52 @@
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from datetime import datetime, timezone
|
||||
from backend.config import settings
|
||||
|
||||
# 创建数据库引擎
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}, # SQLite 特定配置
|
||||
echo=False, # 生产环境设为 False
|
||||
)
|
||||
|
||||
# 创建会话工厂
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# 创建基类
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# SQLite timezone 修复:在加载对象后,将所有 naive datetime 转换为 UTC timezone-aware
|
||||
@event.listens_for(Base, "load", propagate=True)
|
||||
def receive_load(target, context):
|
||||
"""在从数据库加载对象后,将所有 datetime 字段转换为 timezone-aware (UTC)"""
|
||||
for attr_name in dir(target):
|
||||
# 跳过私有属性和方法
|
||||
if attr_name.startswith('_'):
|
||||
continue
|
||||
|
||||
try:
|
||||
attr_value = getattr(target, attr_name)
|
||||
|
||||
# 如果是 naive datetime,添加 UTC timezone
|
||||
if isinstance(attr_value, datetime) and attr_value.tzinfo is None:
|
||||
setattr(target, attr_name, attr_value.replace(tzinfo=timezone.utc))
|
||||
except (AttributeError, TypeError):
|
||||
# 某些属性可能无法访问或设置,跳过
|
||||
continue
|
||||
|
||||
|
||||
def get_db():
|
||||
"""依赖注入:获取数据库会话"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""初始化数据库:创建所有表"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -0,0 +1,29 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, Text, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from backend.models.database import Base
|
||||
|
||||
|
||||
class TaskTemplate(Base):
|
||||
"""打卡任务模板"""
|
||||
__tablename__ = "task_templates"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
||||
name = Column(String(100), nullable=False, comment="模板名称")
|
||||
description = Column(Text, nullable=True, comment="模板描述")
|
||||
|
||||
# 父模板 ID(用于继承)
|
||||
parent_id = Column(Integer, ForeignKey("task_templates.id", ondelete="SET NULL"), nullable=True, comment="父模板 ID")
|
||||
|
||||
# 字段配置(JSON 格式)
|
||||
field_config = Column(Text, nullable=False, comment="字段配置(JSON)")
|
||||
|
||||
is_active = Column(Boolean, default=True, comment="是否启用")
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
# 自引用关系:父模板和子模板
|
||||
parent = relationship("TaskTemplate", remote_side=[id], backref="children")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<TaskTemplate(id={self.id}, name='{self.name}', is_active={self.is_active})>"
|
||||
@@ -0,0 +1,46 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, Index
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from backend.models.database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""用户模型 - 账户信息"""
|
||||
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
||||
jwt_sub = Column(String(200), unique=True, nullable=True, index=True, comment="QQ 扫码登录的唯一用户标识(注册时为空)")
|
||||
alias = Column(String(50), unique=True, nullable=False, index=True, comment="用户别名(用于登录)")
|
||||
email = Column(String(100), nullable=True, comment="用户邮箱(用于接收通知)")
|
||||
password_hash = Column(String(200), nullable=True, comment="密码哈希(bcrypt加密)")
|
||||
authorization = Column(Text, nullable=True, comment="当前有效的 QQ Token")
|
||||
jwt_exp = Column(String(20), default="0", comment="Token 过期时间戳")
|
||||
token_expiring_notified = Column(Boolean, default=False, nullable=False, comment="Token 即将过期提醒是否已发送(过期前30分钟)")
|
||||
token_expired_notified = Column(Boolean, default=False, nullable=False, comment="Token 已过期提醒是否已发送(过期后30分钟内)")
|
||||
role = Column(String(20), default="user", index=True, comment="角色: user/admin")
|
||||
is_approved = Column(Boolean, default=False, index=True, comment="是否已通过管理员审批")
|
||||
|
||||
# 账户锁定相关字段
|
||||
failed_login_attempts = Column(Integer, default=0, nullable=False, comment="连续登录失败次数")
|
||||
locked_until = Column(DateTime(timezone=True), nullable=True, comment="账户锁定到期时间")
|
||||
last_failed_login = Column(DateTime(timezone=True), nullable=True, comment="最后一次登录失败时间")
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
# 关联打卡任务
|
||||
tasks = relationship("CheckInTask", back_populates="user", cascade="all, delete-orphan")
|
||||
|
||||
# 添加复合索引:加速审批管理查询
|
||||
__table_args__ = (
|
||||
Index('ix_user_role_approved', 'role', 'is_approved'), # 管理员查询待审批用户
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<User(id={self.id}, alias={self.alias}, jwt_sub={self.jwt_sub}, role={self.role})>"
|
||||
|
||||
@property
|
||||
def is_admin(self) -> bool:
|
||||
"""判断是否为管理员"""
|
||||
return self.role == "admin"
|
||||
Reference in New Issue
Block a user