Compare commits
10 Commits
2.0权限管理
...
ee9b19e72a
| Author | SHA1 | Date | |
|---|---|---|---|
| ee9b19e72a | |||
| 3ffcd35093 | |||
| 8c635d6afe | |||
| 465452ef46 | |||
| d119bebe94 | |||
| baaaf7799a | |||
| c273f5a9d9 | |||
| 1a7c06f197 | |||
| 621431dcb9 | |||
| 6d044b234c |
@ -1,9 +1,9 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# --- 数据库 (保持不变) ---
|
||||
# --- 数据库 (已修改为自带 pgvector 的镜像) ---
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
image: pgvector/pgvector:pg15
|
||||
container_name: inventory_db_prod
|
||||
restart: always
|
||||
environment:
|
||||
@ -11,6 +11,7 @@ services:
|
||||
POSTGRES_PASSWORD: StrongPassword123!
|
||||
POSTGRES_DB: inventory_system
|
||||
volumes:
|
||||
# 数据卷保持不变,你的历史数据不会丢失!
|
||||
- ./pgdata_prod:/var/lib/postgresql/data
|
||||
|
||||
# --- 后端 (Flask) (保持不变) ---
|
||||
@ -29,7 +30,7 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
# --- 前端 (Nginx + Vue) (这是需要修改的部分) ---
|
||||
# --- 前端 (Nginx + Vue) (包含 HTTPS 配置) ---
|
||||
frontend:
|
||||
build:
|
||||
context: ./inventory-web
|
||||
|
||||
@ -2,7 +2,7 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
image: pgvector/pgvector:pg15 # 换成这个
|
||||
container_name: inventory_db
|
||||
restart: always
|
||||
environment:
|
||||
@ -10,7 +10,7 @@ services:
|
||||
POSTGRES_PASSWORD: 1234
|
||||
POSTGRES_DB: inventory_system
|
||||
volumes:
|
||||
- ./pgdata_docker:/var/lib/postgresql/data
|
||||
- ./pgdata_docker:/var/lib/postgresql/data # 这里保持不变,Docker会自动创建这个新文件夹
|
||||
ports:
|
||||
- "5435:5432"
|
||||
|
||||
|
||||
@ -90,6 +90,17 @@ def create_app():
|
||||
except ImportError as e:
|
||||
print(f"❌ 错误: Upload 模块导入失败: {e}")
|
||||
|
||||
# -----------------------------------------------------
|
||||
# 2.4 注册以图搜图模块 (Image Search)
|
||||
# -----------------------------------------------------
|
||||
try:
|
||||
from app.api.v1.common.image_search import image_search_bp
|
||||
app.register_blueprint(image_search_bp, url_prefix='/api/v1/common')
|
||||
app.register_blueprint(image_search_bp, url_prefix='/api/common', name='image_search_legacy')
|
||||
print("✅ Image Search 模块注册成功")
|
||||
except ImportError as e:
|
||||
print(f"❌ 错误: Image Search 模块导入失败: {e}")
|
||||
|
||||
# -----------------------------------------------------
|
||||
# 2.4 注册业务操作模块 (Transactions - 借还/维修/报废)
|
||||
# -----------------------------------------------------
|
||||
|
||||
163
inventory-backend/app/api/v1/common/image_search.py
Normal file
163
inventory-backend/app/api/v1/common/image_search.py
Normal file
@ -0,0 +1,163 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
以图搜图 API - CLIP Vision Embedding + pgvector 余弦距离检索
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import json
|
||||
from flask import Blueprint, request, jsonify
|
||||
from sqlalchemy import text
|
||||
from app.extensions import db
|
||||
from app.utils.ai_vision import load_clip_model, get_image_embedding
|
||||
|
||||
# 注册蓝图
|
||||
image_search_bp = Blueprint('image_search', __name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# POST /api/v1/common/image-search
|
||||
# 以图搜图:上传图片 → CLIP embedding → pgvector 余弦相似度检索
|
||||
# ============================================================================
|
||||
|
||||
@image_search_bp.route('/image-search', methods=['POST'])
|
||||
def image_search():
|
||||
# ---------------------------------------------------------
|
||||
# 1. 检查文件
|
||||
# ---------------------------------------------------------
|
||||
if 'file' not in request.files:
|
||||
return jsonify({"code": 400, "msg": "未找到图片文件"}), 400
|
||||
|
||||
file = request.files['file']
|
||||
if file.filename == '':
|
||||
return jsonify({"code": 400, "msg": "未选择文件"}), 400
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 2. 安全保存临时文件
|
||||
# ---------------------------------------------------------
|
||||
ext = file.filename.rsplit('.', 1)[-1].lower()
|
||||
if ext not in {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}:
|
||||
return jsonify({"code": 400, "msg": "不支持的图片格式"}), 400
|
||||
|
||||
tmp_filename = f"{uuid.uuid4().hex}.{ext}"
|
||||
tmp_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'uploads')
|
||||
os.makedirs(tmp_dir, exist_ok=True)
|
||||
tmp_path = os.path.join(tmp_dir, tmp_filename)
|
||||
|
||||
try:
|
||||
file.save(tmp_path)
|
||||
print(f"💾 [ImageSearch] 临时文件已保存: {tmp_path}")
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 3. 提取 CLIP embedding
|
||||
# ---------------------------------------------------------
|
||||
load_clip_model()
|
||||
embedding = get_image_embedding(tmp_path)
|
||||
print(f"✅ [ImageSearch] Embedding 提取成功,维度: {len(embedding)}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ [ImageSearch] 图像处理失败: {e}")
|
||||
return jsonify({"code": 500, "msg": f"图像处理失败: {str(e)}"}), 500
|
||||
|
||||
finally:
|
||||
# ---------------------------------------------------------
|
||||
# 4. 无论成功与否,都删除临时文件
|
||||
# ---------------------------------------------------------
|
||||
if os.path.exists(tmp_path):
|
||||
try:
|
||||
os.remove(tmp_path)
|
||||
print(f"🗑️ [ImageSearch] 临时文件已清理: {tmp_path}")
|
||||
except Exception as e:
|
||||
print(f"⚠️ [ImageSearch] 临时文件删除失败: {e}")
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 5. pgvector 余弦相似度检索(跨表联合检索)
|
||||
# ---------------------------------------------------------
|
||||
try:
|
||||
query_vector_str = '[' + ','.join(str(v) for v in embedding) + ']'
|
||||
|
||||
sql = text("""
|
||||
SELECT id, name, spec_model, image_url,
|
||||
(1 - (vec <=> :query_vector)) AS similarity
|
||||
FROM (
|
||||
-- 1. 基础物料表
|
||||
SELECT id, name, spec_model, product_image AS image_url, img_embedding AS vec
|
||||
FROM material_base
|
||||
WHERE img_embedding IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- 2. 采购入库表 (通过 base_id 关联拿真实物料信息)
|
||||
SELECT mb.id, mb.name, mb.spec_model, sb.arrival_photo AS image_url, sb.arrival_image_embedding AS vec
|
||||
FROM stock_buy sb
|
||||
JOIN material_base mb ON sb.base_id = mb.id
|
||||
WHERE sb.arrival_image_embedding IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- 3. 半成品入库表 (通过 base_id 关联拿真实物料信息)
|
||||
SELECT mb.id, mb.name, mb.spec_model, ss.arrival_photo AS image_url, ss.arrival_image_embedding AS vec
|
||||
FROM stock_semi ss
|
||||
JOIN material_base mb ON ss.base_id = mb.id
|
||||
WHERE ss.arrival_image_embedding IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- 4. 成品入库表 (通过 base_id 关联拿真实物料信息)
|
||||
SELECT mb.id, mb.name, mb.spec_model, sp.product_photo AS image_url, sp.arrival_image_embedding AS vec
|
||||
FROM stock_product sp
|
||||
JOIN material_base mb ON sp.base_id = mb.id
|
||||
WHERE sp.arrival_image_embedding IS NOT NULL
|
||||
) AS combined
|
||||
|
||||
-- 核心:计算余弦距离并排序,取最接近的前 50 个!
|
||||
ORDER BY vec <=> :query_vector LIMIT 50
|
||||
""")
|
||||
|
||||
# 执行查询
|
||||
records = db.session.execute(sql, {"query_vector": query_vector_str}).fetchall()
|
||||
|
||||
results = []
|
||||
seen_product_ids = set() # 【新增】用来记录已经添加过的物料 ID
|
||||
|
||||
for row in records:
|
||||
# 【新增】如果这个物料已经在这个列表里了,直接跳过它
|
||||
if row.id in seen_product_ids:
|
||||
continue
|
||||
|
||||
# 记录这个物料 ID,保证下次不会再重复添加
|
||||
seen_product_ids.add(row.id)
|
||||
|
||||
# 1. 提取原始 URL
|
||||
raw_url = row.image_url
|
||||
clean_url = ""
|
||||
|
||||
if raw_url:
|
||||
if raw_url.startswith('[') and raw_url.endswith(']'):
|
||||
import json
|
||||
try:
|
||||
url_list = json.loads(raw_url)
|
||||
clean_url = url_list[0] if url_list else ""
|
||||
except:
|
||||
clean_url = raw_url
|
||||
else:
|
||||
clean_url = raw_url
|
||||
|
||||
# 2. 组装返回结果
|
||||
results.append({
|
||||
"product_id": row.id,
|
||||
"product_name": row.name,
|
||||
"spec_model": row.spec_model,
|
||||
"image_url": clean_url,
|
||||
"similarity": round(float(row.similarity), 4)
|
||||
})
|
||||
|
||||
# 修改后:只要凑够了 10 个完全不同的物料,就立刻结束循环
|
||||
if len(results) >= 10:
|
||||
break
|
||||
|
||||
return jsonify({"code": 200, "data": results})
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ [ImageSearch] 数据库检索失败: {e}")
|
||||
return jsonify({"code": 500, "msg": f"检索失败: {str(e)}"}), 500
|
||||
@ -140,24 +140,35 @@ class BomService:
|
||||
)
|
||||
)
|
||||
|
||||
# ★ 调试:打印 SQL 语句
|
||||
logger.info(f"[BOM List] keyword={keyword!r} → SQL:\n{str(query_base.statement.compile(compile_kwargs={'literal_binds': True}))}")
|
||||
|
||||
# 获取符合条件的唯一组合
|
||||
target_pairs = query_base.distinct().all()
|
||||
|
||||
if not target_pairs:
|
||||
return []
|
||||
|
||||
# 2. 聚合查询详情
|
||||
# 2. 聚合查询详情(★ 修复:使用 string_agg 聚合子件名称,解决步骤3过滤遗漏问题)
|
||||
results = []
|
||||
for bom_no, version in target_pairs:
|
||||
# ★ 使用子件的别名查询子件信息,聚合所有子件的名称和规格
|
||||
child_alias = db.aliased(MaterialBase)
|
||||
summary = db.session.query(
|
||||
BomTable.parent_id,
|
||||
MaterialBase.name.label('parent_name'),
|
||||
MaterialBase.spec_model.label('parent_spec'),
|
||||
MaterialBase.category.label('parent_category'),
|
||||
BomTable.is_enabled,
|
||||
func.count(BomTable.child_id).label('child_count')
|
||||
func.count(BomTable.child_id).label('child_count'),
|
||||
# ★ 聚合子件名称为逗号分隔字符串(用于步骤3关键词过滤)
|
||||
func.string_agg(child_alias.name, ', ').label('child_names'),
|
||||
# ★ 同时聚合子件规格(备用)
|
||||
func.string_agg(child_alias.spec_model, ', ').label('child_specs')
|
||||
).join(
|
||||
MaterialBase, BomTable.parent_id == MaterialBase.id
|
||||
).outerjoin(
|
||||
child_alias, BomTable.child_id == child_alias.id
|
||||
).filter(
|
||||
BomTable.bom_no == bom_no,
|
||||
BomTable.version == version
|
||||
@ -174,7 +185,9 @@ class BomService:
|
||||
'parent_spec': summary.parent_spec or '',
|
||||
'parent_category': summary.parent_category or '',
|
||||
'is_enabled': summary.is_enabled,
|
||||
'child_count': summary.child_count
|
||||
'child_count': summary.child_count,
|
||||
'child_names': summary.child_names or '', # ★ 新增:子件名称聚合
|
||||
'child_specs': summary.child_specs or '' # ★ 新增:子件规格聚合
|
||||
})
|
||||
|
||||
results.sort(key=lambda x: (x['bom_no'], x['version']), reverse=True)
|
||||
@ -188,6 +201,8 @@ class BomService:
|
||||
or kw in (r.get('parent_spec') or '').lower()
|
||||
or kw in (r.get('bom_no') or '').lower()
|
||||
or kw in (r.get('parent_category') or '').lower()
|
||||
or kw in (r.get('child_names') or '').lower() # ★ 修复:加入子件名称过滤
|
||||
or kw in (r.get('child_specs') or '').lower() # ★ 同步加入子件规格过滤
|
||||
]
|
||||
|
||||
# 按 parent_category 分组
|
||||
|
||||
@ -11,6 +11,8 @@ Dify 智能客服权限服务层
|
||||
- 跨模块越权查询:直接阻断,返回角色专属的错误信息给大模型
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from flask import g, current_app
|
||||
from flask_jwt_extended import decode_token
|
||||
from app.models.system import SysRolePermission
|
||||
@ -185,7 +187,7 @@ class DifyPermissionService:
|
||||
返回:
|
||||
{
|
||||
'blocked': bool, # 是否被拦截
|
||||
'message': str | None, # AI 应返回给用户的错误信息(如果有)
|
||||
'message': Optional[str], # AI 应返回给用户的错误信息(如果有)
|
||||
}
|
||||
"""
|
||||
if DifyPermissionService.is_super_admin(role):
|
||||
|
||||
@ -20,6 +20,8 @@ import logging
|
||||
from threading import Thread
|
||||
from datetime import datetime
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
|
||||
@ -346,7 +348,7 @@ def get_task_status(task_id: str) -> dict:
|
||||
# 获取导出文件路径(供下载接口调用)
|
||||
# =============================================================================
|
||||
|
||||
def get_export_filepath(task_id: str) -> str | None:
|
||||
def get_export_filepath(task_id: str) -> Optional[str]:
|
||||
"""
|
||||
根据 task_id 返回已生成文件的完整路径。
|
||||
未完成或不存在返回 None。
|
||||
|
||||
@ -1048,14 +1048,15 @@ class MaterialBaseService:
|
||||
@staticmethod
|
||||
def get_latest_specs():
|
||||
"""
|
||||
获取所有规格型号的最大连号,按连续区间分组返回
|
||||
获取所有规格型号的分组统计,按规则聚合后返回
|
||||
- 前缀统一大写处理
|
||||
- 只有数字完全连续(N, N+1, N+2...)才认定为同一组
|
||||
- 数字不连续时断开,形成新组
|
||||
- 按每组数量降序排列
|
||||
- 返回每个连续区间的最大值
|
||||
- 匹配模式:(前缀)(单数字二级分类位)(纯数字部分),如 OPT12046 -> OPT, 1, 2046
|
||||
- OPT 系列:使用 前缀+二级分类位 作为分组 Key,如 OPT1, OPT2
|
||||
- 其他前缀:直接使用前缀作为分组 Key
|
||||
- 返回每个分组的数量、最大号、完整规格名
|
||||
"""
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
# 1. 查询所有不为空的规格型号
|
||||
specs = MaterialBase.query.filter(
|
||||
@ -1063,8 +1064,8 @@ class MaterialBaseService:
|
||||
MaterialBase.spec_model != ''
|
||||
).all()
|
||||
|
||||
# 2. 解析并收集所有有效的 (prefix, num, original_spec)
|
||||
parsed = []
|
||||
# 2. 按分组收集所有数字
|
||||
groups = defaultdict(list)
|
||||
|
||||
for material in specs:
|
||||
spec = material.spec_model
|
||||
@ -1072,72 +1073,31 @@ class MaterialBaseService:
|
||||
continue
|
||||
|
||||
base_spec = spec.split('/')[0]
|
||||
|
||||
match = re.match(r'^([A-Za-z]+)(\d+)$', base_spec)
|
||||
match = re.match(r'^([A-Za-z]+)(\d)(\d+)$', base_spec)
|
||||
if not match:
|
||||
continue
|
||||
|
||||
prefix, num_str = match.groups()
|
||||
prefix, sub_cat, num_str = match.groups()
|
||||
prefix = prefix.upper()
|
||||
num = int(num_str)
|
||||
|
||||
parsed.append((prefix, num, spec))
|
||||
# OPT 系列使用 前缀+单数字二级分类 作为 Key
|
||||
key = f"{prefix}{sub_cat}" if prefix == 'OPT' else prefix
|
||||
groups[key].append((num, spec))
|
||||
|
||||
# 3. 先按 prefix 升序,再按 num 升序排序
|
||||
parsed.sort(key=lambda x: (x[0], x[1]))
|
||||
|
||||
# 4. 遍历切分连续区间
|
||||
# 核心逻辑:当 current_num != prev_num + 1 时,断开形成新组
|
||||
intervals = []
|
||||
current_prefix = None
|
||||
current_start = None
|
||||
current_end = None
|
||||
current_last_spec = None
|
||||
|
||||
for prefix, num, spec in parsed:
|
||||
if current_prefix is None:
|
||||
current_prefix = prefix
|
||||
current_start = num
|
||||
current_end = num
|
||||
current_last_spec = spec
|
||||
elif prefix == current_prefix and num == current_end + 1:
|
||||
current_end = num
|
||||
current_last_spec = spec
|
||||
else:
|
||||
intervals.append({
|
||||
'prefix': current_prefix,
|
||||
'start': current_start,
|
||||
'end': current_end,
|
||||
'count': current_end - current_start + 1,
|
||||
'latest': current_last_spec
|
||||
})
|
||||
current_prefix = prefix
|
||||
current_start = num
|
||||
current_end = num
|
||||
current_last_spec = spec
|
||||
|
||||
if current_prefix is not None:
|
||||
intervals.append({
|
||||
'prefix': current_prefix,
|
||||
'start': current_start,
|
||||
'end': current_end,
|
||||
'count': current_end - current_start + 1,
|
||||
'latest': current_last_spec
|
||||
})
|
||||
|
||||
# 5. 按每组数量降序排列,再按前缀升序
|
||||
intervals.sort(key=lambda x: (-x['count'], x['prefix']))
|
||||
|
||||
# 6. 构建返回结果
|
||||
# 3. 生成展示用的统计数据
|
||||
result = []
|
||||
for item in intervals:
|
||||
prefix = item['prefix']
|
||||
start = item['start']
|
||||
end = item['end']
|
||||
for key, items in groups.items():
|
||||
sorted_items = sorted(items, key=lambda x: x[0])
|
||||
max_num, max_spec = sorted_items[-1]
|
||||
result.append({
|
||||
"group": f"{prefix}({start}-{end})",
|
||||
"count": item['count'],
|
||||
"latest": item['latest']
|
||||
'group': key,
|
||||
'count': len(sorted_items),
|
||||
'latest': max_spec,
|
||||
'max_num': max_num
|
||||
})
|
||||
|
||||
# 4. 按数量降序,再按分组名升序排列
|
||||
result.sort(key=lambda x: (-x['count'], x['group']))
|
||||
|
||||
return result
|
||||
132
inventory-backend/app/utils/ai_vision.py
Normal file
132
inventory-backend/app/utils/ai_vision.py
Normal file
@ -0,0 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
AI Vision 模块 - CLIP Vision Encoder ONNX 推理
|
||||
"""
|
||||
|
||||
import os
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import onnxruntime as ort
|
||||
|
||||
# ============================================================================
|
||||
# 全局模型单例(项目启动时加载一次)
|
||||
# ============================================================================
|
||||
|
||||
MODEL_PATH = os.path.join(os.path.dirname(__file__), '..', '..', 'models', 'clip_vision.onnx')
|
||||
|
||||
# 加载选项:CPU 推理,禁用依赖库的启动开销
|
||||
_session_options = ort.SessionOptions()
|
||||
_session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
||||
|
||||
ort_session: ort.InferenceSession = None
|
||||
|
||||
|
||||
def load_clip_model():
|
||||
"""启动时调用:全局加载 CLIP Vision 模型"""
|
||||
global ort_session
|
||||
if ort_session is not None:
|
||||
return ort_session
|
||||
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"CLIP Vision 模型未找到: {MODEL_PATH}")
|
||||
|
||||
ort_session = ort.InferenceSession(MODEL_PATH, sess_options=_session_options, providers=['CPUExecutionProvider'])
|
||||
print(f"✅ [AI Vision] CLIP 模型加载成功: {MODEL_PATH}")
|
||||
return ort_session
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# CLIP 预处理常量
|
||||
# ============================================================================
|
||||
|
||||
# ImageNet 标准归一化(CLIP 官方)
|
||||
IMAGENET_MEAN = [0.485, 0.456, 0.406]
|
||||
IMAGENET_STD = [0.229, 0.224, 0.225]
|
||||
|
||||
# 模型输入尺寸
|
||||
INPUT_SIZE = 224
|
||||
|
||||
|
||||
def _center_crop_and_resize(image: Image.Image) -> Image.Image:
|
||||
"""
|
||||
CLIP 官方预处理:中心裁剪抗干扰
|
||||
- 将图片最短边缩放到 224
|
||||
- 从正中间切取 224x224 区域
|
||||
"""
|
||||
w, h = image.size
|
||||
|
||||
# 计算缩放后的目标尺寸
|
||||
if w < h:
|
||||
new_w = INPUT_SIZE
|
||||
new_h = int(h * INPUT_SIZE / w)
|
||||
else:
|
||||
new_h = INPUT_SIZE
|
||||
new_w = int(w * INPUT_SIZE / h)
|
||||
|
||||
# 缩放
|
||||
image = image.resize((new_w, new_h), Image.BILINEAR)
|
||||
|
||||
# 中心裁剪
|
||||
left = (new_w - INPUT_SIZE) // 2
|
||||
top = (new_h - INPUT_SIZE) // 2
|
||||
right = left + INPUT_SIZE
|
||||
bottom = top + INPUT_SIZE
|
||||
|
||||
return image.crop((left, top, right, bottom))
|
||||
|
||||
|
||||
def _normalize(image_np: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
对 224x224x3 图像进行 CLIP 标准归一化
|
||||
image_np: shape (H, W, C), dtype uint8, 值域 [0, 255]
|
||||
返回: shape (C, H, W), dtype float32, 值域 [0, 1]
|
||||
"""
|
||||
# HWC -> CHW
|
||||
image_np = image_np.transpose(2, 0, 1).astype(np.float32) / 255.0
|
||||
|
||||
# 归一化
|
||||
for i, (mean, std) in enumerate(zip(IMAGENET_MEAN, IMAGENET_STD)):
|
||||
image_np[i] = (image_np[i] - mean) / std
|
||||
|
||||
return image_np
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# 主函数:提取图像 embedding
|
||||
# ============================================================================
|
||||
|
||||
def get_image_embedding(image_path: str) -> list:
|
||||
"""
|
||||
提取图像的 512 维 CLIP embedding 向量
|
||||
|
||||
参数:
|
||||
image_path: 图像文件路径
|
||||
|
||||
返回:
|
||||
list: 512 维浮点向量
|
||||
"""
|
||||
if ort_session is None:
|
||||
load_clip_model()
|
||||
|
||||
# 1. 图片预处理
|
||||
image = Image.open(image_path).convert('RGB')
|
||||
image = _center_crop_and_resize(image)
|
||||
input_data = _normalize(np.array(image))
|
||||
input_data = np.expand_dims(input_data, axis=0) # [1, 3, 224, 224]
|
||||
|
||||
# 2. 构造占位符输入 (关键修复)
|
||||
dummy_ids = np.zeros((1, 77), dtype=np.int64)
|
||||
dummy_mask = np.zeros((1, 77), dtype=np.int64)
|
||||
|
||||
# 3. 传入模型进行推理
|
||||
# 注意: 模型输入名在你的模型里必须叫 'pixel_values', 'input_ids', 'attention_mask'
|
||||
# 如果报错找不到输入名,请打印 ort_session.get_inputs()[0].name 确认
|
||||
outputs = ort_session.run(
|
||||
['image_embeds'],
|
||||
{
|
||||
'input_ids': dummy_ids,
|
||||
'pixel_values': input_data.astype(np.float32),
|
||||
'attention_mask': dummy_mask
|
||||
}
|
||||
)
|
||||
return outputs[0][0].tolist()
|
||||
@ -10,6 +10,10 @@ flask-cors==4.0.0
|
||||
redis==5.0.1
|
||||
# 图片处理核心库
|
||||
Pillow>=10.0.0
|
||||
# ONNX 模型本地 CPU 推理
|
||||
onnxruntime>=1.16.0
|
||||
# 数值计算(ONNX 推理依赖)
|
||||
numpy>=1.24.0
|
||||
# [旧] 条形码生成库 (建议保留,防止旧代码报错)
|
||||
python-barcode>=0.14.0
|
||||
# [新增] 二维码生成库 (标签打印必需,包含PIL支持)
|
||||
@ -22,3 +26,5 @@ openpyxl>=3.1.2
|
||||
APScheduler==3.10.4
|
||||
# [新增] 时区处理 (APScheduler 需要)
|
||||
pytz
|
||||
# [新增] 进度条库 (脚本和任务所需)
|
||||
tqdm>=4.66.0
|
||||
231
inventory-backend/scripts/init_all_vectors.py
Normal file
231
inventory-backend/scripts/init_all_vectors.py
Normal file
@ -0,0 +1,231 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
全量历史图片向量初始化脚本
|
||||
|
||||
功能:遍历配置表中所有历史图片字段,批量提取 CLIP 512 维向量并存回数据库。
|
||||
用法:python scripts/init_all_vectors.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
# 将项目根目录加入 Python 路径
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from tqdm import tqdm
|
||||
from sqlalchemy import text
|
||||
|
||||
# Flask 应用环境
|
||||
from app import create_app
|
||||
from app.extensions import db
|
||||
from app.utils.ai_vision import get_image_embedding, load_clip_model
|
||||
|
||||
# ============================================================================
|
||||
# 业务配置:表 → 图片字段 → 向量字段 映射 (已全面修复)
|
||||
# ============================================================================
|
||||
TARGET_TABLES = [
|
||||
# 1. 基础物料
|
||||
{"table": "material_base", "img_col": "product_image", "vec_col": "img_embedding"},
|
||||
|
||||
# 2. 采购入库
|
||||
{"table": "stock_buy", "img_col": "arrival_photo", "vec_col": "arrival_image_embedding"},
|
||||
{"table": "stock_buy", "img_col": "inspection_report", "vec_col": "qc_report_image_embedding"}, # 已修复: qc_report -> inspection_report
|
||||
|
||||
# 3. 半成品入库 (新增)
|
||||
{"table": "stock_semi", "img_col": "arrival_photo", "vec_col": "arrival_image_embedding"},
|
||||
{"table": "stock_semi", "img_col": "quality_report_link", "vec_col": "qc_report_image_embedding"},
|
||||
|
||||
# 4. 成品入库 (新增)
|
||||
{"table": "stock_product", "img_col": "product_photo", "vec_col": "arrival_image_embedding"},
|
||||
{"table": "stock_product", "img_col": "quality_report_link", "vec_col": "qc_report_image_embedding"}
|
||||
|
||||
# 注意:成品入库表还有一个 inspection_report_link,但由于数据库中成品表目前只加了两个向量字段,
|
||||
# 暂不将该字段加入遍历,以免覆盖 quality_report_link 的特征。
|
||||
]
|
||||
|
||||
# 物理图片根目录(相对于 app 目录的相对路径 ../uploads/)
|
||||
APP_DIR = os.path.join(os.path.dirname(__file__), '..', 'app')
|
||||
UPLOADS_ROOT = os.path.abspath(os.path.join(APP_DIR, '..', 'uploads'))
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# 核心工具函数
|
||||
# ============================================================================
|
||||
|
||||
def parse_img_field(raw_value: str) -> List[str]:
|
||||
"""
|
||||
健壮解析图片字段,支持以下格式:
|
||||
- JSON 数组字符串: ["a.jpg", "b.jpg"]
|
||||
- 纯字符串单图片: "a.jpg"
|
||||
- 带 /api/v1/files/ 前缀: ["/api/v1/files/a.jpg"]
|
||||
返回: 提取出的文件名列表
|
||||
"""
|
||||
if not raw_value or (isinstance(raw_value, str) and not raw_value.strip()):
|
||||
return []
|
||||
|
||||
try:
|
||||
# 先尝试按 JSON 解析(处理 JSON 数组字符串)
|
||||
parsed = json.loads(raw_value)
|
||||
if isinstance(parsed, list):
|
||||
items = parsed
|
||||
else:
|
||||
items = [parsed]
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
# JSON 解析失败,说明是纯字符串,直接按单图片处理
|
||||
items = [raw_value.strip()]
|
||||
|
||||
filenames = []
|
||||
for item in items:
|
||||
if not item or not isinstance(item, str):
|
||||
continue
|
||||
item = item.strip()
|
||||
if not item:
|
||||
continue
|
||||
# 去掉可能的 /api/v1/files/ 前缀
|
||||
filename = os.path.basename(item)
|
||||
filenames.append(filename)
|
||||
|
||||
return filenames
|
||||
|
||||
|
||||
def build_local_path(filename: str) -> str:
|
||||
"""
|
||||
将文件名拼装成本地绝对路径
|
||||
"""
|
||||
return os.path.join(UPLOADS_ROOT, filename)
|
||||
|
||||
|
||||
def extract_first_valid_vector(raw_img_field: str, table_name: str, img_col: str) -> Optional[str]:
|
||||
"""
|
||||
读取图片字段,从第一条有效图片提取向量,返回写入 DB 的 JSON 字符串。
|
||||
如果所有图片均失败,返回 None。
|
||||
"""
|
||||
filenames = parse_img_field(raw_img_field)
|
||||
if not filenames:
|
||||
return None
|
||||
|
||||
for filename in filenames:
|
||||
local_path = build_local_path(filename)
|
||||
|
||||
if not os.path.exists(local_path):
|
||||
print(f"\033[91m[WARN] {table_name}.{img_col} | 文件不存在: {local_path}\033[0m")
|
||||
continue
|
||||
|
||||
try:
|
||||
vec = get_image_embedding(local_path)
|
||||
if vec is not None:
|
||||
return json.dumps(vec)
|
||||
except Exception as e:
|
||||
print(f"\033[91m[WARN] {table_name}.{img_col} | 推理异常 [{filename}]: {type(e).__name__}: {e}\033[0m")
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# 主入口
|
||||
# ============================================================================
|
||||
|
||||
def main():
|
||||
start = datetime.now()
|
||||
total_success = 0
|
||||
total_skip = 0
|
||||
|
||||
print("=" * 60)
|
||||
print("📦 全量历史图片向量初始化")
|
||||
print("=" * 60)
|
||||
print(f"图片目录: {UPLOADS_ROOT}")
|
||||
print(f"待处理表数: {len(TARGET_TABLES)}")
|
||||
print()
|
||||
|
||||
# 1. 初始化 Flask 应用上下文(加载 CLIP 模型)
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
load_clip_model()
|
||||
print("✅ CLIP 模型加载完成")
|
||||
print()
|
||||
|
||||
# 2. 遍历目标表
|
||||
for config in TARGET_TABLES:
|
||||
table_name = config["table"]
|
||||
img_col = config["img_col"]
|
||||
vec_col = config["vec_col"]
|
||||
|
||||
print(f"正在处理表: {table_name}, 字段: {img_col}")
|
||||
|
||||
# 3. 查询待清洗记录(只选未处理过的)
|
||||
sql = text(f"""
|
||||
SELECT id, {img_col}
|
||||
FROM {table_name}
|
||||
WHERE {img_col} IS NOT NULL
|
||||
AND {img_col} != '[]'
|
||||
AND ({vec_col} IS NULL)
|
||||
""")
|
||||
rows = db.session.execute(sql).fetchall()
|
||||
|
||||
if not rows:
|
||||
print(f"[{table_name}/{img_col}] ⏭ 无待处理记录")
|
||||
continue
|
||||
|
||||
print(f"\n[{table_name}/{img_col}] 📋 待处理: {len(rows)} 条")
|
||||
|
||||
# 4. 逐条处理
|
||||
processed = 0
|
||||
success_count = 0
|
||||
|
||||
for row in tqdm(rows, desc=f"{table_name}/{img_col}", unit="条"):
|
||||
record_id = row[0]
|
||||
raw_img = row[1]
|
||||
|
||||
try:
|
||||
vec_json = extract_first_valid_vector(raw_img, table_name, img_col)
|
||||
if vec_json is None:
|
||||
total_skip += 1
|
||||
continue
|
||||
|
||||
# 更新向量字段
|
||||
update_sql = text(f"""
|
||||
UPDATE {table_name} SET {vec_col} = :vec_str WHERE id = :id
|
||||
""")
|
||||
db.session.execute(update_sql, {"vec_str": vec_json, "id": record_id})
|
||||
success_count += 1
|
||||
|
||||
# 每 50 条提交一次
|
||||
if processed > 0 and processed % 50 == 0:
|
||||
db.session.commit()
|
||||
print(f"\n ✅ 已提交 {processed} 条")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n\033[91m[WARN] {table_name}/{img_col} | ID={record_id} 处理异常: {type(e).__name__}: {e}\033[0m")
|
||||
# 关键:任何异常都不中断,只 continue 下一条
|
||||
db.session.rollback()
|
||||
continue
|
||||
finally:
|
||||
processed += 1
|
||||
|
||||
# 循环结束后补一次 commit(处理未凑满50条的剩余数据)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
total_success += success_count
|
||||
print(f"[{table_name}/{img_col}] ✅ 完成,成功 {success_count} 条 / 跳过 {len(rows) - success_count} 条")
|
||||
|
||||
# 5. 汇总报告
|
||||
elapsed = (datetime.now() - start).total_seconds()
|
||||
print()
|
||||
print("=" * 60)
|
||||
print(f"🏁 全部完成!总计耗时 {elapsed:.1f} 秒")
|
||||
print(f" ✅ 成功写入向量: {total_success} 条")
|
||||
print(f" ⏭ 无有效图片(跳过): {total_skip} 条")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,3 +1,6 @@
|
||||
# .env.development
|
||||
# 注意:这里必须写你电脑的局域网 IP
|
||||
VITE_API_BASE_URL=http://172.16.0.95:8000/api/v1
|
||||
# 1. 本地局域网测试用(比如让平板连 192.168.9.33)
|
||||
#VITE_API_BASE_URL=http://192.168.9.33:8000/api/v1
|
||||
|
||||
# 2. 服务器环境用(推送到服务器前,把上面那行注释掉,这行解开)
|
||||
VITE_API_BASE_URL=http://172.16.0.95:8000/api/v1
|
||||
@ -10,25 +10,64 @@
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
<script>
|
||||
// 获取当前用户的登录凭证 (Token)
|
||||
var currentToken = localStorage.getItem('access_token') || localStorage.getItem('token') || '';
|
||||
window.initDifyChatbot = function() {
|
||||
// 【关键】增加保护检查:确保 DOM 已经就绪
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', performInit);
|
||||
} else {
|
||||
performInit();
|
||||
}
|
||||
};
|
||||
|
||||
window.difyChatbotConfig = {
|
||||
token: '6T0eTgukUEqzK0iW',
|
||||
baseUrl: 'http://172.16.0.198:8080',
|
||||
inputs: {
|
||||
"user_token": currentToken
|
||||
},
|
||||
systemVariables: {},
|
||||
userVariables: {},
|
||||
function performInit() {
|
||||
var currentToken = localStorage.getItem('access_token') || localStorage.getItem('token') || '';
|
||||
var username = localStorage.getItem("username") || '';
|
||||
|
||||
if (!currentToken) {
|
||||
console.log('未检测到 Token,暂不加载 Dify');
|
||||
return;
|
||||
}
|
||||
|
||||
// 彻底清理浏览器内存中残留的 Dify 全局对象
|
||||
window.difyChatbot = undefined;
|
||||
delete window.difyChatbot;
|
||||
|
||||
// 清理旧的 DOM 节点
|
||||
var oldScript = document.getElementById('6T0eTgukUEqzK0iW');
|
||||
if (oldScript) oldScript.remove();
|
||||
document.querySelectorAll('[id^="dify-chatbot-"]').forEach(function(el) { el.remove(); });
|
||||
|
||||
// 动态化 user_id,打破 Dify 会话锁定机制
|
||||
var dynamicUserId = username + '_' + currentToken.slice(-8);
|
||||
|
||||
window.difyChatbotConfig = {
|
||||
token: '6T0eTgukUEqzK0iW',
|
||||
baseUrl: 'http://172.16.0.198:8080',
|
||||
inputs: {
|
||||
"user_token": currentToken
|
||||
},
|
||||
systemVariables: {
|
||||
"user_id": dynamicUserId
|
||||
},
|
||||
userVariables: {},
|
||||
};
|
||||
|
||||
// 重新挂载
|
||||
var script = document.createElement('script');
|
||||
script.src = 'http://172.16.0.198:8080/embed.min.js?t=' + new Date().getTime();
|
||||
script.id = '6T0eTgukUEqzK0iW';
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
|
||||
console.log('✅ Dify chatbot 已挂载新会话,当前绑定 ID:', dynamicUserId);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script
|
||||
src="http://172.16.0.198:8080/embed.min.js"
|
||||
id="6T0eTgukUEqzK0iW"
|
||||
defer>
|
||||
</script>
|
||||
<!--<script-->
|
||||
<!-- src="http://172.16.0.198:8080/embed.min.js"-->
|
||||
<!-- id="6T0eTgukUEqzK0iW"-->
|
||||
<!-- defer>-->
|
||||
<!--</script>-->
|
||||
|
||||
<style>
|
||||
#dify-chatbot-bubble-button {
|
||||
@ -38,7 +77,7 @@
|
||||
|
||||
/* 变成"独立悬浮窗口" */
|
||||
#dify-chatbot-bubble-window {
|
||||
/* 👇 解除原本锁定在右下角的限制,将其定位在屏幕中间偏左上 */
|
||||
/* 解除原本锁定在右下角的限制,将其定位在屏幕中间偏左上 */
|
||||
top: 15vh !important;
|
||||
left: 20vw !important;
|
||||
bottom: auto !important;
|
||||
@ -49,9 +88,9 @@
|
||||
height: 70vh !important;
|
||||
|
||||
border-radius: 12px !important;
|
||||
box-shadow: 0 12px 48px rgba(0, 0, 0, 0.2) !important; /* 增加超大弥散阴影,浮现感更强 */
|
||||
box-shadow: 0 12px 48px rgba(0, 0, 0, 0.2) !important;
|
||||
|
||||
/* 👇 开启右下角拖拽,并强制留出 16px 的白边给拖拽手柄 */
|
||||
/* 开启右下角拖拽,并强制留出 16px 的白边给拖拽手柄 */
|
||||
resize: both !important;
|
||||
overflow: hidden !important;
|
||||
padding-bottom: 16px !important;
|
||||
|
||||
@ -20,6 +20,10 @@ onMounted(() => {
|
||||
if (userStore.token) {
|
||||
userStore.refreshUserPermissions()
|
||||
}
|
||||
// 当 Vue 根组件挂载完毕,确保 Dify 图标一定会被加载
|
||||
if (typeof (window as any).initDifyChatbot === 'function') {
|
||||
(window as any).initDifyChatbot()
|
||||
}
|
||||
})
|
||||
|
||||
// ================================================================
|
||||
@ -189,7 +193,8 @@ const handleLogout = () => {
|
||||
.then(async () => {
|
||||
userStore.logout()
|
||||
ElMessage({ type: 'success', message: '已安全退出' })
|
||||
await router.replace('/login')
|
||||
// 直接原生跳转,重置一切
|
||||
window.location.href = '/login'
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
@ -234,7 +239,7 @@ const handleLogout = () => {
|
||||
<footer v-if="!isLoginPage" class="app-footer">
|
||||
<span class="version-tag">
|
||||
<el-icon style="vertical-align: middle; margin-right: 4px"><InfoFilled /></el-icon>
|
||||
当前版本:V3.26(添加AI助手版)
|
||||
当前版本:V3.31(识图版)
|
||||
</span>
|
||||
</footer>
|
||||
|
||||
|
||||
@ -3,7 +3,6 @@ import request from '@/utils/request'
|
||||
/**
|
||||
* 上传文件通用接口
|
||||
* @param data File 对象 或 FormData 对象
|
||||
* 适配说明:list.vue 中 customUpload 已经封装了 FormData,所以这里支持直接传 FormData
|
||||
*/
|
||||
export function uploadFile(data: File | FormData) {
|
||||
let formData: FormData
|
||||
@ -11,14 +10,12 @@ export function uploadFile(data: File | FormData) {
|
||||
if (data instanceof FormData) {
|
||||
formData = data
|
||||
} else {
|
||||
// 如果传入的是原始 File 对象,则手动封装
|
||||
formData = new FormData()
|
||||
// @ts-ignore
|
||||
formData.append('file', data)
|
||||
}
|
||||
|
||||
return request({
|
||||
// 注意:这里 /v1/common/upload 需要与后端 BluePrint 注册的 url_prefix 对应
|
||||
url: '/v1/common/upload',
|
||||
method: 'post',
|
||||
data: formData,
|
||||
@ -29,13 +26,50 @@ export function uploadFile(data: File | FormData) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件通用接口 (新增)
|
||||
* 删除文件通用接口
|
||||
* @param filename 文件名 (例如: a1b2c3d4.jpg)
|
||||
*/
|
||||
export function deleteFile(filename: string) {
|
||||
return request({
|
||||
// 对应后端路由: @upload_bp.route('/files/<filename>', methods=['DELETE'])
|
||||
url: `/v1/common/files/${filename}`,
|
||||
method: 'delete'
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 以图搜图 API
|
||||
// ============================================================================
|
||||
|
||||
/** 以图搜图返回的物料项 */
|
||||
export interface ImageSearchItem {
|
||||
product_id: number
|
||||
product_name: string
|
||||
spec_model: string
|
||||
image_url: string
|
||||
similarity: number
|
||||
}
|
||||
|
||||
/** 以图搜图响应结构 */
|
||||
export interface ImageSearchResponse {
|
||||
code: number
|
||||
msg: string
|
||||
data: ImageSearchItem[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 以图搜图
|
||||
* @param file 图片文件 (File 对象或 Blob)
|
||||
*/
|
||||
export function imageSearch(file: File | Blob) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return request<ImageSearchResponse>({
|
||||
url: '/v1/common/image-search',
|
||||
method: 'post',
|
||||
data: formData,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
})
|
||||
}
|
||||
480
inventory-web/src/components/ImageSearchDialog.vue
Normal file
480
inventory-web/src/components/ImageSearchDialog.vue
Normal file
@ -0,0 +1,480 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="以图搜图"
|
||||
width="95%"
|
||||
style="max-width: 680px;"
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
@close="handleClose"
|
||||
>
|
||||
<div class="image-search-body">
|
||||
<!-- 左侧:图片上传 -->
|
||||
<div class="upload-section">
|
||||
<el-upload
|
||||
ref="uploadRef"
|
||||
class="image-uploader"
|
||||
:auto-upload="false"
|
||||
:show-file-list="false"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
:on-change="handleFileChange"
|
||||
>
|
||||
<div v-if="!previewUrl" class="upload-placeholder">
|
||||
<el-icon class="upload-icon" :size="48"><Camera /></el-icon>
|
||||
<div class="upload-text">点击拍照或选择图片</div>
|
||||
<div class="upload-hint">支持 jpg/png 格式</div>
|
||||
</div>
|
||||
<div v-else class="preview-wrapper">
|
||||
<img :src="previewUrl" class="preview-image" />
|
||||
<div class="preview-overlay">
|
||||
<el-button size="small" @click.stop="clearImage">重新拍照</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-upload>
|
||||
|
||||
<div v-if="searching" class="loading-tip">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
<span>正在识别图片并检索...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:搜索结果 -->
|
||||
<div class="result-section">
|
||||
<div v-if="!searched && !searching" class="result-empty">
|
||||
<el-icon :size="40" color="#c0c4cc"><Picture /></el-icon>
|
||||
<p>上传图片后自动检索</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="searched && results.length === 0" class="result-empty">
|
||||
<el-icon :size="40" color="#c0c4cc"><WarningFilled /></el-icon>
|
||||
<p>未找到相似物料</p>
|
||||
<p class="result-hint">请尝试更换图片</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="result-list">
|
||||
<div
|
||||
v-for="(item, index) in results"
|
||||
:key="item.product_id"
|
||||
class="result-item"
|
||||
>
|
||||
<div class="item-rank">{{ index + 1 }}</div>
|
||||
<div class="item-image">
|
||||
<img
|
||||
v-if="item.image_url"
|
||||
:src="fullImageUrl(item.image_url)"
|
||||
@error="handleImgError($event)"
|
||||
/>
|
||||
<div v-else class="image-placeholder">
|
||||
<el-icon :size="24" color="#c0c4cc"><Picture /></el-icon>
|
||||
</div>
|
||||
</div>
|
||||
<div class="item-info">
|
||||
<div class="item-name">{{ item.product_name || '未命名物料' }}</div>
|
||||
<div class="item-spec">{{ item.spec_model || '无规格' }}</div>
|
||||
<div class="item-similarity">
|
||||
<span class="similarity-label">相似度</span>
|
||||
<span class="similarity-value">{{ (item.similarity * 100).toFixed(2) }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="handleView(item)"
|
||||
>
|
||||
查看详情
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button @click="handleClose">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { Camera, Loading, Picture, WarningFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { imageSearch, type ImageSearchItem } from '@/api/common/upload'
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', val: boolean): void
|
||||
(e: 'use', item: ImageSearchItem): void
|
||||
(e: 'view', item: ImageSearchItem): void
|
||||
}>()
|
||||
|
||||
const visible = ref(props.modelValue)
|
||||
const uploadRef = ref()
|
||||
const previewUrl = ref('')
|
||||
const currentFile = ref<File | null>(null)
|
||||
const searching = ref(false)
|
||||
const searched = ref(false)
|
||||
const results = ref<ImageSearchItem[]>([])
|
||||
|
||||
watch(() => props.modelValue, (val) => {
|
||||
visible.value = val
|
||||
if (!val) {
|
||||
resetState()
|
||||
}
|
||||
})
|
||||
|
||||
watch(visible, (val) => {
|
||||
emit('update:modelValue', val)
|
||||
})
|
||||
|
||||
const handleFileChange = (uploadFile: any) => {
|
||||
const file = uploadFile.raw
|
||||
if (!file) return
|
||||
|
||||
// 校验格式
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp']
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
ElMessage.warning('仅支持 jpg/png/gif/webp/bmp 格式')
|
||||
return
|
||||
}
|
||||
|
||||
currentFile.value = file
|
||||
previewUrl.value = URL.createObjectURL(file)
|
||||
|
||||
// 自动触发搜索
|
||||
doSearch(file)
|
||||
}
|
||||
|
||||
const doSearch = async (file: File) => {
|
||||
if (searching.value) return
|
||||
|
||||
searching.value = true
|
||||
searched.value = false
|
||||
results.value = []
|
||||
|
||||
try {
|
||||
const res = await imageSearch(file)
|
||||
if (res.code === 200) {
|
||||
results.value = res.data || []
|
||||
} else {
|
||||
ElMessage.error(res.msg || '检索失败')
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('image search error:', err)
|
||||
ElMessage.error(err.message || '网络错误,请重试')
|
||||
} finally {
|
||||
searching.value = false
|
||||
searched.value = true
|
||||
}
|
||||
}
|
||||
|
||||
const clearImage = () => {
|
||||
previewUrl.value = ''
|
||||
currentFile.value = null
|
||||
results.value = []
|
||||
searched.value = false
|
||||
uploadRef.value?.clearFiles()
|
||||
}
|
||||
|
||||
const fullImageUrl = (path: string) => {
|
||||
if (!path) return '';
|
||||
// 直接原样返回,完全信任后端传过来的 image_url
|
||||
return path.startsWith('http') ? path : path;
|
||||
}
|
||||
|
||||
const handleImgError = (e: Event) => {
|
||||
const img = e.target as HTMLImageElement
|
||||
img.style.display = 'none'
|
||||
}
|
||||
|
||||
const handleUse = (item: ImageSearchItem) => {
|
||||
emit('use', item)
|
||||
handleClose()
|
||||
}
|
||||
|
||||
const handleView = (item: ImageSearchItem) => {
|
||||
emit('view', item)
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
visible.value = false
|
||||
}
|
||||
|
||||
const resetState = () => {
|
||||
previewUrl.value = ''
|
||||
currentFile.value = null
|
||||
searching.value = false
|
||||
searched.value = false
|
||||
results.value = []
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.image-search-body {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
min-height: 380px;
|
||||
}
|
||||
|
||||
/* ── 左侧上传区 ── */
|
||||
.upload-section {
|
||||
flex: 0 0 220px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.image-uploader {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:deep(.el-upload) {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:deep(.el-upload-dragger) {
|
||||
width: 100%;
|
||||
height: 280px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #fafafa;
|
||||
border: 2px dashed #dcdfe6;
|
||||
border-radius: 8px;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
:deep(.el-upload-dragger:hover) {
|
||||
border-color: #409eff;
|
||||
}
|
||||
|
||||
.upload-placeholder {
|
||||
text-align: center;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
color: #c0c4cc;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.upload-hint {
|
||||
font-size: 12px;
|
||||
color: #c0c4cc;
|
||||
}
|
||||
|
||||
.preview-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 280px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-image {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.preview-overlay {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 10px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.preview-overlay .el-button {
|
||||
color: #fff;
|
||||
border-color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.loading-tip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: #409eff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ── 右侧结果区 ── */
|
||||
.result-section {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.result-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 280px;
|
||||
color: #909399;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.result-empty p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.result-hint {
|
||||
font-size: 12px !important;
|
||||
color: #c0c4cc;
|
||||
}
|
||||
|
||||
.result-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.result-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 12px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 8px;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.result-item:hover {
|
||||
background: #ecf5ff;
|
||||
}
|
||||
|
||||
.item-rank {
|
||||
flex: 0 0 24px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background: #409eff;
|
||||
color: #fff;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.item-image {
|
||||
flex: 0 0 60px;
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid #ebeef5;
|
||||
}
|
||||
|
||||
.item-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.image-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.item-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.item-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.item-spec {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
margin-top: 4px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.item-similarity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.similarity-label {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.similarity-value {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
/* ---- 新增:移动端适配样式 ---- */
|
||||
@media screen and (max-width: 768px) {
|
||||
.image-search-body {
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.upload-section {
|
||||
flex: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:deep(.el-upload), :deep(.el-upload-dragger) {
|
||||
height: 160px;
|
||||
}
|
||||
|
||||
.preview-image {
|
||||
max-height: 140px;
|
||||
width: auto;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.result-section {
|
||||
width: 100%;
|
||||
max-height: 50vh;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -84,6 +84,11 @@ export const useUserStore = defineStore('user', () => {
|
||||
localStorage.setItem('refresh_token', data.refresh_token)
|
||||
}
|
||||
|
||||
// [Dify] 登录成功,重新初始化 Dify(Token 变化时 Dify 会开辟新会话,解决会话串号问题)
|
||||
if (typeof window.initDifyChatbot === 'function') {
|
||||
window.initDifyChatbot()
|
||||
}
|
||||
|
||||
// 登录成功后,根据角色获取权限
|
||||
if (role.value) {
|
||||
try {
|
||||
@ -110,6 +115,11 @@ export const useUserStore = defineStore('user', () => {
|
||||
const setToken = (newToken: string) => {
|
||||
token.value = newToken
|
||||
localStorage.setItem('access_token', newToken)
|
||||
|
||||
// [Dify] Token 刷新后,重新初始化 Dify 以更新用户会话
|
||||
if (typeof window.initDifyChatbot === 'function') {
|
||||
window.initDifyChatbot()
|
||||
}
|
||||
}
|
||||
|
||||
// 退出逻辑
|
||||
@ -123,6 +133,11 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
// 2. 清空 LocalStorage (硬盘)
|
||||
localStorage.removeItem('access_token')
|
||||
|
||||
// [Dify] 退出登录时,彻底销毁桌面上的 Dify 聊天窗口,防止信息泄露或报错
|
||||
document.querySelectorAll('[id^="dify-chatbot-"]').forEach(el => el.remove())
|
||||
|
||||
// 清空其他本地存储
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('role')
|
||||
|
||||
@ -164,7 +164,7 @@
|
||||
|
||||
<el-table :data="filteredChildren" border style="width: 100%; margin-bottom: 15px" max-height="300">
|
||||
<el-table-column label="子件物料" min-width="250" v-if="hasFormFieldPermission('child_id')">
|
||||
<template #default="{ row, $index }">
|
||||
<template #default="{ row }">
|
||||
<!-- ====== 改造:子件下拉 - 远程搜索 + 懒加载 ====== -->
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<el-select
|
||||
@ -174,14 +174,14 @@
|
||||
remote
|
||||
reserve-keyword
|
||||
style="flex: 1;"
|
||||
:remote-method="(q: string) => handleRemoteSearch(q, 'child', $index)"
|
||||
:remote-method="(q: string) => handleRemoteSearch(q, 'child', row.rowKey)"
|
||||
:loading="selectLoading"
|
||||
:loading-text="`正在加载第 ${childQueryParams.page} 页...`"
|
||||
:popper-class="`bom-loadmore-popper child-popper-${$index}`"
|
||||
@visible-change="(visible: boolean) => handleVisibleChange(visible, 'child', $index)"
|
||||
:popper-class="`bom-loadmore-popper child-popper-${row.rowKey}`"
|
||||
@visible-change="(visible: boolean) => handleVisibleChange(visible, 'child', row.rowKey)"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in getChildOptions($index)"
|
||||
v-for="item in getChildOptions(row.rowKey)"
|
||||
:key="item.id"
|
||||
:label="`${item.name} (${item.spec})`"
|
||||
:value="item.id"
|
||||
@ -197,7 +197,7 @@
|
||||
type="primary"
|
||||
link
|
||||
:icon="EditPen"
|
||||
@click.stop="openMaterialInNewTab(row.child_id, getChildSpec($index))"
|
||||
@click.stop="openMaterialInNewTab(row.child_id, getChildSpec(row.rowKey))"
|
||||
style="font-size: 16px; padding: 4px;"
|
||||
/>
|
||||
</el-tooltip>
|
||||
@ -218,8 +218,8 @@
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="操作" width="60" align="center" v-if="userStore.hasPermission('bom_manage:operation')">
|
||||
<template #default="{ $index }">
|
||||
<el-button type="danger" link @click="removeChild($index)">删</el-button>
|
||||
<template #default="{ row }">
|
||||
<el-button type="danger" link @click="removeChild(row.rowKey)">删</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@ -240,7 +240,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
|
||||
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
|
||||
import { Plus, Search, EditPen } from '@element-plus/icons-vue'
|
||||
@ -266,6 +266,7 @@ interface MaterialBase {
|
||||
spec: string
|
||||
}
|
||||
interface ChildRow {
|
||||
rowKey: number // 唯一标识,替代 $index 作为 Map key
|
||||
child_id: number | null
|
||||
dosage: number
|
||||
remark: string
|
||||
@ -288,6 +289,15 @@ const activeCategories = ref([]) // 默认全部展开
|
||||
const searchKeyword = ref('')
|
||||
const childSearchKeyword = ref('')
|
||||
|
||||
// ★ 自动搜索:输入后 500ms 防抖触发搜索(无需回车)
|
||||
watch(searchKeyword, (val) => {
|
||||
// 防抖:延迟 500ms 执行,避免频繁请求
|
||||
clearTimeout((window as any)._bomSearchTimer)
|
||||
;(window as any)._bomSearchTimer = setTimeout(() => {
|
||||
fetchBomList()
|
||||
}, 500)
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// 【改造】分页 + 远程搜索相关状态
|
||||
// ============================================================
|
||||
@ -321,15 +331,15 @@ const getChildOptions = (index: number): MaterialBase[] => {
|
||||
// ============================================================
|
||||
const fetchMaterialOptions = async (
|
||||
type: 'parent' | 'child',
|
||||
index?: number,
|
||||
rowKey?: number,
|
||||
isLoadMore = false
|
||||
) => {
|
||||
// 子件行需要 index
|
||||
if (type === 'child' && index === undefined) return
|
||||
// 子件行需要 rowKey(唯一标识,不再依赖数组索引)
|
||||
if (type === 'child' && rowKey === undefined) return
|
||||
|
||||
const params = type === 'parent'
|
||||
? parentQueryParams
|
||||
: childDropdownStates.value.get(index!)?.queryParams
|
||||
: childDropdownStates.value.get(rowKey!)?.queryParams
|
||||
|
||||
if (!params) return
|
||||
|
||||
@ -353,12 +363,19 @@ const fetchMaterialOptions = async (
|
||||
const newItems = list.filter(m => !existingIds.has(m.id))
|
||||
parentOptions.value.push(...newItems)
|
||||
} else {
|
||||
parentOptions.value = list
|
||||
// ★ 修复回显丢失:先检查当前选中项是否在列表中,不在则从原 options 保留
|
||||
const selectedId = form.parent_id
|
||||
let finalList = [...list]
|
||||
if (selectedId && !list.find(m => m.id === selectedId)) {
|
||||
const existing = parentOptions.value.find(m => m.id === selectedId)
|
||||
if (existing) finalList.unshift(existing)
|
||||
}
|
||||
parentOptions.value = finalList
|
||||
}
|
||||
// 判断是否还有更多数据
|
||||
parentHasMore.value = parentOptions.value.length < total
|
||||
} else {
|
||||
const state = childDropdownStates.value.get(index!)
|
||||
const state = childDropdownStates.value.get(rowKey!)
|
||||
if (!state) return
|
||||
|
||||
if (isLoadMore) {
|
||||
@ -366,7 +383,15 @@ const fetchMaterialOptions = async (
|
||||
const newItems = list.filter(m => !existingIds.has(m.id))
|
||||
state.options.push(...newItems)
|
||||
} else {
|
||||
state.options = list
|
||||
// ★ 修复回显丢失:先通过 rowKey 精准找到当前行,再检查选中项是否在列表中
|
||||
const currentRow = form.children.find(c => c.rowKey === rowKey)
|
||||
const currentSelectedId = currentRow?.child_id
|
||||
let finalList = [...list]
|
||||
if (currentSelectedId && !list.find(m => m.id === currentSelectedId)) {
|
||||
const existing = state.options.find(m => m.id === currentSelectedId)
|
||||
if (existing) finalList.unshift(existing)
|
||||
}
|
||||
state.options = finalList
|
||||
}
|
||||
state.hasMore = state.options.length < total
|
||||
}
|
||||
@ -384,27 +409,27 @@ const fetchMaterialOptions = async (
|
||||
const handleRemoteSearch = (
|
||||
query: string,
|
||||
type: 'parent' | 'child',
|
||||
index?: number
|
||||
rowKey?: number
|
||||
) => {
|
||||
if (type === 'parent') {
|
||||
parentQueryParams.keyword = query
|
||||
parentQueryParams.page = 1
|
||||
parentHasMore.value = true
|
||||
fetchMaterialOptions('parent')
|
||||
} else if (type === 'child' && index !== undefined) {
|
||||
const state = childDropdownStates.value.get(index)
|
||||
} else if (type === 'child' && rowKey !== undefined) {
|
||||
const state = childDropdownStates.value.get(rowKey)
|
||||
if (!state) return
|
||||
state.queryParams.keyword = query
|
||||
state.queryParams.page = 1
|
||||
state.hasMore = true
|
||||
fetchMaterialOptions('child', index)
|
||||
fetchMaterialOptions('child', rowKey)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 【改造】下拉框展开/收起处理(重置分页 + 预加载第一页)
|
||||
// ============================================================
|
||||
const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', index?: number) => {
|
||||
const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', rowKey?: number) => {
|
||||
if (!visible) return
|
||||
|
||||
if (type === 'parent') {
|
||||
@ -412,20 +437,20 @@ const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', index?:
|
||||
parentQueryParams.keyword = ''
|
||||
parentHasMore.value = true
|
||||
fetchMaterialOptions('parent')
|
||||
} else if (type === 'child' && index !== undefined) {
|
||||
} else if (type === 'child' && rowKey !== undefined) {
|
||||
// 确保该行下拉状态已初始化
|
||||
if (!childDropdownStates.value.has(index)) {
|
||||
childDropdownStates.value.set(index, {
|
||||
if (!childDropdownStates.value.has(rowKey)) {
|
||||
childDropdownStates.value.set(rowKey, {
|
||||
options: [],
|
||||
queryParams: { page: 1, limit: PAGE_SIZE, keyword: '' },
|
||||
hasMore: true
|
||||
})
|
||||
}
|
||||
const state = childDropdownStates.value.get(index)!
|
||||
const state = childDropdownStates.value.get(rowKey)!
|
||||
state.queryParams.page = 1
|
||||
state.queryParams.keyword = ''
|
||||
state.hasMore = true
|
||||
fetchMaterialOptions('child', index)
|
||||
fetchMaterialOptions('child', rowKey)
|
||||
}
|
||||
|
||||
// 延迟 50ms 等待弹窗 DOM 完全渲染
|
||||
@ -433,7 +458,7 @@ const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', index?:
|
||||
// 动态拼接精确的选择器
|
||||
const exactSelector = type === 'parent'
|
||||
? '.parent-popper .el-select-dropdown__wrap'
|
||||
: `.child-popper-${index} .el-select-dropdown__wrap`;
|
||||
: `.child-popper-${rowKey} .el-select-dropdown__wrap`;
|
||||
|
||||
const popperWrap = document.querySelector(exactSelector) as HTMLElement;
|
||||
|
||||
@ -450,9 +475,9 @@ const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', index?:
|
||||
if (scrollHeight - scrollTop - clientHeight <= 10) {
|
||||
if (type === 'parent') {
|
||||
loadMoreParent();
|
||||
} else if (type === 'child' && index !== undefined) {
|
||||
} else if (type === 'child' && rowKey !== undefined) {
|
||||
// 触发子件加载
|
||||
loadMoreChild(popperWrap, index);
|
||||
loadMoreChild(popperWrap, rowKey);
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -470,20 +495,20 @@ const loadMoreParent = () => {
|
||||
fetchMaterialOptions('parent', undefined, true)
|
||||
}
|
||||
|
||||
const loadMoreChild = (_el: HTMLElement, index: number) => {
|
||||
const state = childDropdownStates.value.get(index)
|
||||
const loadMoreChild = (_el: HTMLElement, rowKey: number) => {
|
||||
const state = childDropdownStates.value.get(rowKey)
|
||||
if (!state) return
|
||||
if (selectLoading.value || !state.hasMore) return
|
||||
state.queryParams.page++
|
||||
fetchMaterialOptions('child', index, true)
|
||||
fetchMaterialOptions('child', rowKey, true)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 【改造】初始化子件行下拉状态
|
||||
// ============================================================
|
||||
const initChildDropdownState = (index: number) => {
|
||||
if (!childDropdownStates.value.has(index)) {
|
||||
childDropdownStates.value.set(index, {
|
||||
const initChildDropdownState = (rowKey: number) => {
|
||||
if (!childDropdownStates.value.has(rowKey)) {
|
||||
childDropdownStates.value.set(rowKey, {
|
||||
options: [],
|
||||
queryParams: { page: 1, limit: PAGE_SIZE, keyword: '' },
|
||||
hasMore: true
|
||||
@ -500,7 +525,7 @@ const filteredChildren = computed(() => {
|
||||
}
|
||||
const kw = childSearchKeyword.value.toLowerCase()
|
||||
return form.children.filter(child => {
|
||||
const state = childDropdownStates.value.get(form.children.indexOf(child))
|
||||
const state = childDropdownStates.value.get(child.rowKey)
|
||||
const material = state?.options.find(m => m.id === child.child_id)
|
||||
if (!material) return false
|
||||
const name = (material.name || '').toLowerCase()
|
||||
@ -510,10 +535,11 @@ const filteredChildren = computed(() => {
|
||||
})
|
||||
|
||||
// 获取子件规格(从 childDropdownStates 缓存中查找)
|
||||
const getChildSpec = (index: number): string => {
|
||||
const state = childDropdownStates.value.get(index)
|
||||
if (!state || !form.children[index]?.child_id) return ''
|
||||
const material = state.options.find((m: MaterialBase) => m.id === form.children[index].child_id)
|
||||
const getChildSpec = (rowKey: number): string => {
|
||||
const state = childDropdownStates.value.get(rowKey)
|
||||
const row = form.children.find(c => c.rowKey === rowKey)
|
||||
if (!state || !row?.child_id) return ''
|
||||
const material = state.options.find((m: MaterialBase) => m.id === row.child_id)
|
||||
return material?.spec || ''
|
||||
}
|
||||
|
||||
@ -677,8 +703,9 @@ const loadDetail = async (bomNo: string, version: string) => {
|
||||
const res = await getBomDetail(bomNo, version)
|
||||
if (res.code === 200) {
|
||||
const data = res.data
|
||||
// 1. 映射子件基本数据
|
||||
form.children = data.children.map((child: any) => ({
|
||||
// 1. 映射子件基本数据(使用 idx 生成唯一 rowKey)
|
||||
form.children = data.children.map((child: any, idx: number) => ({
|
||||
rowKey: idx, // 用数组索引作为唯一标识(编辑场景下不会增删行)
|
||||
child_id: child.child_id,
|
||||
dosage: child.dosage,
|
||||
remark: child.remark || ''
|
||||
@ -686,7 +713,7 @@ const loadDetail = async (bomNo: string, version: string) => {
|
||||
|
||||
// 2. 初始化子件下拉状态,并预填充 options 解决回显显示 ID 的问题
|
||||
form.children.forEach((child, idx) => {
|
||||
initChildDropdownState(idx)
|
||||
initChildDropdownState(idx) // rowKey === idx(编辑场景下唯一)
|
||||
|
||||
if (child.child_id) {
|
||||
const state = childDropdownStates.value.get(idx)!
|
||||
@ -755,26 +782,17 @@ const resetForm = () => {
|
||||
}
|
||||
|
||||
const addChild = () => {
|
||||
const idx = form.children.length
|
||||
form.children.push({ child_id: null, dosage: 0, remark: '' })
|
||||
initChildDropdownState(idx)
|
||||
const rowKey = Date.now() // 生成唯一标识,不再使用数组长度
|
||||
form.children.push({ rowKey, child_id: null, dosage: 0, remark: '' })
|
||||
initChildDropdownState(rowKey)
|
||||
}
|
||||
|
||||
const removeChild = (idx: number) => {
|
||||
form.children.splice(idx, 1)
|
||||
// 清理该行下拉状态(需要重新索引后续行的状态)
|
||||
rebuildChildDropdownStates()
|
||||
}
|
||||
|
||||
// 重建子件下拉状态索引(删除行后需要重新编号)
|
||||
const rebuildChildDropdownStates = () => {
|
||||
const newMap = new Map<number, ChildDropdownState>()
|
||||
form.children.forEach((_, idx) => {
|
||||
if (childDropdownStates.value.has(idx)) {
|
||||
newMap.set(idx, childDropdownStates.value.get(idx)!)
|
||||
}
|
||||
})
|
||||
childDropdownStates.value = newMap
|
||||
const removeChild = (rowKey: number) => {
|
||||
// 通过 rowKey 找到并删除该行(不再依赖数组索引)
|
||||
const idx = form.children.findIndex(c => c.rowKey === rowKey)
|
||||
if (idx !== -1) form.children.splice(idx, 1)
|
||||
// 直接删除该行的下拉状态(无需重建索引)
|
||||
childDropdownStates.value.delete(rowKey)
|
||||
}
|
||||
|
||||
const submitForm = async () => {
|
||||
|
||||
@ -80,12 +80,9 @@ const onLogin = async () => {
|
||||
const success = await userStore.handleLogin(loginForm)
|
||||
|
||||
if (success) {
|
||||
// [新增] 2. 登录成功后,立即拉取当前用户的权限字典
|
||||
// 这样进入 Dashboard 时,所有按钮/列的显示状态就已经确定了
|
||||
await permissionStore.loadPermissions()
|
||||
|
||||
// 3. 跳转
|
||||
router.push('/dashboard')
|
||||
// 直接跳转并触发完整页面重载,干净重置 Dify Embed Token
|
||||
window.location.href = '/dashboard'
|
||||
} else {
|
||||
// 失败(业务逻辑拒绝):弹出模态框
|
||||
showLoginFailAlert('用户名或密码错误')
|
||||
|
||||
@ -84,6 +84,9 @@
|
||||
|
||||
<el-button type="primary" plain @click="handleQuery">搜索</el-button>
|
||||
<el-button plain @click="resetQuery">重置</el-button>
|
||||
<el-button type="primary" plain @click="imageSearchVisible = true">
|
||||
<el-icon style="margin-right: 5px"><Picture /></el-icon>拍照识图
|
||||
</el-button>
|
||||
<el-popover
|
||||
v-model:visible="advancedFilterVisible"
|
||||
placement="bottom"
|
||||
@ -564,6 +567,13 @@
|
||||
/>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 拍照识图弹窗 -->
|
||||
<ImageSearchDialog
|
||||
v-model="imageSearchVisible"
|
||||
@use="handleImageSearchUse"
|
||||
@view="handleImageSearchView"
|
||||
/>
|
||||
|
||||
<!-- 预警设置弹窗 -->
|
||||
<el-dialog v-model="warningDialog.visible" :title="warningDialog.title" width="500px" append-to-body destroy-on-close>
|
||||
<el-form ref="warningFormRef" :model="warningForm" :rules="warningRules" label-width="100px">
|
||||
@ -633,7 +643,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
|
||||
import { Plus, Document, Refresh, Setting, Rank, Camera, Link, Download, Bell, CircleCheck, Files, ZoomIn, Delete } from '@element-plus/icons-vue';
|
||||
import { Plus, Document, Refresh, Setting, Rank, Camera, Link, Download, Bell, CircleCheck, Files, ZoomIn, Delete, Picture } from '@element-plus/icons-vue';
|
||||
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
|
||||
import type { FormInstance, FormRules } from 'element-plus';
|
||||
import { useUserStore } from '@/stores/user';
|
||||
@ -655,6 +665,8 @@ import {
|
||||
import { uploadFile, deleteFile } from '@/api/common/upload';
|
||||
import { usePasteUpload } from '@/hooks/usePasteUpload';
|
||||
import WebRtcCamera from '@/components/Camera/WebRtcCamera.vue';
|
||||
import ImageSearchDialog from '@/components/ImageSearchDialog.vue';
|
||||
import { imageSearch as imageSearchApi, type ImageSearchItem } from '@/api/common/upload';
|
||||
|
||||
const userStore = useUserStore();
|
||||
|
||||
@ -716,6 +728,7 @@ const isUploading = ref(false);
|
||||
|
||||
const tableSize = ref<'large' | 'default' | 'small'>('large');
|
||||
const advancedFilterVisible = ref(false);
|
||||
const imageSearchVisible = ref(false);
|
||||
const advancedConditions = ref([{ field: '', operator: '', value: '' }]);
|
||||
const fieldOptions = computed(() => {
|
||||
const allFields = [
|
||||
@ -1585,15 +1598,8 @@ const customUpload = async (options: any, targetField: 'generalImage' | 'general
|
||||
if (res.code === 200) {
|
||||
const newUrl = res.data.url
|
||||
form.value[targetField].push(newUrl)
|
||||
// 同步更新 fileList,触发 el-upload UI 刷新
|
||||
const fileObj = { name: newUrl.split('/').pop(), url: getImageUrl(newUrl) }
|
||||
if (targetField === 'generalImage') {
|
||||
fileListImage.value.push(fileObj)
|
||||
} else {
|
||||
fileListManual.value.push(fileObj)
|
||||
}
|
||||
ElMessage.success('上传成功')
|
||||
onSuccess(res)
|
||||
onSuccess(res) // el-upload v-model 自动更新 fileList,无需手动 push
|
||||
} else {
|
||||
ElMessage.error(res.msg || '上传失败');
|
||||
onError(new Error(res.msg))
|
||||
@ -1693,6 +1699,21 @@ const handleCameraConfirm = async (file: File) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 点击"查看详情":直接在当前页面应用规格型号并搜索
|
||||
const handleImageSearchView = (item: any) => {
|
||||
// 1. 关闭以图搜图弹窗
|
||||
imageSearchVisible.value = false;
|
||||
|
||||
// 2. 将选中的规格型号填入搜索表单的 keyword 中
|
||||
queryParams.keyword = item.spec_model;
|
||||
|
||||
// 3. 触发列表的查询函数,刷新表格数据
|
||||
handleQuery();
|
||||
|
||||
// 4. 给出友好提示
|
||||
ElMessage.success(`已应用物料规格: ${item.spec_model} 进行搜索`);
|
||||
};
|
||||
|
||||
const addCondition = () => {
|
||||
advancedConditions.value.push({ field: '', operator: '', value: '' });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user