initial commit
This commit is contained in:
@@ -0,0 +1,12 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
Binary file not shown.
@@ -0,0 +1,16 @@
|
|||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||||
|
|
||||||
|
DATABASE_URL = "sqlite:///./data/inventory.db"
|
||||||
|
|
||||||
|
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
version: "3.8"
|
||||||
|
|
||||||
|
services:
|
||||||
|
inventory:
|
||||||
|
build: .
|
||||||
|
container_name: inventory-management
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "8011:8000"
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
- ./static:/app/static
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from database import engine, Base
|
||||||
|
from models import Inventory, TransactionLog
|
||||||
|
|
||||||
|
# 初始化数据库表
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
print("数据库表创建成功!")
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from database import engine, Base
|
||||||
|
from routers import router
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 创建数据表
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
app = FastAPI(title="库存管理系统", version="1.0.0")
|
||||||
|
|
||||||
|
# CORS
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# API路由
|
||||||
|
app.include_router(router, prefix="/api")
|
||||||
|
|
||||||
|
# 健康检查
|
||||||
|
@app.get("/api/health")
|
||||||
|
def health():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
# 静态文件(前端) - 必须放在最后
|
||||||
|
static_dir = os.path.join(os.path.dirname(__file__), "static")
|
||||||
|
if os.path.exists(static_dir):
|
||||||
|
app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Float, DateTime, Text, func
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Inventory(Base):
|
||||||
|
"""库存表"""
|
||||||
|
__tablename__ = "inventory"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="序号")
|
||||||
|
cInvCode = Column(String(100), nullable=False, index=True, comment="产品编码")
|
||||||
|
supplier = Column(String(200), nullable=True, comment="供应商")
|
||||||
|
casing_label_remark = Column(Text, nullable=True, comment="现外壳&标签&备注")
|
||||||
|
batch = Column(String(100), nullable=True, comment="批次")
|
||||||
|
current_remaining = Column(Float, default=0, comment="当前时间剩余")
|
||||||
|
storage_location = Column(String(200), nullable=True, comment="存货地点")
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||||
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||||
|
|
||||||
|
|
||||||
|
class TransactionLog(Base):
|
||||||
|
"""出入库记录表"""
|
||||||
|
__tablename__ = "transaction_log"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
||||||
|
inventory_id = Column(Integer, nullable=False, index=True, comment="库存ID")
|
||||||
|
cInvCode = Column(String(100), nullable=False, index=True, comment="产品编码")
|
||||||
|
type = Column(String(10), nullable=False, comment="类型: in/out")
|
||||||
|
quantity = Column(Float, nullable=False, comment="数量")
|
||||||
|
remark = Column(Text, nullable=True, comment="备注")
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), comment="操作时间")
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn==0.30.6
|
||||||
|
sqlalchemy==2.0.35
|
||||||
|
openpyxl==3.1.5
|
||||||
|
python-multipart==0.0.12
|
||||||
|
pydantic==2.9.2
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Query
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy import or_
|
||||||
|
from typing import Optional
|
||||||
|
import io
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from database import get_db
|
||||||
|
from models import Inventory, TransactionLog
|
||||||
|
from schemas import InventoryCreate, InventoryUpdate, StockOperation
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def inventory_to_dict(item: Inventory) -> dict:
|
||||||
|
"""将Inventory模型转为字典"""
|
||||||
|
return {
|
||||||
|
"id": item.id,
|
||||||
|
"cInvCode": item.cInvCode,
|
||||||
|
"supplier": item.supplier,
|
||||||
|
"casing_label_remark": item.casing_label_remark,
|
||||||
|
"batch": item.batch,
|
||||||
|
"current_remaining": item.current_remaining,
|
||||||
|
"storage_location": item.storage_location,
|
||||||
|
"created_at": item.created_at.isoformat() if item.created_at else None,
|
||||||
|
"updated_at": item.updated_at.isoformat() if item.updated_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def log_to_dict(log: TransactionLog) -> dict:
|
||||||
|
"""将TransactionLog模型转为字典"""
|
||||||
|
return {
|
||||||
|
"id": log.id,
|
||||||
|
"inventory_id": log.inventory_id,
|
||||||
|
"cInvCode": log.cInvCode,
|
||||||
|
"type": log.type,
|
||||||
|
"quantity": log.quantity,
|
||||||
|
"remark": log.remark,
|
||||||
|
"created_at": log.created_at.isoformat() if log.created_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 库存 CRUD =====
|
||||||
|
|
||||||
|
@router.get("/inventory")
|
||||||
|
def list_inventory(
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
|
search: Optional[str] = None,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""获取库存列表,支持分页和搜索"""
|
||||||
|
query = db.query(Inventory)
|
||||||
|
if search:
|
||||||
|
keyword = f"%{search}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
Inventory.cInvCode.like(keyword),
|
||||||
|
Inventory.supplier.like(keyword),
|
||||||
|
Inventory.batch.like(keyword),
|
||||||
|
Inventory.storage_location.like(keyword),
|
||||||
|
Inventory.casing_label_remark.like(keyword),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
total = query.count()
|
||||||
|
items = query.order_by(Inventory.id.asc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||||
|
return {"total": total, "items": [inventory_to_dict(i) for i in items]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/inventory")
|
||||||
|
def create_inventory(data: InventoryCreate, db: Session = Depends(get_db)):
|
||||||
|
"""新增库存"""
|
||||||
|
item = Inventory(**data.model_dump())
|
||||||
|
db.add(item)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(item)
|
||||||
|
return inventory_to_dict(item)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/inventory/{item_id}")
|
||||||
|
def update_inventory(item_id: int, data: InventoryUpdate, db: Session = Depends(get_db)):
|
||||||
|
"""更新库存"""
|
||||||
|
item = db.query(Inventory).filter(Inventory.id == item_id).first()
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="库存记录不存在")
|
||||||
|
update_data = data.model_dump(exclude_unset=True)
|
||||||
|
for key, value in update_data.items():
|
||||||
|
setattr(item, key, value)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(item)
|
||||||
|
return inventory_to_dict(item)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/inventory/{item_id}")
|
||||||
|
def delete_inventory(item_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""删除库存"""
|
||||||
|
item = db.query(Inventory).filter(Inventory.id == item_id).first()
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="库存记录不存在")
|
||||||
|
db.delete(item)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "删除成功"}
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 出入库 =====
|
||||||
|
|
||||||
|
@router.post("/stock/operation")
|
||||||
|
def stock_operation(op: StockOperation, db: Session = Depends(get_db)):
|
||||||
|
"""出入库操作"""
|
||||||
|
item = db.query(Inventory).filter(Inventory.id == op.inventory_id).first()
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(status_code=404, detail="库存记录不存在")
|
||||||
|
|
||||||
|
if op.type == "out":
|
||||||
|
if item.current_remaining < op.quantity:
|
||||||
|
raise HTTPException(status_code=400, detail=f"库存不足,当前剩余: {item.current_remaining}")
|
||||||
|
item.current_remaining -= op.quantity
|
||||||
|
elif op.type == "in":
|
||||||
|
item.current_remaining += op.quantity
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=400, detail="类型必须是 in 或 out")
|
||||||
|
|
||||||
|
# 记录操作日志
|
||||||
|
log = TransactionLog(
|
||||||
|
inventory_id=item.id,
|
||||||
|
cInvCode=item.cInvCode,
|
||||||
|
type=op.type,
|
||||||
|
quantity=op.quantity,
|
||||||
|
remark=op.remark,
|
||||||
|
)
|
||||||
|
db.add(log)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(item)
|
||||||
|
return {"message": "操作成功", "current_remaining": item.current_remaining}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/stock/logs")
|
||||||
|
def clear_stock_logs(db: Session = Depends(get_db)):
|
||||||
|
"""清空所有出入库记录"""
|
||||||
|
count = db.query(TransactionLog).delete()
|
||||||
|
db.commit()
|
||||||
|
return {"message": f"已清空 {count} 条出入库记录"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stock/logs")
|
||||||
|
def get_stock_logs(
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
|
search: Optional[str] = None,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""获取出入库记录"""
|
||||||
|
query = db.query(TransactionLog)
|
||||||
|
if search:
|
||||||
|
keyword = f"%{search}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
TransactionLog.cInvCode.like(keyword),
|
||||||
|
TransactionLog.remark.like(keyword),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
total = query.count()
|
||||||
|
items = query.order_by(TransactionLog.id.asc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||||
|
return {"total": total, "items": [log_to_dict(l) for l in items]}
|
||||||
|
|
||||||
|
|
||||||
|
# ===== Excel 导入导出 =====
|
||||||
|
|
||||||
|
@router.get("/inventory/export")
|
||||||
|
def export_inventory(db: Session = Depends(get_db)):
|
||||||
|
"""导出库存为Excel"""
|
||||||
|
items = db.query(Inventory).order_by(Inventory.id.asc()).all()
|
||||||
|
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "库存数据"
|
||||||
|
|
||||||
|
# 表头
|
||||||
|
headers = ["序号", "产品编码", "供应商", "现外壳&标签&备注", "批次", "当前时间剩余", "存货地点"]
|
||||||
|
ws.append(headers)
|
||||||
|
|
||||||
|
# 表头样式
|
||||||
|
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||||
|
header_font = Font(bold=True, size=12, color="FFFFFF")
|
||||||
|
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
|
||||||
|
header_alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
thin_border = Border(
|
||||||
|
left=Side(style='thin'), right=Side(style='thin'),
|
||||||
|
top=Side(style='thin'), bottom=Side(style='thin')
|
||||||
|
)
|
||||||
|
|
||||||
|
for col_idx, header in enumerate(headers, 1):
|
||||||
|
cell = ws.cell(row=1, column=col_idx, value=header)
|
||||||
|
cell.font = header_font
|
||||||
|
cell.fill = header_fill
|
||||||
|
cell.alignment = header_alignment
|
||||||
|
cell.border = thin_border
|
||||||
|
|
||||||
|
# 数据行
|
||||||
|
for item in items:
|
||||||
|
row_data = [
|
||||||
|
item.id,
|
||||||
|
item.cInvCode,
|
||||||
|
item.supplier or "",
|
||||||
|
item.casing_label_remark or "",
|
||||||
|
item.batch or "",
|
||||||
|
item.current_remaining,
|
||||||
|
item.storage_location or "",
|
||||||
|
]
|
||||||
|
ws.append(row_data)
|
||||||
|
|
||||||
|
# 调整列宽
|
||||||
|
col_widths = [8, 20, 20, 30, 15, 15, 20]
|
||||||
|
for idx, width in enumerate(col_widths, 1):
|
||||||
|
ws.column_dimensions[openpyxl.utils.get_column_letter(idx)].width = width
|
||||||
|
|
||||||
|
# 保存到内存
|
||||||
|
output = io.BytesIO()
|
||||||
|
wb.save(output)
|
||||||
|
output.seek(0)
|
||||||
|
|
||||||
|
filename = f"库存数据_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||||
|
filename_encoded = quote(filename)
|
||||||
|
return StreamingResponse(
|
||||||
|
output,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename={filename_encoded}; filename*=UTF-8''{filename_encoded}"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/inventory/import")
|
||||||
|
def import_inventory(file: UploadFile = File(...), db: Session = Depends(get_db)):
|
||||||
|
"""从Excel导入库存"""
|
||||||
|
if not file.filename.endswith(('.xlsx', '.xls')):
|
||||||
|
raise HTTPException(status_code=400, detail="只支持 .xlsx 或 .xls 文件")
|
||||||
|
|
||||||
|
try:
|
||||||
|
contents = file.file.read()
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(contents))
|
||||||
|
ws = wb.active
|
||||||
|
|
||||||
|
imported = 0
|
||||||
|
updated = 0
|
||||||
|
errors = []
|
||||||
|
|
||||||
|
# 查找表头位置
|
||||||
|
header_map = {}
|
||||||
|
expected_headers = {
|
||||||
|
"序号": "id",
|
||||||
|
"产品编码": "cInvCode",
|
||||||
|
"供应商": "supplier",
|
||||||
|
"现外壳&标签&备注": "casing_label_remark",
|
||||||
|
"外壳&标签&备注": "casing_label_remark",
|
||||||
|
"批次": "batch",
|
||||||
|
"当前时间剩余": "current_remaining",
|
||||||
|
"存货地点": "storage_location",
|
||||||
|
}
|
||||||
|
|
||||||
|
for row_idx, row in enumerate(ws.iter_rows(min_row=1, max_row=5), 1):
|
||||||
|
for col_idx, cell in enumerate(row):
|
||||||
|
if cell.value and str(cell.value).strip() in expected_headers:
|
||||||
|
header_map[str(cell.value).strip()] = col_idx
|
||||||
|
|
||||||
|
if not header_map.get("产品编码"):
|
||||||
|
raise HTTPException(status_code=400, detail="未找到有效的表头行,请确保包含'产品编码'列")
|
||||||
|
|
||||||
|
# 解析数据行(从第2行开始,假设第1行是表头)
|
||||||
|
for row_idx, row in enumerate(ws.iter_rows(min_row=2), 2):
|
||||||
|
try:
|
||||||
|
# 先读取序号
|
||||||
|
id_col = header_map.get("序号")
|
||||||
|
record_id = None
|
||||||
|
if id_col is not None and id_col < len(row):
|
||||||
|
id_val = row[id_col].value
|
||||||
|
if id_val is not None:
|
||||||
|
try:
|
||||||
|
record_id = int(float(id_val))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
record_id = None
|
||||||
|
|
||||||
|
cInvCode_col = header_map.get("产品编码")
|
||||||
|
if cInvCode_col is None:
|
||||||
|
continue
|
||||||
|
cInvCode = row[cInvCode_col].value if cInvCode_col < len(row) else None
|
||||||
|
if not cInvCode:
|
||||||
|
continue
|
||||||
|
cInvCode = str(cInvCode).strip()
|
||||||
|
|
||||||
|
def get_val(key, default=""):
|
||||||
|
col = header_map.get(key)
|
||||||
|
if col is not None and col < len(row):
|
||||||
|
val = row[col].value
|
||||||
|
return str(val).strip() if val is not None else default
|
||||||
|
return default
|
||||||
|
|
||||||
|
supplier = get_val("供应商")
|
||||||
|
casing_label_remark = get_val("现外壳&标签&备注") or get_val("外壳&标签&备注")
|
||||||
|
batch = get_val("批次")
|
||||||
|
storage_location = get_val("存货地点")
|
||||||
|
|
||||||
|
current_remaining_val = 0
|
||||||
|
cr_col = header_map.get("当前时间剩余")
|
||||||
|
if cr_col is not None and cr_col < len(row):
|
||||||
|
val = row[cr_col].value
|
||||||
|
try:
|
||||||
|
current_remaining_val = float(val) if val is not None else 0
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
current_remaining_val = 0
|
||||||
|
|
||||||
|
# 按序号优先,否则按产品编码+批次
|
||||||
|
if record_id:
|
||||||
|
# 按序号查找
|
||||||
|
existing = db.query(Inventory).filter(Inventory.id == record_id).first()
|
||||||
|
if existing:
|
||||||
|
existing.cInvCode = cInvCode
|
||||||
|
existing.supplier = supplier
|
||||||
|
existing.casing_label_remark = casing_label_remark
|
||||||
|
existing.batch = batch
|
||||||
|
existing.current_remaining = current_remaining_val
|
||||||
|
existing.storage_location = storage_location
|
||||||
|
updated += 1
|
||||||
|
else:
|
||||||
|
# 序号不存在,新增并指定ID
|
||||||
|
new_item = Inventory(
|
||||||
|
id=record_id,
|
||||||
|
cInvCode=cInvCode,
|
||||||
|
supplier=supplier,
|
||||||
|
casing_label_remark=casing_label_remark,
|
||||||
|
batch=batch,
|
||||||
|
current_remaining=current_remaining_val,
|
||||||
|
storage_location=storage_location,
|
||||||
|
)
|
||||||
|
db.add(new_item)
|
||||||
|
imported += 1
|
||||||
|
else:
|
||||||
|
# 按产品编码+批次去重
|
||||||
|
existing = db.query(Inventory).filter(
|
||||||
|
Inventory.cInvCode == cInvCode,
|
||||||
|
Inventory.batch == batch
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
existing.supplier = supplier or existing.supplier
|
||||||
|
existing.casing_label_remark = casing_label_remark or existing.casing_label_remark
|
||||||
|
existing.current_remaining = current_remaining_val if current_remaining_val else existing.current_remaining
|
||||||
|
existing.storage_location = storage_location or existing.storage_location
|
||||||
|
updated += 1
|
||||||
|
else:
|
||||||
|
new_item = Inventory(
|
||||||
|
cInvCode=cInvCode,
|
||||||
|
supplier=supplier,
|
||||||
|
casing_label_remark=casing_label_remark,
|
||||||
|
batch=batch,
|
||||||
|
current_remaining=current_remaining_val,
|
||||||
|
storage_location=storage_location,
|
||||||
|
)
|
||||||
|
db.add(new_item)
|
||||||
|
imported += 1
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
errors.append(f"第{row_idx}行: {str(e)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
return {
|
||||||
|
"message": f"导入完成:新增 {imported} 条,更新 {updated} 条",
|
||||||
|
"imported": imported,
|
||||||
|
"updated": updated,
|
||||||
|
"errors": errors[:10],
|
||||||
|
}
|
||||||
|
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 导出出入库记录 =====
|
||||||
|
|
||||||
|
@router.get("/stock/export")
|
||||||
|
def export_stock_logs(db: Session = Depends(get_db)):
|
||||||
|
"""导出出入库记录为Excel"""
|
||||||
|
items = db.query(TransactionLog).order_by(TransactionLog.id.desc()).all()
|
||||||
|
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "出入库记录"
|
||||||
|
|
||||||
|
headers = ["序号", "产品编码", "类型", "数量", "备注", "操作时间"]
|
||||||
|
ws.append(headers)
|
||||||
|
|
||||||
|
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||||
|
header_font = Font(bold=True, size=12, color="FFFFFF")
|
||||||
|
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
|
||||||
|
header_alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
thin_border = Border(
|
||||||
|
left=Side(style='thin'), right=Side(style='thin'),
|
||||||
|
top=Side(style='thin'), bottom=Side(style='thin')
|
||||||
|
)
|
||||||
|
|
||||||
|
for col_idx, header in enumerate(headers, 1):
|
||||||
|
cell = ws.cell(row=1, column=col_idx, value=header)
|
||||||
|
cell.font = header_font
|
||||||
|
cell.fill = header_fill
|
||||||
|
cell.alignment = header_alignment
|
||||||
|
cell.border = thin_border
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
ws.append([
|
||||||
|
item.id,
|
||||||
|
item.cInvCode,
|
||||||
|
"入库" if item.type == "in" else "出库",
|
||||||
|
item.quantity,
|
||||||
|
item.remark or "",
|
||||||
|
item.created_at.strftime("%Y-%m-%d %H:%M:%S") if item.created_at else "",
|
||||||
|
])
|
||||||
|
|
||||||
|
col_widths = [8, 20, 10, 10, 30, 20]
|
||||||
|
for idx, width in enumerate(col_widths, 1):
|
||||||
|
ws.column_dimensions[openpyxl.utils.get_column_letter(idx)].width = width
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
wb.save(output)
|
||||||
|
output.seek(0)
|
||||||
|
|
||||||
|
filename = f"出入库记录_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||||
|
filename_encoded = quote(filename)
|
||||||
|
return StreamingResponse(
|
||||||
|
output,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename={filename_encoded}; filename*=UTF-8''{filename_encoded}"}
|
||||||
|
)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 库存 =====
|
||||||
|
class InventoryBase(BaseModel):
|
||||||
|
cInvCode: str
|
||||||
|
supplier: Optional[str] = None
|
||||||
|
casing_label_remark: Optional[str] = None
|
||||||
|
batch: Optional[str] = None
|
||||||
|
current_remaining: float = 0
|
||||||
|
storage_location: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryCreate(InventoryBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryUpdate(BaseModel):
|
||||||
|
cInvCode: Optional[str] = None
|
||||||
|
supplier: Optional[str] = None
|
||||||
|
casing_label_remark: Optional[str] = None
|
||||||
|
batch: Optional[str] = None
|
||||||
|
current_remaining: Optional[float] = None
|
||||||
|
storage_location: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryResponse(InventoryBase):
|
||||||
|
id: int
|
||||||
|
created_at: Optional[datetime] = None
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 出入库 =====
|
||||||
|
class StockOperation(BaseModel):
|
||||||
|
inventory_id: int
|
||||||
|
type: str # "in" or "out"
|
||||||
|
quantity: float
|
||||||
|
remark: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class TransactionLogResponse(BaseModel):
|
||||||
|
id: int
|
||||||
|
inventory_id: int
|
||||||
|
cInvCode: str
|
||||||
|
type: str
|
||||||
|
quantity: float
|
||||||
|
remark: Optional[str] = None
|
||||||
|
created_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>库存管理系统</title>
|
||||||
|
<link rel="stylesheet" href="https://unpkg.com/element-plus@2.4.4/dist/index.css">
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||||
|
background: #f0f2f5;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
#app { min-height: 100vh; }
|
||||||
|
|
||||||
|
.top-header {
|
||||||
|
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
|
||||||
|
padding: 0 30px;
|
||||||
|
height: 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
box-shadow: 0 2px 12px rgba(0,0,0,0.15);
|
||||||
|
}
|
||||||
|
.top-header .logo {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
color: #fff;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
}
|
||||||
|
.top-header .logo .icon-box {
|
||||||
|
width: 36px; height: 36px;
|
||||||
|
background: linear-gradient(135deg, #e94560, #c23152);
|
||||||
|
border-radius: 8px;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
.top-header .header-right {
|
||||||
|
display: flex; align-items: center; gap: 16px;
|
||||||
|
color: #b8c7d9; font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-container {
|
||||||
|
max-width: 1400px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-cards {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
.stat-card {
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
display: flex; align-items: center; gap: 16px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
|
||||||
|
transition: transform 0.2s, box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
.stat-card:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 6px 16px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
.stat-card .stat-icon {
|
||||||
|
width: 52px; height: 52px;
|
||||||
|
border-radius: 12px;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
.stat-card .stat-icon.blue { background: #e8f4fd; color: #1890ff; }
|
||||||
|
.stat-card .stat-icon.green { background: #e8f8e8; color: #52c41a; }
|
||||||
|
.stat-card .stat-icon.orange { background: #fff7e6; color: #fa8c16; }
|
||||||
|
.stat-card .stat-icon.red { background: #fff1f0; color: #f5222d; }
|
||||||
|
.stat-card .stat-info h3 { font-size: 28px; color: #1a1a2e; font-weight: 700; }
|
||||||
|
.stat-card .stat-info p { font-size: 13px; color: #8c8c8c; margin-top: 4px; }
|
||||||
|
|
||||||
|
.table-card {
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 24px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
|
||||||
|
}
|
||||||
|
.table-card .card-header {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
margin-bottom: 20px; flex-wrap: wrap; gap: 12px;
|
||||||
|
}
|
||||||
|
.table-card .card-header .left {
|
||||||
|
display: flex; align-items: center; gap: 12px;
|
||||||
|
}
|
||||||
|
.table-card .card-header .right {
|
||||||
|
display: flex; align-items: center; gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrap {
|
||||||
|
display: flex; justify-content: flex-end; margin-top: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-dialog .stock-info {
|
||||||
|
background: #f6f8fa;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.stock-dialog .stock-info .info-row {
|
||||||
|
display: flex; gap: 24px; font-size: 14px;
|
||||||
|
}
|
||||||
|
.stock-dialog .stock-info .info-row span { color: #8c8c8c; }
|
||||||
|
.stock-dialog .stock-info .info-row strong { color: #1a1a2e; }
|
||||||
|
|
||||||
|
.el-table th.el-table__cell {
|
||||||
|
background: #f8f9fc !important;
|
||||||
|
color: #1a1a2e;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.stat-cards { grid-template-columns: repeat(2, 1fr); }
|
||||||
|
.main-container { padding: 12px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app">
|
||||||
|
<div class="top-header">
|
||||||
|
<div class="logo">
|
||||||
|
<div class="icon-box">📦</div>
|
||||||
|
库存管理系统
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<span>{{ currentTime }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="main-container">
|
||||||
|
<div class="stat-cards">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-icon blue">📋</div>
|
||||||
|
<div class="stat-info"><h3>{{ stats.total }}</h3><p>产品总数</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-icon green">📊</div>
|
||||||
|
<div class="stat-info"><h3>{{ stats.totalRemaining }}</h3><p>库存总量</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-icon orange">🏭</div>
|
||||||
|
<div class="stat-info"><h3>{{ stats.supplierCount }}</h3><p>供应商数</p></div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-icon red">⚠️</div>
|
||||||
|
<div class="stat-info"><h3>{{ stats.lowStock }}</h3><p>库存预警 (≤0)</p></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-tabs v-model="activeTab" class="table-card">
|
||||||
|
<!-- 库存管理 -->
|
||||||
|
<el-tab-pane label="库存管理" name="inventory">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="left">
|
||||||
|
<el-input v-model="searchKeyword" placeholder="搜索产品编码/供应商/批次..." style="width: 300px" clearable @keyup.enter="loadInventory" @clear="loadInventory"></el-input>
|
||||||
|
<el-button type="primary" @click="loadInventory">查询</el-button>
|
||||||
|
</div>
|
||||||
|
<div class="right">
|
||||||
|
<el-button type="success" @click="showAddDialog">新增</el-button>
|
||||||
|
<el-button type="warning" @click="triggerImport">导入</el-button>
|
||||||
|
<el-button type="info" @click="exportInventory">导出</el-button>
|
||||||
|
<input ref="fileInput" type="file" accept=".xlsx,.xls" style="display:none" @change="handleImport" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-table :data="inventoryList" border stripe style="width: 100%" v-loading="loading">
|
||||||
|
<el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
|
||||||
|
<el-table-column prop="cInvCode" label="产品编码" width="160"></el-table-column>
|
||||||
|
<el-table-column prop="supplier" label="供应商" width="160"></el-table-column>
|
||||||
|
<el-table-column prop="casing_label_remark" label="现外壳&标签&备注" width="200"></el-table-column>
|
||||||
|
<el-table-column prop="batch" label="批次" width="140"></el-table-column>
|
||||||
|
<el-table-column prop="current_remaining" label="当前时间剩余" width="130" align="center">
|
||||||
|
<template #default="scope">
|
||||||
|
<el-tag :type="scope.row.current_remaining <= 0 ? 'danger' : scope.row.current_remaining <= 10 ? 'warning' : 'success'" effect="plain">
|
||||||
|
{{ scope.row.current_remaining }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="storage_location" label="存货地点" width="160"></el-table-column>
|
||||||
|
<el-table-column label="操作" width="260" align="center" fixed="right">
|
||||||
|
<template #default="scope">
|
||||||
|
<el-button size="small" type="success" @click="showStockDialog(scope.row, 'in')">入库</el-button>
|
||||||
|
<el-button size="small" type="warning" @click="showStockDialog(scope.row, 'out')">出库</el-button>
|
||||||
|
<el-button size="small" type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
|
||||||
|
<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrap">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="page"
|
||||||
|
v-model:page-size="pageSize"
|
||||||
|
:page-sizes="[20, 50, 100]"
|
||||||
|
:total="total"
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
@size-change="loadInventory"
|
||||||
|
@current-change="loadInventory"
|
||||||
|
></el-pagination>
|
||||||
|
</div>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<!-- 出入库记录 -->
|
||||||
|
<el-tab-pane label="出入库记录" name="logs">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="left">
|
||||||
|
<el-input v-model="logSearch" placeholder="搜索产品编码/备注..." style="width: 300px" clearable @keyup.enter="loadLogs" @clear="loadLogs"></el-input>
|
||||||
|
<el-button type="primary" @click="loadLogs">查询</el-button>
|
||||||
|
</div>
|
||||||
|
<div class="right">
|
||||||
|
<el-button type="danger" @click="clearLogs">清空记录</el-button>
|
||||||
|
<el-button type="info" @click="exportLogs">导出记录</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-table :data="logList" border stripe style="width: 100%" v-loading="logLoading">
|
||||||
|
<el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
|
||||||
|
<el-table-column prop="cInvCode" label="产品编码" width="160"></el-table-column>
|
||||||
|
<el-table-column prop="type" label="类型" width="100" align="center">
|
||||||
|
<template #default="scope">
|
||||||
|
<el-tag :type="scope.row.type === 'in' ? 'success' : 'danger'" effect="plain">
|
||||||
|
{{ scope.row.type === 'in' ? '📥 入库' : '📤 出库' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="quantity" label="数量" width="100" align="center"></el-table-column>
|
||||||
|
<el-table-column prop="remark" label="备注" min-width="200"></el-table-column>
|
||||||
|
<el-table-column prop="created_at" label="操作时间" width="180" align="center">
|
||||||
|
<template #default="scope">
|
||||||
|
{{ formatTime(scope.row.created_at) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrap">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="logPage"
|
||||||
|
v-model:page-size="logPageSize"
|
||||||
|
:page-sizes="[20, 50, 100]"
|
||||||
|
:total="logTotal"
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
@size-change="loadLogs"
|
||||||
|
@current-change="loadLogs"
|
||||||
|
></el-pagination>
|
||||||
|
</div>
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 新增/编辑对话框 -->
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEdit ? '编辑库存' : '新增库存'" width="560px" destroy-on-close>
|
||||||
|
<el-form :model="form" label-width="130px" ref="formRef">
|
||||||
|
<el-form-item label="产品编码" required>
|
||||||
|
<el-input v-model="form.cInvCode" placeholder="请输入产品编码" :disabled="isEdit"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="供应商">
|
||||||
|
<el-input v-model="form.supplier" placeholder="请输入供应商"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="现外壳&标签&备注">
|
||||||
|
<el-input v-model="form.casing_label_remark" type="textarea" :rows="2" placeholder="请输入外壳、标签、备注信息"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="批次">
|
||||||
|
<el-input v-model="form.batch" placeholder="请输入批次"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="当前时间剩余">
|
||||||
|
<el-input-number v-model="form.current_remaining" :min="0" :precision="2" style="width: 100%"></el-input-number>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="存货地点">
|
||||||
|
<el-input v-model="form.storage_location" placeholder="请输入存货地点"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- 出入库对话框 -->
|
||||||
|
<el-dialog v-model="stockDialogVisible" :title="stockType === 'in' ? '📥 入库操作' : '📤 出库操作'" width="480px" destroy-on-close class="stock-dialog">
|
||||||
|
<div class="stock-info">
|
||||||
|
<div class="info-row">
|
||||||
|
<div><span>产品编码:</span><strong>{{ stockItem ? stockItem.cInvCode : '' }}</strong></div>
|
||||||
|
<div><span>当前库存:</span><strong>{{ stockItem ? stockItem.current_remaining : 0 }}</strong></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<el-form :model="stockForm" label-width="80px">
|
||||||
|
<el-form-item label="数量">
|
||||||
|
<el-input-number v-model="stockForm.quantity" :min="0.01" :precision="2" style="width: 100%"></el-input-number>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="备注">
|
||||||
|
<el-input v-model="stockForm.remark" type="textarea" :rows="2" placeholder="请输入备注"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="stockDialogVisible = false">取消</el-button>
|
||||||
|
<el-button :type="stockType === 'in' ? 'success' : 'warning'" @click="handleStockSubmit" :loading="stockLoading">
|
||||||
|
确认{{ stockType === 'in' ? '入库' : '出库' }}
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="https://unpkg.com/vue@3.3.13/dist/vue.global.prod.js"></script>
|
||||||
|
<script src="https://unpkg.com/element-plus@2.4.4/dist/index.full.min.js"></script>
|
||||||
|
<script src="https://unpkg.com/@element-plus/icons-vue@2.3.1/dist/index.iife.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const { createApp, ref, reactive, onMounted, computed, nextTick } = Vue;
|
||||||
|
|
||||||
|
const app = createApp({
|
||||||
|
setup() {
|
||||||
|
const API = '/api';
|
||||||
|
const activeTab = ref('inventory');
|
||||||
|
const loading = ref(false);
|
||||||
|
const currentTime = ref('');
|
||||||
|
|
||||||
|
// 库存列表
|
||||||
|
const inventoryList = ref([]);
|
||||||
|
const page = ref(1);
|
||||||
|
const pageSize = ref(20);
|
||||||
|
const total = ref(0);
|
||||||
|
const searchKeyword = ref('');
|
||||||
|
|
||||||
|
// 出入库记录
|
||||||
|
const logList = ref([]);
|
||||||
|
const logPage = ref(1);
|
||||||
|
const logPageSize = ref(20);
|
||||||
|
const logTotal = ref(0);
|
||||||
|
const logSearch = ref('');
|
||||||
|
const logLoading = ref(false);
|
||||||
|
|
||||||
|
// 统计
|
||||||
|
const stats = reactive({ total: 0, totalRemaining: 0, supplierCount: 0, lowStock: 0 });
|
||||||
|
|
||||||
|
// 表单
|
||||||
|
const dialogVisible = ref(false);
|
||||||
|
const isEdit = ref(false);
|
||||||
|
const editId = ref(null);
|
||||||
|
const submitLoading = ref(false);
|
||||||
|
const formRef = ref(null);
|
||||||
|
const form = reactive({
|
||||||
|
cInvCode: '', supplier: '', casing_label_remark: '',
|
||||||
|
batch: '', current_remaining: 0, storage_location: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 出入库
|
||||||
|
const stockDialogVisible = ref(false);
|
||||||
|
const stockType = ref('in');
|
||||||
|
const stockItem = ref(null);
|
||||||
|
const stockLoading = ref(false);
|
||||||
|
const stockForm = reactive({ quantity: 1, remark: '' });
|
||||||
|
const fileInput = ref(null);
|
||||||
|
|
||||||
|
const updateTime = () => {
|
||||||
|
currentTime.value = new Date().toLocaleString('zh-CN', { hour12: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadInventory = async () => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ page: page.value, page_size: pageSize.value });
|
||||||
|
if (searchKeyword.value) params.set('search', searchKeyword.value);
|
||||||
|
const res = await fetch(API + '/inventory?' + params);
|
||||||
|
const data = await res.json();
|
||||||
|
inventoryList.value = data.items || [];
|
||||||
|
total.value = data.total || 0;
|
||||||
|
stats.total = data.total || 0;
|
||||||
|
stats.totalRemaining = (data.items || []).reduce((s, i) => s + (i.current_remaining || 0), 0);
|
||||||
|
const suppliers = new Set((data.items || []).map(i => i.supplier).filter(Boolean));
|
||||||
|
stats.supplierCount = suppliers.size;
|
||||||
|
stats.lowStock = (data.items || []).filter(i => i.current_remaining <= 0).length;
|
||||||
|
} catch (e) {
|
||||||
|
ElementPlus.ElMessage.error('加载库存失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadLogs = async () => {
|
||||||
|
logLoading.value = true;
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ page: logPage.value, page_size: logPageSize.value });
|
||||||
|
if (logSearch.value) params.set('search', logSearch.value);
|
||||||
|
const res = await fetch(API + '/stock/logs?' + params);
|
||||||
|
const data = await res.json();
|
||||||
|
logList.value = data.items || [];
|
||||||
|
logTotal.value = data.total || 0;
|
||||||
|
} catch (e) {
|
||||||
|
ElementPlus.ElMessage.error('加载记录失败');
|
||||||
|
} finally {
|
||||||
|
logLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const showAddDialog = () => {
|
||||||
|
isEdit.value = false;
|
||||||
|
editId.value = null;
|
||||||
|
Object.assign(form, { cInvCode: '', supplier: '', casing_label_remark: '', batch: '', current_remaining: 0, storage_location: '' });
|
||||||
|
dialogVisible.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const showEditDialog = (row) => {
|
||||||
|
isEdit.value = true;
|
||||||
|
editId.value = row.id;
|
||||||
|
Object.assign(form, {
|
||||||
|
cInvCode: row.cInvCode, supplier: row.supplier || '',
|
||||||
|
casing_label_remark: row.casing_label_remark || '', batch: row.batch || '',
|
||||||
|
current_remaining: row.current_remaining, storage_location: row.storage_location || '',
|
||||||
|
});
|
||||||
|
dialogVisible.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!form.cInvCode) {
|
||||||
|
ElementPlus.ElMessage.warning('请输入产品编码');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
submitLoading.value = true;
|
||||||
|
try {
|
||||||
|
const url = isEdit.value ? API + '/inventory/' + editId.value : API + '/inventory';
|
||||||
|
const method = isEdit.value ? 'PUT' : 'POST';
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: method,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(form),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json();
|
||||||
|
throw new Error(err.detail || '操作失败');
|
||||||
|
}
|
||||||
|
ElementPlus.ElMessage.success(isEdit.value ? '更新成功' : '新增成功');
|
||||||
|
dialogVisible.value = false;
|
||||||
|
loadInventory();
|
||||||
|
} catch (e) {
|
||||||
|
ElementPlus.ElMessage.error(e.message);
|
||||||
|
} finally {
|
||||||
|
submitLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (row) => {
|
||||||
|
try {
|
||||||
|
await ElementPlus.ElMessageBox.confirm(
|
||||||
|
'确定删除产品编码 "' + row.cInvCode + '" 的库存记录吗?',
|
||||||
|
'确认删除',
|
||||||
|
{ type: 'warning' }
|
||||||
|
);
|
||||||
|
const res = await fetch(API + '/inventory/' + row.id, { method: 'DELETE' });
|
||||||
|
if (!res.ok) throw new Error('删除失败');
|
||||||
|
ElementPlus.ElMessage.success('删除成功');
|
||||||
|
loadInventory();
|
||||||
|
} catch (e) {
|
||||||
|
if (e !== 'cancel') ElementPlus.ElMessage.error(e.message || '删除失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const showStockDialog = (row, type) => {
|
||||||
|
stockType.value = type;
|
||||||
|
stockItem.value = Object.assign({}, row);
|
||||||
|
stockForm.quantity = 1;
|
||||||
|
stockForm.remark = '';
|
||||||
|
stockDialogVisible.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStockSubmit = async () => {
|
||||||
|
if (stockForm.quantity <= 0) {
|
||||||
|
ElementPlus.ElMessage.warning('数量必须大于0');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stockLoading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch(API + '/stock/operation', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
inventory_id: stockItem.value.id,
|
||||||
|
type: stockType.value,
|
||||||
|
quantity: stockForm.quantity,
|
||||||
|
remark: stockForm.remark,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.detail || '操作失败');
|
||||||
|
ElementPlus.ElMessage.success(data.message);
|
||||||
|
stockDialogVisible.value = false;
|
||||||
|
loadInventory();
|
||||||
|
loadLogs();
|
||||||
|
} catch (e) {
|
||||||
|
ElementPlus.ElMessage.error(e.message);
|
||||||
|
} finally {
|
||||||
|
stockLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const exportInventory = () => { window.open(API + '/inventory/export', '_blank'); };
|
||||||
|
const exportLogs = () => { window.open(API + '/stock/export', '_blank'); };
|
||||||
|
|
||||||
|
const clearLogs = async () => {
|
||||||
|
try {
|
||||||
|
await ElementPlus.ElMessageBox.confirm(
|
||||||
|
'确定清空所有出入库记录吗?此操作不可恢复!',
|
||||||
|
'确认清空',
|
||||||
|
{ type: 'warning' }
|
||||||
|
);
|
||||||
|
const res = await fetch(API + '/stock/logs', { method: 'DELETE' });
|
||||||
|
if (!res.ok) throw new Error('清空失败');
|
||||||
|
const data = await res.json();
|
||||||
|
ElementPlus.ElMessage.success(data.message);
|
||||||
|
loadLogs();
|
||||||
|
} catch (e) {
|
||||||
|
if (e !== 'cancel') ElementPlus.ElMessage.error(e.message || '清空失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const triggerImport = () => { fileInput.value.click(); };
|
||||||
|
|
||||||
|
const handleImport = async (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
try {
|
||||||
|
const res = await fetch(API + '/inventory/import', { method: 'POST', body: formData });
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.detail || '导入失败');
|
||||||
|
ElementPlus.ElMessage.success(data.message);
|
||||||
|
loadInventory();
|
||||||
|
} catch (e) {
|
||||||
|
ElementPlus.ElMessage.error(e.message);
|
||||||
|
}
|
||||||
|
e.target.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatTime = (t) => {
|
||||||
|
if (!t) return '-';
|
||||||
|
return new Date(t).toLocaleString('zh-CN', { hour12: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadInventory();
|
||||||
|
loadLogs();
|
||||||
|
updateTime();
|
||||||
|
setInterval(updateTime, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
activeTab, loading, currentTime,
|
||||||
|
inventoryList, page, pageSize, total, searchKeyword,
|
||||||
|
logList, logPage, logPageSize, logTotal, logSearch, logLoading,
|
||||||
|
stats,
|
||||||
|
dialogVisible, isEdit, form, formRef, submitLoading,
|
||||||
|
stockDialogVisible, stockType, stockItem, stockForm, stockLoading,
|
||||||
|
fileInput,
|
||||||
|
loadInventory, loadLogs,
|
||||||
|
showAddDialog, showEditDialog, handleSubmit, handleDelete,
|
||||||
|
showStockDialog, handleStockSubmit,
|
||||||
|
exportInventory, exportLogs, clearLogs, triggerImport, handleImport, formatTime,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(ElementPlus);
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component);
|
||||||
|
}
|
||||||
|
app.mount('#app');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user