初始提交:项目基础结构

- backend: FastAPI 后端服务 (Python)
- frontend: React + Tauri 前端应用
- docker-compose.yml: 容器编排配置
This commit is contained in:
2026-08-04 10:05:59 +08:00
commit 17105dc9c2
61 changed files with 3633 additions and 0 deletions

13
backend/.env Normal file
View File

@ -0,0 +1,13 @@
# ============================================================
# 生产流转管理系统 — 后端环境变量
# 测试环境局域网 IP: 192.168.9.80
# 数据库: PostgreSQL 15 + pgvector (独立容器, 端口 5433)
# ============================================================
DATABASE_URL=postgresql+asyncpg://track:track_prod_2026@localhost:5433/track_production
SECRET_KEY=change-me-to-a-random-secret-key-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=30
DEBUG=true
# 跨域白名单JSON 数组格式,供 pydantic 解析)
CORS_ORIGINS='["http://localhost:1420", "tauri://localhost", "http://192.168.9.80:1420", "http://192.168.9.80"]'

5
backend/.env.example Normal file
View File

@ -0,0 +1,5 @@
DATABASE_URL=postgresql+asyncpg://track:track_prod_2026@localhost:5433/track_production
SECRET_KEY=change-me-to-a-random-secret-key-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=30
DEBUG=true
CORS_ORIGINS='["http://localhost:1420", "tauri://localhost"]'

150
backend/alembic.ini Normal file
View File

@ -0,0 +1,150 @@
# 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 已由 env.py 从 app.core.config.settings 自动读取,此处仅作占位
sqlalchemy.url = postgresql+asyncpg://track:track_prod_2026@localhost:5433/track_production
[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
backend/alembic/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

59
backend/alembic/env.py Normal file
View File

@ -0,0 +1,59 @@
"""Alembic 迁移环境配置 — 异步引擎 + 自动加载模型"""
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy.ext.asyncio import create_async_engine
from app.core.config import settings
from app.models import Base # 自动发现所有 SQLAlchemy 模型
# Alembic Config 对象
config = context.config
# 日志配置
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# 将 DATABASE_URL 同步到 alembic 配置中(覆盖 alembic.ini 中的占位值)
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
# 自动生成迁移时需要的 models 元数据
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""离线模式:生成 SQL 脚本而非直接执行"""
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 do_run_migrations(connection):
"""在线模式:通过数据库连接执行迁移"""
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
"""在线模式:异步引擎"""
connectable = create_async_engine(
config.get_main_option("sqlalchemy.url"),
echo=settings.DEBUG,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

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"}

1
backend/app/__init__.py Normal file
View File

@ -0,0 +1 @@
# Track Production API

Binary file not shown.

View File

View File

View 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=["用户管理"])

View File

Binary file not shown.

Binary file not shown.

View 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()

View 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

View 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
View 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"}

View 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",
]

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,6 @@
"""SQLAlchemy 声明式基类"""
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass

View 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}>"

View 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}>"

View 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}>"

View 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}>"

View File

View File

38
backend/requirements.txt Normal file
View File

@ -0,0 +1,38 @@
alembic==1.18.5
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.14.2
asyncpg==0.31.0
bcrypt==5.0.0
cffi==2.1.1
click==8.4.2
colorama==0.4.6
cryptography==50.0.0
ecdsa==0.19.2
fastapi==0.141.1
greenlet==3.5.4
h11==0.16.0
httptools==0.8.0
idna==3.18
Mako==1.3.12
MarkupSafe==3.0.3
passlib==1.7.4
psycopg2-binary==2.9.12
pyasn1==0.6.4
pycparser==3.0
pydantic==2.13.4
pydantic-settings==2.14.2
pydantic_core==2.46.4
python-dotenv==1.2.2
python-jose==3.5.0
python-multipart==0.0.32
PyYAML==6.0.3
rsa==4.9.1
six==1.17.0
SQLAlchemy==2.0.51
starlette==1.3.1
typing-inspection==0.4.2
typing_extensions==4.16.0
uvicorn==0.52.1
watchfiles==1.2.0
websockets==17.0.1