初始提交:项目基础结构
- backend: FastAPI 后端服务 (Python) - frontend: React + Tauri 前端应用 - docker-compose.yml: 容器编排配置
This commit is contained in:
1
backend/app/__init__.py
Normal file
1
backend/app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Track Production API
|
||||
BIN
backend/app/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/v1/__init__.py
Normal file
0
backend/app/api/v1/__init__.py
Normal file
7
backend/app/api/v1/router.py
Normal file
7
backend/app/api/v1/router.py
Normal file
@ -0,0 +1,7 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
# 后续在此注册子路由
|
||||
# from app.api.v1 import users, products, orders, ...
|
||||
# api_router.include_router(users.router, prefix="/users", tags=["用户管理"])
|
||||
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
BIN
backend/app/core/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
backend/app/core/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/core/__pycache__/config.cpython-313.pyc
Normal file
BIN
backend/app/core/__pycache__/config.cpython-313.pyc
Normal file
Binary file not shown.
33
backend/app/core/config.py
Normal file
33
backend/app/core/config.py
Normal file
@ -0,0 +1,33 @@
|
||||
"""核心配置 — Pydantic Settings 自动从 .env 读取"""
|
||||
import json
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# ---- 数据库 ----
|
||||
DATABASE_URL: str = "postgresql+asyncpg://track:track_prod_2026@localhost:5433/track_production"
|
||||
|
||||
# ---- JWT ----
|
||||
SECRET_KEY: str = "change-me-in-production"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# ---- 调试 ----
|
||||
DEBUG: bool = True
|
||||
|
||||
# ---- CORS 跨域白名单(JSON 数组字符串,直接从 .env 的 CORS_ORIGINS 读取) ----
|
||||
CORS_ORIGINS: str = '["http://localhost:1420", "tauri://localhost"]'
|
||||
|
||||
@property
|
||||
def CORS_ORIGINS_LIST(self) -> list[str]:
|
||||
"""将 JSON 字符串解析为 Python list,供 CORSMiddleware 使用"""
|
||||
try:
|
||||
return json.loads(self.CORS_ORIGINS)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return ["http://localhost:1420", "tauri://localhost"]
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
24
backend/app/core/database.py
Normal file
24
backend/app/core/database.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""数据库连接 — 异步引擎 + 连接池"""
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.DATABASE_URL,
|
||||
echo=settings.DEBUG,
|
||||
pool_size=20, # 连接池常驻连接数
|
||||
max_overflow=10, # 超出 pool_size 时最多再创建的连接数
|
||||
pool_recycle=3600, # 连接回收时间(秒),防止 MySQL 8 小时断连
|
||||
pool_pre_ping=True, # 每次取出连接前先 ping 检测可用性
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
"""FastAPI 依赖注入:每次请求获取一个数据库会话"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
29
backend/app/core/security.py
Normal file
29
backend/app/core/security.py
Normal file
@ -0,0 +1,29 @@
|
||||
"""安全模块 — JWT Token 生成与验证"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
|
||||
"""生成 JWT Access Token"""
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + (
|
||||
expires_delta or timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
)
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""验证明文密码 vs 哈希密码"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""对明文密码进行哈希"""
|
||||
return pwd_context.hash(password)
|
||||
38
backend/app/main.py
Normal file
38
backend/app/main.py
Normal file
@ -0,0 +1,38 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.core.config import settings
|
||||
from app.api.v1.router import api_router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期:启动时初始化连接,关闭时释放资源"""
|
||||
# 启动:验证数据库连接等
|
||||
yield
|
||||
# 关闭:清理资源
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Track Production API",
|
||||
description="工厂生产流转管理系统 API",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# ---- CORS 跨域配置(从环境变量读取白名单) ----
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.CORS_ORIGINS_LIST,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# ---- 注册路由 ----
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok", "version": "0.1.0"}
|
||||
14
backend/app/models/__init__.py
Normal file
14
backend/app/models/__init__.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""模型包 — 导入 Base 及所有模型,供 Alembic 自动发现"""
|
||||
from app.models.base import Base
|
||||
from app.models.production_order import ProductionOrder
|
||||
from app.models.product import Product
|
||||
from app.models.task import Task
|
||||
from app.models.task_log import TaskLog
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"ProductionOrder",
|
||||
"Product",
|
||||
"Task",
|
||||
"TaskLog",
|
||||
]
|
||||
BIN
backend/app/models/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/models/__pycache__/base.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/base.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/models/__pycache__/product.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/product.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/models/__pycache__/production_order.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/production_order.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/models/__pycache__/task.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/task.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/models/__pycache__/task_log.cpython-313.pyc
Normal file
BIN
backend/app/models/__pycache__/task_log.cpython-313.pyc
Normal file
Binary file not shown.
6
backend/app/models/base.py
Normal file
6
backend/app/models/base.py
Normal file
@ -0,0 +1,6 @@
|
||||
"""SQLAlchemy 声明式基类"""
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
50
backend/app/models/product.py
Normal file
50
backend/app/models/product.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""产品模型"""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import String, DateTime, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Product(Base):
|
||||
__tablename__ = "products"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,
|
||||
)
|
||||
serial_number: Mapped[str] = mapped_column(
|
||||
String(16), unique=True, index=True, nullable=False, comment="产品序列号(16位)",
|
||||
)
|
||||
|
||||
# ---- 物理外键(关联本库 production_orders) ----
|
||||
order_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("production_orders.id"), nullable=False, comment="所属订单ID",
|
||||
)
|
||||
|
||||
# ---- 逻辑外键(关联老系统物料表,仅存储 ID,无物理约束) ----
|
||||
material_id: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, comment="物料ID(逻辑外键→老系统)",
|
||||
)
|
||||
|
||||
# ---- 物理外键(自引用:父产品) ----
|
||||
parent_product_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("products.id"), nullable=True, comment="父产品ID",
|
||||
)
|
||||
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, default="pending", comment="产品状态",
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), comment="创建时间",
|
||||
)
|
||||
|
||||
# ---- 关系 ----
|
||||
order: Mapped["ProductionOrder"] = relationship("ProductionOrder", lazy="selectin")
|
||||
parent_product: Mapped["Product | None"] = relationship(
|
||||
"Product", remote_side="Product.id", lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Product {self.serial_number}>"
|
||||
31
backend/app/models/production_order.py
Normal file
31
backend/app/models/production_order.py
Normal file
@ -0,0 +1,31 @@
|
||||
"""生产订单模型"""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import String, DateTime
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ProductionOrder(Base):
|
||||
__tablename__ = "production_orders"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,
|
||||
)
|
||||
order_no: Mapped[str] = mapped_column(
|
||||
String(64), unique=True, index=True, nullable=False, comment="订单编号",
|
||||
)
|
||||
customer_info: Mapped[str | None] = mapped_column(
|
||||
String(500), nullable=True, comment="客户信息",
|
||||
)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, default="pending", comment="订单状态",
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), comment="创建时间",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ProductionOrder {self.order_no}>"
|
||||
59
backend/app/models/task.py
Normal file
59
backend/app/models/task.py
Normal file
@ -0,0 +1,59 @@
|
||||
"""任务模型 — 支持无限嵌套"""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import String, DateTime, Boolean, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Task(Base):
|
||||
__tablename__ = "tasks"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,
|
||||
)
|
||||
|
||||
# ---- 物理外键(关联本库 products) ----
|
||||
product_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("products.id"), nullable=False, comment="所属产品ID",
|
||||
)
|
||||
|
||||
# ---- 物理外键(自引用:无限嵌套父子任务) ----
|
||||
parent_task_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("tasks.id"), nullable=True, index=True, comment="父任务ID",
|
||||
)
|
||||
|
||||
task_name: Mapped[str] = mapped_column(
|
||||
String(200), nullable=False, comment="任务名称",
|
||||
)
|
||||
|
||||
# ---- 逻辑外键(关联老系统用户表,仅存储 ID,无物理约束) ----
|
||||
assignee_id: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, comment="负责人ID(逻辑外键→老系统)",
|
||||
)
|
||||
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, default="pending", comment="任务状态",
|
||||
)
|
||||
|
||||
notify_parent_on_complete: Mapped[bool] = mapped_column(
|
||||
Boolean, default=False, comment="完成后是否通知父任务",
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), comment="创建时间",
|
||||
)
|
||||
|
||||
# ---- 关系 ----
|
||||
product: Mapped["Product"] = relationship("Product", lazy="selectin")
|
||||
parent_task: Mapped["Task | None"] = relationship(
|
||||
"Task", remote_side="Task.id", back_populates="child_tasks", lazy="selectin",
|
||||
)
|
||||
child_tasks: Mapped[list["Task"]] = relationship(
|
||||
"Task", back_populates="parent_task", lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Task {self.task_name}>"
|
||||
44
backend/app/models/task_log.py
Normal file
44
backend/app/models/task_log.py
Normal file
@ -0,0 +1,44 @@
|
||||
"""任务操作日志模型"""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import String, DateTime, ForeignKey, Text
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class TaskLog(Base):
|
||||
__tablename__ = "task_logs"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,
|
||||
)
|
||||
|
||||
# ---- 物理外键(关联本库 tasks) ----
|
||||
task_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("tasks.id"), nullable=False, index=True, comment="所属任务ID",
|
||||
)
|
||||
|
||||
# ---- 逻辑外键(关联老系统用户表,仅存储 ID,无物理约束) ----
|
||||
operator_id: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, comment="操作人ID(逻辑外键→老系统)",
|
||||
)
|
||||
|
||||
action_type: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, comment="操作类型",
|
||||
)
|
||||
|
||||
remark: Mapped[str | None] = mapped_column(
|
||||
Text, nullable=True, comment="备注",
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), comment="创建时间",
|
||||
)
|
||||
|
||||
# ---- 关系 ----
|
||||
task: Mapped["Task"] = relationship("Task", lazy="selectin")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<TaskLog {self.action_type} @ {self.created_at}>"
|
||||
0
backend/app/schemas/__init__.py
Normal file
0
backend/app/schemas/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
Reference in New Issue
Block a user