Compare commits

27 Commits

Author SHA1 Message Date
super 855f1affd9 紫鸟查询店铺更新 2026-04-02 01:15:50 +08:00
super df606a1087 Merge branch 'master' of https://gitee.com/TeaCodeNice/crawler-plugin 2026-04-01 21:20:04 +08:00
super ece3552b89 更新部分内容 2026-04-01 21:20:01 +08:00
铭坤 4df3945131 modified: app/ali_oss.py
new file:   app/amazon/del_brand.py
	new file:   app/amazon/main.py
	modified:   app/blueprints/__pycache__/brand.cpython-39.pyc
	modified:   app/blueprints/__pycache__/communication.cpython-39.pyc
	modified:   app/blueprints/__pycache__/main.cpython-39.pyc
	modified:   app/blueprints/brand.py
	new file:   "app/blueprints/brand_\345\244\207\344\273\275.py"
	modified:   app/blueprints/communication.py
	modified:   app/blueprints/main.py
	modified:   app/config.py
	modified:   app/main.py
2026-04-01 11:53:12 +08:00
super 6eb0f33421 删除模块 取消打开紫鸟 2026-03-31 23:12:46 +08:00
super 25ce9f74b8 处理这个python打开紫鸟 2026-03-30 23:15:08 +08:00
super 0f1f471590 处理掉一些BUG 2026-03-30 22:47:19 +08:00
super d9487b6885 品牌多文件chunk修复 2026-03-30 21:06:10 +08:00
super 9845ab8f2a 暂存 2026-03-30 20:54:05 +08:00
super 6fa130386a Merge branch 'master' of https://gitee.com/TeaCodeNice/crawler-plugin 2026-03-30 20:48:02 +08:00
super 53df8b9971 暂存 2026-03-30 20:39:13 +08:00
铭坤 d6625762cf modified: app/.env
modified:   app/ali_oss.py
	modified:   app/app.py
	new file:   app/blueprints/__pycache__/communication.cpython-39.pyc
	modified:   app/blueprints/communication.py
	modified:   app/brand_spider/__pycache__/main.cpython-39.pyc
	modified:   app/config.py
	modified:   app/main.py
	modified:   app/static/bg.jpg
	modified:   app/tool/__pycache__/devices.cpython-39.pyc
	modified:   app/web_source/brand.html
	modified:   app/web_source/templates_backup/brand.html
2026-03-30 19:44:04 +08:00
super cb3b9e9cfe 完善删除品牌asin 2026-03-29 19:03:24 +08:00
super 3d39236b13 完成删除品牌 2026-03-29 13:41:03 +08:00
super 9e57fa5762 完成品牌删除模块 2026-03-29 00:22:45 +08:00
super 9c6232bc85 完成前后端紫鸟部分开发 2026-03-28 15:42:18 +08:00
super d3c7938627 完成前后端删除、紫鸟部分开发 2026-03-28 15:42:02 +08:00
super 06256946fa 提交暂存 2026-03-27 22:00:01 +08:00
super 2042d386e2 提交过滤 2026-03-27 21:58:43 +08:00
铭坤 7176754564 Merge branch 'master' of https://gitee.com/TeaCodeNice/crawler-plugin 2026-03-27 21:56:53 +08:00
铭坤 a20222192e modified: assets/convert.js
modified:   assets/dedupe.js
	modified:   assets/split.js
	modified:   blueprints/__pycache__/brand.cpython-311.pyc
	modified:   blueprints/__pycache__/brand.cpython-39.pyc
	new file:   blueprints/communication.py
	modified:   config.py
	modified:   main.py
	modified:   new_web_source/convert.html
	modified:   new_web_source/dedupe.html
	modified:   new_web_source/split.html
2026-03-27 21:56:19 +08:00
super a5c2681e88 Merge branch 'master' of https://gitee.com/TeaCodeNice/crawler-plugin 2026-03-27 21:51:34 +08:00
super 5e2f750359 更新运行日志
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 21:51:23 +08:00
super 27602890ab 品牌 2026-03-27 21:48:13 +08:00
铭坤 dfe0d652ce new file: assets/_plugin-vue_export-helper-Dh4yMZWw.js
new file:   assets/_plugin-vue_export-helper-xvHHTGU_.css
	new file:   assets/convert-1dkFPbKa.css
	new file:   assets/convert-6b0yq-M0.css
	new file:   assets/convert-BxkpMHO9.css
	new file:   assets/convert-D4Yv2oRy.css
	new file:   assets/convert-DwbQug2y.css
	modified:   assets/convert.js
	new file:   assets/dedupe-B0eqpVpj.css
	new file:   assets/dedupe-BHE_BCAJ.css
	new file:   assets/dedupe-Day_nGxq.css
	new file:   assets/dedupe-DzFvTfoj.css
	new file:   assets/dedupe-rhGu1E8E.css
	modified:   assets/dedupe.js
	new file:   assets/el-alert-Ct0RpqUD.css
	new file:   assets/pywebview-B6ZNXusn.css
	new file:   assets/pywebview-BRrok0pS.js
	new file:   assets/pywebview-BnpJyyGZ.js
	new file:   assets/pywebview-CGwF8TuM.js
	new file:   assets/pywebview-Chz98E9c.css
	new file:   assets/pywebview-D-PKWjUg.js
	new file:   assets/pywebview-DVgP2-kW.js
	new file:   assets/pywebview-IqgMfeBe.css
	new file:   assets/pywebview-Rm5Hhqpf.js
	new file:   assets/pywebview-leZCedEt.js
	new file:   assets/split-BsJfbBqn.css
	new file:   assets/split-DAa_Usoh.css
	new file:   assets/split-DidKJ84l.css
	new file:   assets/split-R_8V5xgh.css
	new file:   assets/split-_O6NHqDj.css
	modified:   assets/split.js
	modified:   blueprints/__pycache__/brand.cpython-311.pyc
	modified:   blueprints/__pycache__/brand.cpython-39.pyc
	modified:   blueprints/brand.py
	modified:   config.py
	modified:   main.py
	modified:   new_web_source/convert.html
	modified:   new_web_source/dedupe.html
	modified:   new_web_source/split.html
2026-03-27 21:35:28 +08:00
super 24076adf98 品牌 2026-03-27 21:33:07 +08:00
super 15a78abc1b 删除品牌 2026-03-27 21:32:00 +08:00
102 changed files with 9018 additions and 6838 deletions
+3
View File
@@ -36,3 +36,6 @@ ERP-Demo/
xlsx/ xlsx/
app/__pycache__ app/__pycache__
backend/__pycache__ backend/__pycache__
app/assets/
app/new_web_source
app/user_data/
+8 -5
View File
@@ -1,12 +1,15 @@
base_url=http://159.75.121.33:15124 base_url=http://8.136.19.173:15124
workflow_id=7608812635877900322 workflow_id=7608812635877900322
mysql_host=159.75.121.33 mysql_host=8.136.19.173
mysql_user=AIimage mysql_user=aiimage
proxy_url=https://api.jikip.com/ip-get?num=1&minute=1&format=json&area=all&protocol=1&mode=2&key=r4m8dov52giup2o proxy_url=https://api.jikip.com/ip-get?num=1&minute=1&format=json&area=all&protocol=1&mode=2&key=t24g6gi44ubufd8
proxy_mode=2 proxy_mode=2
client_name=NanriAI client_name=ShuFuAI
java_api_base=http://127.0.0.1:18080 java_api_base=http://127.0.0.1:18080
# java_api_base=http://8.136.19.173:18080
Binary file not shown.
Binary file not shown.
Binary file not shown.
+519
View File
@@ -0,0 +1,519 @@
import traceback
import winreg
import subprocess
import time
import uuid
import requests
import json
import os
from typing import Literal
from DrissionPage import Chromium
from DrissionPage.common import By
def kill_process(version: Literal["v5", "v6"]):
"""杀紫鸟客户端进程(独立函数版本)"""
driver = ZiniaoDriver({})
driver.kill_process(version)
class ZiniaoDriver:
"""紫鸟浏览器自动化驱动类"""
def __init__(self, user_info: dict, socket_port: int = 19890):
"""
初始化紫鸟浏览器驱动
Args:
user_info: 用户信息字典,包含 company, username, password
socket_port: 客户端通信端口,默认 19890
"""
self.user_info = user_info
self.socket_port = socket_port
self.client_path = None
self.browser = None
self.tab = None
self.store_id = None
def get_zinaio_exe(self, protocol_name: str = "superbrowser"):
"""
获取紫鸟安装目录
Args:
protocol_name: 协议名称,默认 "superbrowser"
Returns:
exe_path: 紫鸟浏览器可执行文件路径
"""
try:
key_path = rf"SOFTWARE\Classes\{protocol_name}\shell\open\command"
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path)
command, _ = winreg.QueryValueEx(key, "")
winreg.CloseKey(key)
if isinstance(command, str):
exe_path = command.split()[0]
else:
exe_path = command[0]
return exe_path
except FileNotFoundError:
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path)
command, _ = winreg.QueryValueEx(key, "")
winreg.CloseKey(key)
if isinstance(command, str):
exe_path = command.split()[0]
else:
exe_path = command[0]
return exe_path
except FileNotFoundError:
return None
def update_core(self):
"""
下载所有内核,打开店铺前调用,需客户端版本5.285.7以上
因为http有超时时间,所以这个action适合循环调用,直到返回成功
"""
data = {
"action": "updateCore",
"requestId": str(uuid.uuid4()),
}
data.update(self.user_info)
while True:
url = f'http://127.0.0.1:{self.socket_port}'
response = requests.post(url, json.dumps(data).encode('utf-8'), timeout=120)
result = response.json()
print(result)
if result is None:
print("等待客户端启动...")
time.sleep(2)
continue
if result.get("statusCode") is None or result.get("statusCode") == -10003:
print("当前版本不支持此接口,请升级客户端")
return
elif result.get("statusCode") == 0:
print("更新内核完成")
return
else:
print(f"等待更新内核: {json.dumps(result)}")
time.sleep(2)
def kill_process(self, version: Literal["v5", "v6"]):
"""
杀紫鸟客户端进程
Args:
version: 客户端版本
"""
if version == "v5":
process_name = 'SuperBrowser.exe'
else:
process_name = 'ziniao.exe'
os.system('taskkill /f /t /im ' + process_name)
time.sleep(3)
def get_browser_list(self) -> list:
"""
获取浏览器列表
Returns:
list: 浏览器列表
"""
request_id = str(uuid.uuid4())
data = {
"action": "getBrowserList",
"requestId": request_id
}
data.update(self.user_info)
url = f'http://127.0.0.1:{self.socket_port}'
response = requests.post(url, json.dumps(data).encode('utf-8'), timeout=120)
r = response.json()
if str(r.get("statusCode")) == "0":
print(r)
return r.get("browserList")
elif str(r.get("statusCode")) == "-10003":
print(f"login Err {json.dumps(r, ensure_ascii=False)}")
exit()
else:
print(f"Fail {json.dumps(r, ensure_ascii=False)} ")
exit()
def open_store(self, store_info, isWebDriverReadOnlyMode=0, isprivacy=0,
isHeadless=0, cookieTypeSave=0, jsInfo=""):
"""
打开店铺
Args:
store_info: 店铺信息(browserId 或 browserOauth)
isWebDriverReadOnlyMode: 是否只读模式,默认 0
isprivacy: 隐私模式,默认 0
isHeadless: 无头模式,默认 0
cookieTypeSave: cookie保存类型,默认 0
jsInfo: 注入的JS信息,默认 ""
Returns:
dict: 返回结果
"""
request_id = str(uuid.uuid4())
data = {
"action": "startBrowser",
"isWaitPluginUpdate": 0,
"isHeadless": isHeadless,
"requestId": request_id,
"isWebDriverReadOnlyMode": isWebDriverReadOnlyMode,
"cookieTypeLoad": 0,
"cookieTypeSave": cookieTypeSave,
"runMode": "1",
"isLoadUserPlugin": False,
"pluginIdType": 1,
"privacyMode": isprivacy
}
data.update(self.user_info)
if store_info.isdigit():
data["browserId"] = store_info
else:
data["browserOauth"] = store_info
if len(str(jsInfo)) > 2:
data["injectJsInfo"] = json.dumps(jsInfo)
url = f'http://127.0.0.1:{self.socket_port}'
response = requests.post(url, json.dumps(data).encode('utf-8'), timeout=120)
r = response.json()
if str(r.get("statusCode")) == "0":
return r
elif str(r.get("statusCode")) == "-10003":
print(f"login Err {json.dumps(r, ensure_ascii=False)}")
exit()
else:
print(f"Fail {json.dumps(r, ensure_ascii=False)} ")
exit()
def get_browser(self, port) -> Chromium:
"""
获取浏览器实例
Args:
port: 调试端口
Returns:
Chromium: DrissionPage浏览器实例
"""
browser = Chromium(port)
return browser
def start_client(self):
"""启动紫鸟客户端"""
self.client_path = self.get_zinaio_exe("superbrowser").strip('"')
print(self.client_path)
cmd = [self.client_path, '--run_type=web_driver', '--ipc_type=http',
'--port=' + str(self.socket_port)]
print(" ".join(cmd))
subprocess.Popen(cmd)
time.sleep(5)
def open_shop(self, shop_name: str):
"""
打开指定店铺
Args:
shop_name: 店铺名称
Returns:
Chromium or str: 成功返回浏览器实例,失败返回错误信息
"""
# 启动客户端
self.start_client()
# 更新内核
self.update_core()
# 获取店铺列表
shop_ls = self.get_browser_list()
self.store_id = None
# print(shop_ls)
for shop in shop_ls:
if shop.get("browserName") == shop_name:
self.store_id = shop.get('browserOauth')
break
if not self.store_id:
print("店铺不存在")
return "店铺不存在"
# 打开店铺
ret_json = self.open_store(self.store_id)
print(ret_json)
self.store_id = ret_json.get("browserOauth")
if self.store_id is None:
self.store_id = ret_json.get("browserId")
# 获取drissionpage浏览器会话
self.browser = self.get_browser(ret_json.get('debuggingPort'))
ip_check_url = ret_json.get("ipDetectionPage")
if not ip_check_url:
print("ip检测页地址为空,请升级紫鸟浏览器到最新版")
print(f"=====关闭店铺:{shop_name}=====")
self.close_store(self.store_id)
exit()
ip_usable = self.open_ip_check(self.browser, ip_check_url)
if ip_usable:
print("ip检测通过,打开店铺平台主页")
self.open_launcher_page(ret_json.get("launcherPage"), self.browser)
else:
print("IP检测不通过")
return self.browser
def close_store(self, browser_oauth=None):
"""
关闭店铺
Args:
browser_oauth: 店铺OAuth标识,如果不提供则使用当前打开的店铺
Returns:
dict: 返回结果
"""
if browser_oauth is None:
browser_oauth = self.store_id
request_id = str(uuid.uuid4())
data = {
"action": "stopBrowser",
"requestId": request_id,
"duplicate": 0,
"browserOauth": browser_oauth
}
data.update(self.user_info)
url = f'http://127.0.0.1:{self.socket_port}'
response = requests.post(url, json.dumps(data).encode('utf-8'), timeout=120)
r = response.json()
if str(r.get("statusCode")) == "0":
return r
elif str(r.get("statusCode")) == "-10003":
print(f"login Err {json.dumps(r, ensure_ascii=False)}")
exit()
else:
print(f"Fail {json.dumps(r, ensure_ascii=False)} ")
exit()
def open_launcher_page(self, launcher_page: str, browser: Chromium = None):
"""
打开启动页面
Args:
launcher_page: 要打开的页面URL
browser: 浏览器实例,如果不提供则使用当前浏览器实例
"""
if browser is None:
browser = self.browser
tab = browser.new_tab(url=launcher_page)
self.tab = tab
return tab
def open_ip_check(self, browser: Chromium, ip_check_url: str):
"""
打开ip检测页检测ip是否正常
:param browser: drissionpage浏览器会话
:param ip_check_url ip检测页地址
:return 检测结果
"""
try:
tab = browser.latest_tab
tab.get(ip_check_url)
success_button = tab.ele((By.XPATH, '//button[contains(@class, "styles_btn--success")]'),
timeout=60) # 等待查找元素60秒
if success_button:
print("ip检测成功")
return True
else:
print("ip检测超时")
return False
except Exception as e:
print("ip检测异常:" + traceback.format_exc())
return False
class AmazoneDriver(ZiniaoDriver):
"""亚马逊专用驱动类,继承自ZiniaoDriver"""
def SwitchingCountries(self, country_name: str):
"""
切换国家
操作:
1、//div[@class="dropdown-account-switcher-header-label"]/span[last()] 获取此元素文本,判断当前国家,如果与目标国家相同则不操作,否则执行下一步
2、点击 //div[@class="dropdown-account-switcher-header-label"] 打开下拉框
3、点击 //div[@class="dropdown-account-switcher-list-item"] 第一个展开国家列表
4、点击 //div[@class="dropdown-account-switcher-list-item dropdown-account-switcher-list-item-indented" and @title="国家名"] 切换到目标国家
5、等待页面加载完成,判断国家是否切换成功,成功则返回True,否则返回False
Args:
country_name: 目标国家名称
Returns:
bool: 切换成功返回True,失败返回False
"""
try:
if self.browser is None:
print("浏览器实例不存在,请先打开店铺")
return False
# 获取当前标签页
tab = self.tab
# 步骤1:获取当前国家名称
print(f"正在检查当前国家...")
current_country_ele = tab.ele('xpath://div[@class="dropdown-account-switcher-header-label"]/span[last()]',
timeout=10)
if current_country_ele:
current_country = current_country_ele.text.strip()
print(f"当前国家:{current_country}")
# 判断是否与目标国家相同
if current_country == country_name:
print(f"当前已经是目标国家 {country_name},无需切换")
return True
else:
print("无法获取当前国家信息")
return False
# 步骤2:点击打开下拉框
print(f"正在打开国家切换下拉框...")
dropdown_header = tab.ele('xpath://div[@class="dropdown-account-switcher-header-label"]', timeout=10)
if not dropdown_header:
print("找不到国家切换下拉框")
return False
dropdown_header.click()
time.sleep(1) # 等待下拉框展开
# 步骤3:点击第一个展开国家列表
print(f"正在展开国家列表...")
first_item = tab.ele('xpath://div[@class="dropdown-account-switcher-list-item"]', timeout=10)
if not first_item:
print("找不到国家列表项")
return False
first_item.click()
time.sleep(1) # 等待国家列表展开
# 步骤4:点击目标国家
print(f"正在切换到国家:{country_name}")
target_country_xpath = f'//div[@class="dropdown-account-switcher-list-item dropdown-account-switcher-list-item-indented" and @title="{country_name}"]'
target_country = tab.ele(f'xpath:{target_country_xpath}', timeout=10)
if not target_country:
print(f"找不到目标国家:{country_name}")
return False
target_country.click()
# 步骤5:等待页面加载完成并验证切换结果
print(f"等待页面加载...")
# time.sleep(3) # 等待页面加载
self.tab.wait.doc_loaded()
# 再次检查当前国家
new_country_ele = tab.ele('xpath://div[@class="dropdown-account-switcher-header-label"]/span[last()]',
timeout=10)
if new_country_ele:
new_country = new_country_ele.text.strip()
if new_country == country_name:
print(f"国家切换成功:{new_country}")
return True
else:
print(f"国家切换失败,当前国家:{new_country},目标国家:{country_name}")
return False
else:
print("无法验证切换结果")
return False
except Exception as e:
print(f"切换国家时发生异常:{traceback.format_exc()}")
return False
def SwitchPage(self):
"""
切换至 管理所有库存页面
1、等待 //navigation-favorites-bar[@class="hydrated"] 出现
"""
navigation = self.tab.ele('xpath://navigation-favorites-bar[@class="hydrated"]')
navigation.wait.displayed(raise_err=False)
page_btn = navigation.sr('xpath://internal-fav-bar-links[@data-internal="navigation"]').sr(
'xpath://a[@data-page-id="ezdpc-gui-inventory-mons"]')
page_btn.wait.displayed(raise_err=False)
page_btn.click(timeout=5)
self.tab.wait.doc_loaded()
# 等待搜索框出现
search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group')
search_region.wait.displayed(raise_err=False)
def search(self, asin):
search_region = self.tab.ele('xpath://div[@id="searchBoxContainer"]//kat-input-group')
search_region.wait.displayed(raise_err=False)
time.sleep(0.6)
search_input = self.tab.ele("xpath://kat-input[contains(@class,'SearchBox-module__searchInput')]").sr(
'xpath://span[@class="container"]//input[@part="input"]')
search_input.input(asin)
for _ in range(3):
search_btn = self.tab.ele("xpath://kat-icon[@name='search']")
search_btn.click()
load_ele = self.tab.ele("xpath://div[contains(@class,'Loader-module__loader')]")
load_ele.wait.hidden(timeout=20)
time.sleep(1)
sku_ls = self.tab.eles("//div[@data-sku]")
return sku_ls
def del_action(self, sku_ele):
dropdown = sku_ele.ele('xpath:.//kat-dropdown-button[@variant="secondary"]')
dropdown.click()
time.sleep(1)
del_btn = dropdown.ele("xpath:.//button[@role='menuitem' and text()='删除商品信息']")
del_btn.wait.displayed(raise_err=False)
del_btn.click()
confirm_btn = self.tab.ele('xpath://kat-modal[@data-testid="action-modal"]//kat-button[@variant="primary"]')
confirm_btn.wait.displayed(raise_err=False)
confirm_btn.wait.enabled()
confirm_btn.click()
suc_alert = self.tab.ele("xpath://kat-alert[@variant='success']")
suc = suc_alert.wait.displayed(raise_err=False, timeout=5)
return suc
if __name__ == '__main__':
# 使用示例
user_info = {
"company": "rongchuang123",
"username": "自动化_Robot",
"password": "#20zsg25"
}
shop_name = "郭亚芳"
kill_process("v6")
# 创建驱动实例
driver = AmazoneDriver(user_info)
# 打开店铺并获取浏览器实例
browser = driver.open_shop(shop_name)
country = "西班牙"
asin = "Voanos"
sw_suc = driver.SwitchingCountries(country)
driver.SwitchPage()
sku_ls = driver.search(asin=asin)
print("查询结果有:", len(sku_ls))
for sku in sku_ls:
suc = driver.del_action(sku)
print(sku, "删除结果", suc)
+421
View File
@@ -0,0 +1,421 @@
import time
import traceback
import requests
from datetime import datetime
from typing import Dict, Any, List
from config import JSON_TASK_QUEUE, runing_task, runing_shop, DELETE_BRAND_API_BASE, ZN_COMPANY, ZN_USERNAME, ZN_PASSWORD
from amazon.del_brand import AmazoneDriver, kill_process
class TaskMonitor:
"""任务监控器:负责监控队列并执行品牌删除任务"""
def __init__(self):
"""初始化任务监控器"""
self.running = True
self.user_info = {
"company": ZN_COMPANY,
"username": ZN_USERNAME,
"password": ZN_PASSWORD
}
self.chunk_index = 1 # 当前处理的分块索引
def log(self, message: str, level: str = "INFO"):
"""日志输出
Args:
message: 日志消息
level: 日志级别
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] [{level}] {message}")
def start(self):
"""启动任务监控(阻塞式循环)"""
self.log("任务监控器启动,开始监听队列...")
while self.running:
try:
# 阻塞式获取任务,避免CPU空转
task_data = JSON_TASK_QUEUE.get(block=True, timeout=1)
# 检查任务类型
task_type = task_data.get("type", "")
if task_type != "delete-brand-run":
self.log(f"未知任务类型: {task_type},跳过", "WARNING")
continue
# 处理任务
self.log(f"接收到删除品牌任务,开始处理...")
self.process_task(task_data)
except Exception as e:
if "Empty" not in str(e): # 忽略队列为空的超时异常
self.log(f"任务处理异常: {traceback.format_exc()}", "ERROR")
time.sleep(0.1) # 短暂等待避免异常循环
def process_task(self, task_data: Dict[str, Any]):
"""处理单个任务
Args:
task_data: 任务数据
"""
try:
data = task_data.get("data", {})
task_id = data.get("taskId")
items = data.get("items", [])
if not task_id:
self.log("任务ID为空,跳过", "WARNING")
return
# 初始化任务状态
self.update_task_status(
task_id,
status="running",
start_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
total_shops=len(items),
processed_shops=0,
total_asins=sum(shop.get("totalRows", 0) for shop in items),
processed_asins=0,
success_count=0,
failed_count=0,
stop_requested=False # 暂停请求标志
)
self.log(f"开始处理任务 {task_id},共 {len(items)} 个店铺")
# 遍历处理每个店铺
for idx, shop_data in enumerate(items, 1):
shop_name = shop_data.get("shopName", "未知店铺")
self.log(f"[{idx}/{len(items)}] 开始处理店铺: {shop_name}")
try:
self.process_shop(shop_data, task_id)
# 更新已处理店铺数
if task_id in runing_task:
runing_task[task_id]["processed_shops"] += 1
except Exception as e:
self.log(f"处理店铺 {shop_name} 失败: {str(e)}", "ERROR")
self.log(traceback.format_exc(), "ERROR")
# 检查任务最终状态
if task_id in runing_task and runing_task[task_id].get("stop_requested", False):
self.update_task_status(task_id, status="stopped")
self.log(f"任务 {task_id} 已被暂停!")
else:
self.update_task_status(task_id, status="completed")
self.log(f"任务 {task_id} 处理完成!")
except Exception as e:
self.log(f"任务处理失败: {traceback.format_exc()}", "ERROR")
if task_id:
self.update_task_status(task_id, status="failed", error=str(e))
def process_shop(self, shop_data: Dict[str, Any], task_id: int):
"""处理单个店铺(包含重试逻辑)
Args:
shop_data: 店铺数据
task_id: 任务ID
"""
shop_name = shop_data.get("shopName", "未知店铺")
result_id = shop_data.get("resultId")
countries = shop_data.get("countries", [])
if not countries:
self.log(f"店铺 {shop_name} 没有国家数据,跳过", "WARNING")
return
# 更新当前处理的店铺
self.update_task_status(task_id, current_shop=shop_name)
# 将店铺添加到正在执行中的店铺列表
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
runing_shop[shop_name] = start_time
self.log(f"店铺 {shop_name} 已添加到执行列表,开始时间: {start_time}")
# 店铺打开重试最多3次
driver = None
browser = None
max_retries = 3
for retry in range(max_retries):
try:
self.log(f"尝试打开店铺 {shop_name} (第 {retry + 1}/{max_retries} 次)")
# 如果不是第一次尝试,先杀进程
if retry > 0:
self.log("重试前先杀掉浏览器进程...")
kill_process("v6")
time.sleep(2)
# 创建驱动并打开店铺
driver = AmazoneDriver(self.user_info)
browser = driver.open_shop(shop_name)
if browser and browser != "店铺不存在":
self.log(f"成功打开店铺 {shop_name}")
break
else:
self.log(f"打开店铺失败: {browser}", "WARNING")
driver = None
except Exception as e:
self.log(f"打开店铺异常: {str(e)}", "ERROR")
driver = None
# 如果还有重试机会,等待后继续
if retry < max_retries - 1:
time.sleep(3)
# 检查是否成功打开
if not driver or not browser or browser == "店铺不存在":
self.log(f"店铺 {shop_name} 打开失败,已重试 {max_retries} 次,跳过该店铺", "ERROR")
return
try:
# 处理每个国家
for country_data in countries:
# 检查是否收到暂停请求
if task_id in runing_task and runing_task[task_id].get("stop_requested", False):
self.log(f"检测到任务 {task_id} 的暂停请求,停止处理国家", "WARNING")
break # 跳出循环,进入finally关闭店铺
try:
self.process_country(driver, country_data, task_id, result_id, shop_data)
except Exception as e:
country_name = country_data.get("country", "未知")
self.log(f"处理国家 {country_name} 失败: {str(e)}", "ERROR")
self.log(traceback.format_exc(), "ERROR")
finally:
# 关闭店铺
try:
if driver:
self.log(f"关闭店铺 {shop_name}")
driver.close_store()
time.sleep(2)
except Exception as e:
self.log(f"关闭店铺失败: {str(e)}", "WARNING")
# 从正在执行中的店铺列表中移除
if shop_name in runing_shop:
del runing_shop[shop_name]
self.log(f"店铺 {shop_name} 已从执行列表中移除")
def process_country(self, driver: AmazoneDriver, country_data: Dict[str, Any],
task_id: int, result_id: int, shop_data: Dict[str, Any]):
"""处理单个国家的所有ASIN
Args:
driver: 亚马逊驱动实例
country_data: 国家数据
task_id: 任务ID
result_id: 结果ID
shop_data: 店铺数据
"""
country = country_data.get("country", "未知")
items = country_data.get("items", [])
self.log(f"开始处理国家: {country},共 {len(items)} 个ASIN")
self.update_task_status(task_id, current_country=country)
# 切换国家
try:
switch_success = driver.SwitchingCountries(country)
if not switch_success:
self.log(f"切换到国家 {country} 失败,跳过该国家", "ERROR")
return
except Exception as e:
self.log(f"切换国家 {country} 异常: {str(e)}", "ERROR")
return
# 切换到库存管理页面
try:
driver.SwitchPage()
self.log(f"已切换到库存管理页面")
except Exception as e:
self.log(f"切换页面失败: {str(e)}", "ERROR")
return
# 处理每个ASIN
file_key = shop_data.get("fileKey", "")
source_filename = shop_data.get("sourceFilename", "")
total_rows = shop_data.get("totalRows", 0)
for idx, asin_item in enumerate(items, 1):
# 检查是否收到暂停请求
if task_id in runing_task and runing_task[task_id].get("stop_requested", False):
self.log(f"检测到任务 {task_id} 的暂停请求,停止处理", "WARNING")
return # 返回到上层,会触发店铺关闭
try:
self.log(f"[{idx}/{len(items)}] 处理ASIN: {asin_item.get('asin', '')}")
self.process_asin(driver, asin_item, country, task_id, result_id,
file_key, source_filename, total_rows, idx)
except Exception as e:
asin = asin_item.get("asin", "未知")
self.log(f"处理ASIN {asin} 失败: {str(e)}", "ERROR")
# 继续处理下一个ASIN
def process_asin(self, driver: AmazoneDriver, asin_item: Dict[str, Any],
country: str, task_id: int, result_id: int, file_key: str,
source_filename: str, total_rows: int):
"""处理单个ASIN并回传结果
Args:
driver: 亚马逊驱动实例
asin_item: ASIN数据项
country: 国家名称
task_id: 任务ID
result_id: 结果ID
file_key: 文件KEY
source_filename: 源文件名
total_rows: 总行数
chunk_index: 当前处理索引
"""
asin = asin_item.get("asin", "")
row_index = asin_item.get("rowIndex", 0)
# 更新当前处理的ASIN
self.update_task_status(task_id, current_asin=asin)
status = "失败"
try:
# 搜索ASIN
sku_ls = driver.search(asin=asin)
self.log(f"搜索到 {len(sku_ls)} 个SKU")
if len(sku_ls) == 0:
status = "查询不到"
self.log(f"ASIN {asin} 未找到商品", "WARNING")
else:
# 删除所有找到的SKU
success_count = 0
for sku in sku_ls:
try:
suc = driver.del_action(sku)
if suc:
success_count += 1
self.log(f"SKU 删除成功")
else:
self.log(f"SKU 删除失败", "WARNING")
except Exception as e:
self.log(f"删除SKU异常: {str(e)}", "ERROR")
if success_count > 0:
status = "成功"
self.log(f"ASIN {asin} 删除成功 ({success_count}/{len(sku_ls)})")
# 更新成功计数
if task_id in runing_task:
runing_task[task_id]["success_count"] += 1
else:
status = "失败"
self.log(f"ASIN {asin} 所有SKU删除失败", "ERROR")
# 更新失败计数
if task_id in runing_task:
runing_task[task_id]["failed_count"] += 1
except Exception as e:
status = "删除异常"
self.log(f"处理ASIN {asin} 异常: {str(e)}", "ERROR")
# 更新失败计数
if task_id in runing_task:
runing_task[task_id]["failed_count"] += 1
# 更新已处理ASIN计数
if task_id in runing_task:
runing_task[task_id]["processed_asins"] += 1
# 回传结果到API
try:
payload = {
"submissionId": "",
"files": [{
"fileKey": file_key,
"sourceFilename": source_filename,
"chunkIndex": self.chunk_index,
"chunkTotal": total_rows,
"processedRows": self.chunk_index,
"totalRows": total_rows,
"currentCountry": country,
"currentAsin": asin,
"countries": [{
"country": country,
"items": [{
"asin": asin,
"status": status
}]
}]
}]
}
self.post_result(task_id, payload)
self.log(f"ASIN {asin} 结果已回传,状态: {status}")
except Exception as e:
self.log(f"回传结果失败: {str(e)}", "ERROR")
def post_result(self, task_id: int, payload: Dict[str, Any]):
"""回传结果到API
Args:
task_id: 任务ID
payload: 结果数据
"""
url = f"{DELETE_BRAND_API_BASE}/newApi/api/delete-brand/tasks/{task_id}/result"
try:
response = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=30,
verify=False # 忽略SSL证书验证
)
if response.status_code == 200:
self.log(f"结果回传成功: {url}")
else:
self.log(f"结果回传失败,状态码: {response.status_code}", "WARNING")
except Exception as e:
self.log(f"调用API异常: {str(e)}", "ERROR")
def update_task_status(self, task_id: int, **kwargs):
"""更新任务状态
Args:
task_id: 任务ID
**kwargs: 要更新的字段
"""
if task_id not in runing_task:
runing_task[task_id] = {}
runing_task[task_id].update(kwargs)
def stop(self):
"""停止监控"""
self.running = False
self.log("任务监控器已停止")
def main():
"""主函数:启动任务监控"""
# 创建并启动任务监控器
monitor = TaskMonitor()
try:
monitor.start()
except KeyboardInterrupt:
monitor.log("接收到中断信号,正在停止...")
monitor.stop()
except Exception as e:
monitor.log(f"监控器异常退出: {traceback.format_exc()}", "ERROR")
if __name__ == "__main__":
main()
+14 -2
View File
@@ -15,13 +15,24 @@ from blueprints.main import main_bp
from blueprints.admin import admin_bp from blueprints.admin import admin_bp
from blueprints.image import image_bp from blueprints.image import image_bp
from blueprints.brand import brand_bp from blueprints.brand import brand_bp
from blueprints.communication import communication_bp
def create_app(): def create_app():
app = Flask(__name__, template_folder=BASE_DIR, static_folder=BASE_DIR) app = Flask(__name__, template_folder=BASE_DIR, static_folder=BASE_DIR)
CORS(app) frontend_origin = os.environ.get('FRONTEND_ORIGIN', '*')
app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(32)) cors_origins = frontend_origin if frontend_origin != '*' else '*'
CORS(
app,
supports_credentials=True,
resources={r"/api/*": {"origins": cors_origins}, r"/login": {"origins": cors_origins}},
)
# 生产环境必须通过环境变量注入固定 SECRET_KEY;否则服务重启会使旧会话失效。
app.secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key-change-me')
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = os.environ.get('SESSION_COOKIE_SAMESITE', 'Lax')
app.config['SESSION_COOKIE_SECURE'] = os.environ.get('SESSION_COOKIE_SECURE', '0') == '1'
# 注册蓝图(不设 url_prefix,保持原有 URL 路径不变,前端无需改动) # 注册蓝图(不设 url_prefix,保持原有 URL 路径不变,前端无需改动)
app.register_blueprint(auth_bp) app.register_blueprint(auth_bp)
@@ -29,6 +40,7 @@ def create_app():
app.register_blueprint(admin_bp) app.register_blueprint(admin_bp)
app.register_blueprint(image_bp) app.register_blueprint(image_bp)
app.register_blueprint(brand_bp) app.register_blueprint(brand_bp)
app.register_blueprint(communication_bp)
return app return app
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
+12 -8
View File
@@ -187,8 +187,8 @@ def _run_brand_single(taskid,brand_ls, fileUrl,strategy,totalLines,chunkTotal,ch
# "invalidBrands": invalidBrands,"queryFailedBrands": queryFailedBrands # "invalidBrands": invalidBrands,"queryFailedBrands": queryFailedBrands
# }]}) # }]})
json=data) json=data)
print(data) # print(data)
print(taskid,brand_ls, fileUrl) # print(taskid,brand_ls, fileUrl)
print("提交结果",data,"\n-->",resp.text) print("提交结果",data,"\n-->",resp.text)
return True return True
@@ -242,9 +242,11 @@ def _background_brand_task(task_id,data):
fileUrl = file_data.get("fileUrl") fileUrl = file_data.get("fileUrl")
if not brand_ls: if not brand_ls:
continue continue
for i in range(0, len(brand_ls), 5): file_chunks = [brand_ls[i:i + 5] for i in range(0, len(brand_ls), 5)]
chunk = brand_ls[i:i + 5] chunk_total = len(file_chunks)
tasks.append((chunk, fileUrl)) total_lines = len(brand_ls)
for chunk_index, chunk in enumerate(file_chunks, start=1):
tasks.append((chunk, fileUrl, total_lines, chunk_total, chunk_index))
if tasks: if tasks:
max_workers = min(8, len(tasks)) max_workers = min(8, len(tasks))
@@ -253,8 +255,8 @@ def _background_brand_task(task_id,data):
_push_task_event(task_id, {'status': 'cancelled'}) _push_task_event(task_id, {'status': 'cancelled'})
return return
futures = [ futures = [
executor.submit(_run_brand_single, task_id, chunk, file_url, strategy,len(brand_ls),len(tasks),chunkIndex+1) executor.submit(_run_brand_single, task_id, chunk, file_url, strategy, total_lines, chunk_total, chunk_index)
for chunkIndex,(chunk, file_url) in enumerate(tasks) for chunk, file_url, total_lines, chunk_total, chunk_index in tasks
] ]
for future in as_completed(futures): for future in as_completed(futures):
if _is_task_cancelled(task_id): if _is_task_cancelled(task_id):
@@ -362,7 +364,7 @@ def api_brand_expand_folder_recursive():
@brand_bp.route('/api/brand/run', methods=['POST']) @brand_bp.route('/api/brand/run', methods=['POST'])
@login_required # @login_required
def api_brand_run(): def api_brand_run():
"""立即运行:创建任务并后台执行,立即返回 task_id,前端可轮询进度与取消""" """立即运行:创建任务并后台执行,立即返回 task_id,前端可轮询进度与取消"""
try: try:
@@ -400,6 +402,7 @@ def api_brand_run():
"content-type":"application/json", "content-type":"application/json",
},data=json.dumps({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""})) },data=json.dumps({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""}))
print({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""}) print({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""})
print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id}")
resp_data = resp.json() resp_data = resp.json()
# print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id} 返回:",resp_data,"状态:",resp.status_code) # print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id} 返回:",resp_data,"状态:",resp.status_code)
if resp_data.get("success"): if resp_data.get("success"):
@@ -408,6 +411,7 @@ def api_brand_run():
threading.Thread(target=_background_brand_task, args=(task_id,data), daemon=True).start() threading.Thread(target=_background_brand_task, args=(task_id,data), daemon=True).start()
return jsonify({'success': True, 'task_id': task_id}) return jsonify({'success': True, 'task_id': task_id})
else: else:
print(resp_data)
return jsonify({'success': False, 'error': "请求接口失败"}), 500 return jsonify({'success': False, 'error': "请求接口失败"}), 500
except Exception as e: except Exception as e:
+726
View File
@@ -0,0 +1,726 @@
"""
品牌爬虫蓝图:展开文件夹、运行任务、任务列表/详情、下载结果
"""
import os
import json
import threading
import traceback
import zipfile
import io
import time
import requests
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
from flask import Blueprint, request, jsonify, session, send_file, redirect, Response
from app_common import get_db, login_required, BASE_DIR
from config import bucket_path,JAVA_API_BASE
from brand_spider.main import single_file_handle, TaskCancelledError
brand_bp = Blueprint('brand', __name__)
BRAND_OUTPUT_DIR = os.path.join(BASE_DIR, 'brand_output')
OSS_PREFIX = "brand_results"
# 任务完成时推送给前端的 SSE 队列:task_id -> [Queue, ...]
_task_event_queues = {}
_task_event_lock = threading.Lock()
# 任务行级进度(当前处理文件的行数/总行数),仅存内存,不落库:
# task_id -> {
# 'file_index': int, # 当前处理第几个文件
# 'file_total': int, # 总文件数
# 'file_path': str, # 当前文件路径
# 'current_line': int, # 当前行号(或当前品牌序号)
# 'total_lines': int, # 总行数(或总品牌数)
# }
_task_line_progress = {}
_task_line_progress_lock = threading.Lock()
_cancelled_brand_tasks = set()
_cancelled_brand_tasks_lock = threading.Lock()
def _mark_task_cancelled(task_id):
with _cancelled_brand_tasks_lock:
_cancelled_brand_tasks.add(task_id)
def _is_task_cancelled(task_id):
with _cancelled_brand_tasks_lock:
return task_id in _cancelled_brand_tasks
def _get_uid_from_request_headers():
"""
从请求头读取 uid。
前端会在 headers 里携带 uid,用于确定本次请求的归属用户。
"""
uid = request.headers.get('uid')
if uid is None:
return None
uid = str(uid).strip()
if not uid:
return None
try:
return int(uid)
except Exception:
return None
def _resolve_user_id():
"""
优先使用请求头 uid;没有请求头 uid 时回退到 session['user_id']。
若二者同时存在但不一致,则视为无效请求并返回 None。
"""
req_uid = _get_uid_from_request_headers()
if req_uid is not None:
sess_uid = session.get('user_id')
if sess_uid is not None:
try:
if int(sess_uid) != int(req_uid):
return None
except Exception:
if str(sess_uid) != str(req_uid):
return None
return req_uid
return session.get('user_id')
def _get_user_id_or_error():
user_id = _resolve_user_id()
if not user_id:
return None, (jsonify({'success': False, 'error': '未登录或缺少uid'}), 401)
try:
return int(user_id), None
except Exception:
return None, (jsonify({'success': False, 'error': 'uid无效'}), 400)
def _push_task_event(task_id, event):
"""向订阅了该任务的所有 SSE 连接推送事件,并移除该任务的队列列表。
同时清理内存中的行级进度,不通过数据库中转行级进度。"""
with _task_event_lock:
queues = _task_event_queues.pop(task_id, [])
for q in queues:
try:
q.put_nowait(event)
except Exception:
pass
# 任务进入终态时,顺便清理行级进度缓存
with _task_line_progress_lock:
_task_line_progress.pop(task_id, None)
status = (event or {}).get('status') if isinstance(event, dict) else None
if status in ('success', 'failed', 'cancelled'):
with _cancelled_brand_tasks_lock:
_cancelled_brand_tasks.discard(task_id)
def _expand_folder_xlsx(folder_path):
"""返回文件夹下所有 .xlsx 文件的绝对路径列表"""
if not folder_path or not os.path.isdir(folder_path):
return []
paths = []
for name in os.listdir(folder_path):
if name.endswith('.xlsx') or name.endswith('.XLSX'):
paths.append(os.path.normpath(os.path.join(folder_path, name)))
return paths
def _upload_local_xlsx_to_oss(local_path, user_id):
"""将本地 xlsx 文件上传到 OSS,返回 (url, None) 或 (None, error_message)。"""
if not local_path or not os.path.isfile(local_path):
return None, "文件不存在"
try:
from ali_oss import upload_file as oss_upload_file
except ImportError:
return None, "OSS 模块未配置"
base = os.path.basename(local_path)
safe_base = "".join(c if c.isalnum() or c in '-_.' else '_' for c in base)
if not safe_base.endswith('.xlsx'):
safe_base = safe_base + '.xlsx'
key = f"{bucket_path}brand_input/{user_id}/{int(time.time() * 1000)}/{safe_base}"
try:
with open(local_path, "rb") as f:
content = f.read()
url = oss_upload_file(content, key)
return url, None
except Exception as e:
return None, str(e)
def _run_brand_single(taskid,brand_ls, fileUrl,strategy,totalLines,chunkTotal,chunkIndex):
""""""
invalidBrands = [] # 不符合品牌的数据
queryFailedBrands = [] # 查询失败的数据
keptRows = []
for brand in brand_ls:
if _is_task_cancelled(taskid):
raise TaskCancelledError("任务已取消")
faild_data,query_faild_data = single_file_handle(brand,strategy)
invalidBrands.extend(faild_data)
queryFailedBrands.extend(query_faild_data)
if len(faild_data) == 0 and len(query_faild_data) == 0:
keptRows.append(brand)
data = { "strategy": strategy ,
"files": [
{
"fileUrl": fileUrl,
"originalFilename": "",
"relativePath": "",
"mainSheetName": "",
"chunkIndex": chunkIndex,
"chunkTotal": chunkTotal,
"totalLines": totalLines,
"keptRows": keptRows,
"invalidBrands": invalidBrands,
"queryFailedBrands": queryFailedBrands
}
]
}
resp = requests.post(f"{JAVA_API_BASE}/api/brand/tasks/{taskid}/result",headers={"accept":"application/json"},
# json={ "strategy": strategy ,
# "files": [
# { "fileUrl": fileUrl,"originalFilename": "","relativePath": "",
# "mainSheetName": "","columns": [],"keptRows": [],
# "invalidBrands": invalidBrands,"queryFailedBrands": queryFailedBrands
# }]})
json=data)
# print(data)
# print(taskid,brand_ls, fileUrl)
print("提交结果",data,"\n-->",resp.text)
return True
def _background_brand_task(task_id,data):
"""
后台执行爬虫任务
参数示例:
data : {
"taskId": 348,
"strategy": "Terms",
"files": [
{
"fileIndex": 1,
"fileUrl": "ab8cce4878754bfd89b4cd3ed20e1395",
"originalFilename": "品牌样例.xlsx",
"relativePath": "店铺A/品牌样例.xlsx",
"sheetName": "Sheet1",
"columns": [
"品牌",
"ASIH",
"状态",
"时间"
],
"rows": [
{
"品牌": "YQAUTEC",
"ASIH": "B0F28NZ752",
"状态": "",
"时间": "",
"__rowIndex": 2
}
],
"uniqueBrands": [
"YQAUTEC"
]
}
]
}
"""
try:
file_ls = data.get("files")
strategy = data.get("strategy")
if not isinstance(file_ls, list):
file_ls = []
tasks = []
for file_data in file_ls:
rows = file_data.get("rows") or []
brand_ls = [i.get("品牌") for i in rows if i.get("品牌")]
fileUrl = file_data.get("fileUrl")
if not brand_ls:
continue
for i in range(0, len(brand_ls), 5):
chunk = brand_ls[i:i + 5]
tasks.append((chunk, fileUrl))
if tasks:
max_workers = min(8, len(tasks))
with ThreadPoolExecutor(max_workers=max_workers) as executor:
if _is_task_cancelled(task_id):
_push_task_event(task_id, {'status': 'cancelled'})
return
futures = [
executor.submit(_run_brand_single, task_id, chunk, file_url, strategy,len(brand_ls),len(tasks),chunkIndex+1)
for chunkIndex,(chunk, file_url) in enumerate(tasks)
]
for future in as_completed(futures):
if _is_task_cancelled(task_id):
for f in futures:
f.cancel()
_push_task_event(task_id, {'status': 'cancelled'})
return
future.result()
_push_task_event(task_id, {'status': 'success'})
except Exception as e:
print("执行出错",traceback.format_exc())
_push_task_event(task_id, {'status': 'failed', 'error_message': str(e)})
print("执行完成")
def _parse_json(val, default=None):
if val is None:
return default if default is not None else []
if isinstance(val, (list, dict)):
return val
try:
return json.loads(val)
except Exception:
return default if default is not None else []
def _is_url(s):
if not isinstance(s, str) or not s.strip():
return False
return s.strip().startswith('http://') or s.strip().startswith('https://')
def _normalize_result_paths(raw):
"""
将 result_paths 规范化为 (url_list, zip_url)。
支持旧格式 list 或新格式 dict {"urls": [...], "zip_url": "..."}。
"""
if not raw:
return [], None
if isinstance(raw, dict):
urls = raw.get('urls') or []
if not isinstance(urls, list):
urls = []
zip_url = raw.get('zip_url')
if zip_url and not isinstance(zip_url, str):
zip_url = None
return urls, zip_url
if isinstance(raw, list):
return raw, None
return [], None
@brand_bp.route('/api/brand/expand-folder', methods=['POST'])
@login_required
def api_brand_expand_folder():
"""展开文件夹,返回其下所有 .xlsx 文件路径列表"""
try:
_, err = _get_user_id_or_error()
if err:
return err
data = request.get_json() or {}
folder = (data.get('folder') or '').strip()
if not folder:
return jsonify({'success': False, 'error': '请提供 folder 路径'}), 400
paths = _expand_folder_xlsx(folder)
return jsonify({'success': True, 'paths': paths})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
def _expand_folder_xlsx_recursive_items(folder_path):
"""返回文件夹下所有 .xlsx 文件的绝对路径和相对路径列表(递归)"""
if not folder_path or not os.path.isdir(folder_path):
return []
items = []
root = os.path.normpath(folder_path)
for current_root, _, filenames in os.walk(root):
for name in filenames:
if not (name.endswith('.xlsx') or name.endswith('.XLSX')):
continue
absolute_path = os.path.normpath(os.path.join(current_root, name))
relative_path = os.path.relpath(absolute_path, root).replace('\\', '/')
items.append({
'absolutePath': absolute_path,
'relativePath': relative_path,
})
items.sort(key=lambda item: item['relativePath'])
return items
@brand_bp.route('/api/brand/expand-folder-recursive', methods=['POST'])
@login_required
def api_brand_expand_folder_recursive():
"""递归展开文件夹,返回 .xlsx 文件绝对路径及相对路径列表"""
try:
_, err = _get_user_id_or_error()
if err:
return err
data = request.get_json() or {}
folder = (data.get('folder') or '').strip()
if not folder:
return jsonify({'success': False, 'error': '请提供 folder 路径'}), 400
items = _expand_folder_xlsx_recursive_items(folder)
return jsonify({'success': True, 'items': items})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/run', methods=['POST'])
# @login_required
def api_brand_run():
"""立即运行:创建任务并后台执行,立即返回 task_id,前端可轮询进度与取消"""
try:
data = request.get_json() or {}
paths = data.get('paths') or []
# task_type: 1=立即执行,2=添加任务;此接口默认 1
try:
task_type = int(data.get('task_type') or 1)
except Exception:
task_type = 1
if task_type not in (1, 2):
task_type = 1
strategy = (data.get('strategy') or 'Terms').strip()
if strategy not in ('Terms', 'Simple'):
strategy = 'Terms'
if not isinstance(paths, list):
paths = []
paths = [p.strip() for p in paths if p and isinstance(p, str) and os.path.isfile(p.strip())]
if not paths:
return jsonify({'success': False, 'error': '没有有效的 xlsx 文件路径'}), 400
# 先上传到 OSS,获取链接再入库
user_id, err = _get_user_id_or_error()
if err:
return err
urls = []
for p in paths:
url, err = _upload_local_xlsx_to_oss(p, user_id)
if err:
return jsonify({'success': False, 'error': f'上传文件失败: {os.path.basename(p)} - {err}'}), 500
base_name = os.path.basename(p)
urls.append({"fileUrl": url,"originalFilename": base_name,"relativePath": p })
# 请求提交
resp = requests.post(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id}",headers={
"content-type":"application/json",
},data=json.dumps({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""}))
print({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""})
print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id}")
resp_data = resp.json()
# print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id} 返回:",resp_data,"状态:",resp.status_code)
if resp_data.get("success"):
task_id = resp_data.get("data").get("taskId")
data = resp_data.get("data")
threading.Thread(target=_background_brand_task, args=(task_id,data), daemon=True).start()
return jsonify({'success': True, 'task_id': task_id})
else:
print(resp_data)
return jsonify({'success': False, 'error': "请求接口失败"}), 500
except Exception as e:
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/tasks', methods=['GET', 'POST'])
# @login_required
def api_brand_tasks():
"""GET: 获取当前用户的任务列表;POST: 添加任务(后台执行)"""
if request.method == 'GET':
try:
user_id, err = _get_user_id_or_error()
if err:
return err
resp = requests.get(f"{JAVA_API_BASE}/api/brand/tasks", params={
"userId": user_id
})
resp_data = resp.json()
print("获取列表",resp.text)
if resp_data.get("success"):
items = resp_data.get("data").get("items")
return jsonify({'success': True, 'items': items})
return jsonify({'success': True, 'items': []})
except Exception as e:
traceback.print_exc()
print("获取列表失败",e)
return jsonify({'success': False, 'error': str(e)}), 500
# POST
try:
data = request.get_json() or {}
paths = data.get('paths') or []
# task_type: 1=立即执行,2=添加任务;此接口默认 2
try:
task_type = int(data.get('task_type') or 2)
except Exception:
task_type = 2
if task_type not in (1, 2):
task_type = 2
strategy = (data.get('strategy') or 'Terms').strip()
if strategy not in ('Terms', 'Simple'):
strategy = 'Terms'
if not isinstance(paths, list):
paths = []
paths = [p.strip() for p in paths if p and isinstance(p, str)]
if not paths:
return jsonify({'success': False, 'error': '请提供至少一个文件路径或链接'}), 400
user_id, err = _get_user_id_or_error()
if err:
return err
urls = []
for p in paths:
url, err = _upload_local_xlsx_to_oss(p, user_id)
if err:
return jsonify({'success': False, 'error': f'上传文件失败: {os.path.basename(p)} - {err}'}), 500
base_name = os.path.basename(p)
urls.append({"fileUrl": url, "originalFilename": base_name, "relativePath": p})
params = {
"userId": user_id
}
# resp = requests.post(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id}",headers={
# "content-type":"application/json",
# },data=json.dumps({ "files": urls, "strategy": strategy,"taskType": 1,"archiveName": ""}))
req_data = {"files": urls, "strategy": strategy, "taskType": 2, "archiveName": ""}
resp = requests.post(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id}", headers={"content-type": "application/json"},
data=json.dumps(req_data))
print(req_data)
# print(f"{JAVA_API_BASE}/api/brand/tasks?userId={user_id},返回", resp.text)
resp_data = resp.json()
if resp_data.get("success"):
task_id = resp_data.get("data").get("taskId")
data = resp_data.get("data")
return jsonify({'success': True, 'task_id': task_id})
return jsonify({'success': False, 'task_id': "请求异常"})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/tasks/<int:task_id>')
# @login_required
def api_brand_task_detail(task_id):
"""获取单个任务详情(用于轮询状态)"""
try:
resp = requests.get(f"{JAVA_API_BASE}/api/brand/tasks/{task_id}")
resp_data = resp.json()
if resp_data.get("success"):
task = resp_data["data"]["task"]
return jsonify({
'success': True,
'task': task
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/tasks/<int:task_id>/line-progress')
# @login_required
def api_brand_task_line_progress(task_id):
"""
获取任务的“当前文件行级进度”(当前行数/总行数)。
该信息仅存放在内存字典 _task_line_progress 中,不写入数据库。
"""
try:
resp = requests.get(f"{JAVA_API_BASE}/api/brand/tasks/{task_id}")
resp_data = resp.json()
if resp_data.get("success"):
if resp_data["data"]["line_progress"]["has_progress"]:
info = resp_data["data"]["line_progress"]["info"]
resp = {
'file_index': int(info.get('file_index') or 0),
'file_total': int(info.get('file_total') or 0),
'file_name': info.get("file_name",""),
'current_line': int(info.get('current_line') or 0),
'total_lines': int(info.get('total_lines') or 0),
}
return jsonify({'success': True, 'has_progress': True, 'info': resp})
raise RuntimeError("获取进度失败")
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/tasks/<int:task_id>/events')
# @login_required
def api_brand_task_events(task_id):
"""SSE:任务完成时后端主动推送事件,前端监听后隐藏进度条与取消按钮"""
user_id, err = _get_user_id_or_error()
if err:
return err
def _task_status_event():
conn = get_db()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT status, error_message FROM brand_crawl_tasks WHERE id = %s AND user_id = %s",
(task_id, user_id)
)
row = cur.fetchone()
finally:
conn.close()
if not row:
return None
st = (row.get('status') or '').lower()
if st in ('success', 'failed', 'cancelled'):
return {'status': st, 'error_message': (row.get('error_message') or '').strip() or None}
return None
# 若任务已处于终态,直接返回一条事件后结束
ev = _task_status_event()
if ev is not None:
def _one_shot():
yield "data: " + json.dumps(ev, ensure_ascii=False) + "\n\n"
return Response(
_one_shot(),
mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'}
)
# 否则注册队列,等待后台任务完成时推送
q = Queue()
with _task_event_lock:
_task_event_queues.setdefault(task_id, []).append(q)
def _stream():
try:
while True:
try:
event = q.get(timeout=20)
yield "data: " + json.dumps(event, ensure_ascii=False) + "\n\n"
return
except Empty:
yield ": keepalive\n\n"
finally:
with _task_event_lock:
lst = _task_event_queues.get(task_id, [])
if q in lst:
lst.remove(q)
if not lst:
_task_event_queues.pop(task_id, None)
return Response(
_stream(),
mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'}
)
@brand_bp.route('/api/brand/tasks/<int:task_id>/cancel', methods=['POST'])
# @login_required
def api_brand_task_cancel(task_id):
"""取消正在执行或等待中的任务(pending/running 均可取消)"""
try:
user_id, err = _get_user_id_or_error()
if err:
return err
resp = requests.post(
f"{JAVA_API_BASE}/api/brand/tasks/{task_id}/cancel",
headers={"accept": "application/json"},
timeout=20
)
try:
resp_data = resp.json()
except Exception:
return jsonify({'success': False, 'error': '取消接口返回非 JSON'}), 500
if not resp_data.get('success'):
return jsonify({'success': False, 'error': '第三方取消任务失败'}), 400
_mark_task_cancelled(task_id)
_push_task_event(task_id, {'status': 'cancelled'})
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/tasks/<int:task_id>', methods=['DELETE'])
@login_required
def api_brand_task_delete(task_id):
"""删除任务(仅限非 running 状态)"""
try:
user_id, err = _get_user_id_or_error()
if err:
return err
resp = requests.delete(
f"{JAVA_API_BASE}/api/brand/tasks/{task_id}",
headers={"accept": "application/json"},
timeout=20
)
try:
resp_data = resp.json()
except Exception:
return jsonify({'success': False, 'error': '取消接口返回非 JSON'}), 500
if not resp_data.get('success'):
return jsonify({'success': False, 'error': '第三方取消任务失败'}), 400
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@brand_bp.route('/api/brand/download/<int:task_id>')
@login_required
def api_brand_download(task_id):
"""下载任务结果:优先使用 OSS zip_url 重定向;否则本地/单链接/多链接按原逻辑处理"""
try:
user_id, err = _get_user_id_or_error()
if err:
return err
conn = get_db()
with conn.cursor() as cur:
cur.execute(
"SELECT result_paths FROM brand_crawl_tasks WHERE id = %s AND user_id = %s",
(task_id, user_id)
)
row = cur.fetchone()
conn.close()
if not row or not row.get('result_paths'):
return jsonify({'success': False, 'error': '无结果可下载'}), 404
raw = row['result_paths']
if isinstance(raw, str):
raw = _parse_json(raw)
url_list, zip_url = _normalize_result_paths(raw)
# 新格式:有 zip_url 直接重定向到 OSS
if zip_url and _is_url(zip_url):
return redirect(zip_url, code=302)
# 兼容旧格式:result_paths 可能为 list(本地路径或 url)
if not url_list and isinstance(raw, list):
url_list = raw
local_paths = [p for p in url_list if isinstance(p, str) and not _is_url(p) and os.path.isfile(p)]
url_paths = [p.strip() for p in url_list if isinstance(p, str) and _is_url(p)]
if len(url_paths) == 1 and not local_paths:
return redirect(url_paths[0], code=302)
if len(local_paths) == 1 and not url_paths:
return send_file(
local_paths[0],
as_attachment=True,
download_name=os.path.basename(local_paths[0])
)
if local_paths or url_paths:
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
for p in local_paths:
zf.write(p, os.path.basename(p))
for url in url_paths:
try:
import requests as req
r = req.get(url, timeout=30, stream=True)
r.raise_for_status()
name = os.path.basename(urlparse(url).path) or ('file_%s' % (url_paths.index(url)))
if not name or name == 'file_%s' % url_paths.index(url):
name = 'download_%s' % url_paths.index(url)
zf.writestr(name, r.content)
except Exception:
pass
buf.seek(0)
return send_file(
buf,
mimetype='application/zip',
as_attachment=True,
download_name='brand_task_%s.zip' % task_id
)
return jsonify({'success': False, 'error': '结果文件不存在或链接不可用'}), 404
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
+82
View File
@@ -0,0 +1,82 @@
import threading
import time
from queue import Empty, Full
from flask import Blueprint, jsonify, request
from config import JSON_TASK_QUEUE,runing_task
communication_bp = Blueprint('communication', __name__)
_del_brand_cache = {}
_del_brand_cache_lock = threading.Lock()
_latest_del_brand_item = None
_latest_del_brand_ts = 0.0
def _resolve_request_id():
rid = request.args.get('id')
if rid is not None and str(rid).strip() != '':
return str(rid)
if request.method == 'POST':
body = request.get_json(silent=True) or {}
rid = body.get('id')
if rid is not None and str(rid).strip() != '':
return str(rid)
return None
@communication_bp.route('/api/amazon/del_brand', methods=['GET', 'POST'])
def del_brand():
"""返回队列中的一个元素;同一 id 重复请求返回已缓存的同一元素;2分钟内不同 id 也返回最近元素。"""
global _latest_del_brand_item, _latest_del_brand_ts
request_id = _resolve_request_id()
if not request_id:
return jsonify({'success': False, 'message': '缺少参数 id', 'data': None}), 400
with _del_brand_cache_lock:
if request_id in _del_brand_cache:
item = _del_brand_cache[request_id]
print("【删除品牌】缓存命中", request_id, item)
return jsonify({'success': True, 'data': item})
if _latest_del_brand_item is not None and (time.time() - _latest_del_brand_ts) <= 120:
_del_brand_cache[request_id] = _latest_del_brand_item
print("【删除品牌】2分钟窗口命中", request_id, _latest_del_brand_item)
return jsonify({'success': True, 'data': _latest_del_brand_item})
try:
item = JSON_TASK_QUEUE.get_nowait()
except Empty:
print("队列为空")
return jsonify({'success': False, 'message': '队列为空', 'data': None})
with _del_brand_cache_lock:
if request_id in _del_brand_cache:
try:
JSON_TASK_QUEUE.put_nowait(item)
except Full:
print("【删除品牌】队列已满,无法归还重复拉取的任务")
item = _del_brand_cache[request_id]
print("【删除品牌】并发归并", request_id, item)
return jsonify({'success': True, 'data': item})
_del_brand_cache[request_id] = item
_latest_del_brand_item = item
_latest_del_brand_ts = time.time()
print("【删除品牌】返回任务数据", item)
return jsonify({'success': True, 'data': item})
@communication_bp.route('/api/amazon/get_all_detail', methods=['GET', 'POST'])
def get_all_detail():
"""获取正在执行的删除品牌任务详情"""
request_id = _resolve_request_id()
if not request_id: #如果没有提供 id 参数,直接返回所有正在执行的任务详情
return jsonify({'success': True, 'data': runing_task})
task_info = runing_task.get(request_id)
if not task_info:
return jsonify({'success': False, 'message': '任务不存在', 'data': None})
return jsonify({'success': True, 'data': task_info})
+8
View File
@@ -110,6 +110,14 @@ def proxy(path):
if key.lower() in ['host', 'content-length', 'connection']: if key.lower() in ['host', 'content-length', 'connection']:
continue continue
headers[key] = value headers[key] = value
try:
print("=============================")
print("target_url:",target_url)
print("params:",params)
print("data:",request.get_data())
print("=============================")
except Exception as e:
print("打印失败",e)
try: try:
# 使用流式请求 # 使用流式请求
Binary file not shown.
+48 -1
View File
@@ -5,6 +5,7 @@ STITCH_WORKFLOW_ID = "7608813873483300907"
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from queue import Queue
load_dotenv() load_dotenv()
_base_url = os.getenv("base_url","http://159.75.121.33:15124") _base_url = os.getenv("base_url","http://159.75.121.33:15124")
@@ -19,6 +20,14 @@ proxy_mode = int(os.getenv("proxy_mode",1))
client_name=os.getenv("client_name") + ".exe" client_name=os.getenv("client_name") + ".exe"
JAVA_API_BASE = os.getenv("java_api_base", "http://127.0.0.1:18080") JAVA_API_BASE = os.getenv("java_api_base", "http://127.0.0.1:18080")
# 紫鸟浏览器配置
ZN_COMPANY = os.getenv("zn_company", "")
ZN_USERNAME = os.getenv("zn_username", "")
ZN_PASSWORD = os.getenv("zn_password", "")
# 删除品牌API配置
DELETE_BRAND_API_BASE = os.getenv("DELETE_BRAND_API_BASE", JAVA_API_BASE)
cache_path = "./user_data" cache_path = "./user_data"
@@ -38,11 +47,49 @@ os.environ['OSS_ACCESS_KEY_SECRET'] = accessKeySecret
os.environ['SECRET_KEY'] = "ddffc7c1d02121d9554d7b080b2511b6" os.environ['SECRET_KEY'] = "ddffc7c1d02121d9554d7b080b2511b6"
debug = False debug = True
version = "1.0.13" version = "1.0.13"
APP_UPDATE_URL = f"{_base_url}/api/version/latest" # 检测更新接口地址,返回 { "file_url": "...", "version": "x.x.x" } APP_UPDATE_URL = f"{_base_url}/api/version/latest" # 检测更新接口地址,返回 { "file_url": "...", "version": "x.x.x" }
os.environ['APP_VERSION'] = version os.environ['APP_VERSION'] = version
os.environ['APP_UPDATE_URL'] = APP_UPDATE_URL os.environ['APP_UPDATE_URL'] = APP_UPDATE_URL
# 队列
JSON_TASK_QUEUE = Queue()
#删除品牌,正在执行中的任务
runing_task = {
}
# 正在执行中的店铺
runing_shop = {}
#
# runing_task = {
# "497": {
# "status": "running", # running/completed/failed
# "start_time": "2026-04-01 10:00:00",
# "stop_requested": False,
# "current_shop": "魏振峰",
# "current_country": "德国",
# "current_asin": "B0D451RQRG",
# "total_shops": 1,
# "processed_shops": 0,
# "total_asins": 14,
# "processed_asins": 3,
# "success_count": 2,
# "failed_count": 1
# }
# }
+58 -92
View File
@@ -1,10 +1,11 @@
""" """
基于 pywebview 实现的跨平台 UI,需先登录方可使用 基于 pywebview 实现的跨平台 UI,需先登录方可使用
""" """
from config import cache_path,debug,version,JAVA_API_BASE from config import cache_path,debug,version,JAVA_API_BASE,JSON_TASK_QUEUE,runing_task,runing_shop
import datetime import datetime
import json import json
import sys import sys
import shutil
import os import os
os.makedirs(cache_path,exist_ok=True) os.makedirs(cache_path,exist_ok=True)
if not debug: if not debug:
@@ -16,11 +17,19 @@ import webview
import threading import threading
import time import time
import requests import requests
import subprocess
with open("version.txt","w",encoding="utf-8") as file: with open("version.txt","w",encoding="utf-8") as file:
file.write(json.dumps({"version":version})) file.write(json.dumps({"version":version}))
print(f"""
========================================================
版本: {version}
========================================================
""")
# 获取当前脚本所在目录 # 获取当前脚本所在目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -170,7 +179,6 @@ class WindowAPI:
def save_template_xlsx(self): def save_template_xlsx(self):
"""弹窗选择保存位置,将品牌文档格式模板 xlsx 保存到用户选择的位置。""" """弹窗选择保存位置,将品牌文档格式模板 xlsx 保存到用户选择的位置。"""
import shutil
template_name = '品牌文档格式_模板.xlsx' template_name = '品牌文档格式_模板.xlsx'
template_path = os.path.join(BASE_DIR, 'static', template_name) template_path = os.path.join(BASE_DIR, 'static', template_name)
if not os.path.isfile(template_path): if not os.path.isfile(template_path):
@@ -189,7 +197,6 @@ class WindowAPI:
except Exception as e: except Exception as e:
return {'success': False, 'error': str(e)} return {'success': False, 'error': str(e)}
def save_template_zip(self): def save_template_zip(self):
"""弹窗选择保存位置,将品牌文档格式模板 xlsx 保存到用户选择的位置。""" """弹窗选择保存位置,将品牌文档格式模板 xlsx 保存到用户选择的位置。"""
import shutil import shutil
@@ -234,100 +241,59 @@ class WindowAPI:
except Exception as e: except Exception as e:
return {'success': False, 'error': str(e)} return {'success': False, 'error': str(e)}
def _select_folder_win32(): def open_external_url(self, url):
"""Windows: 用 ctypes 调用系统文件夹选择对话框,打包成 exe 后也能正常弹窗(不依赖 tkinter)""" if not url or not str(url).strip():
return {'success': False, 'error': '链接为空'}
target = str(url).strip()
try: try:
import ctypes if sys.platform.startswith('win'):
from ctypes import wintypes os.startfile(target)
BIF_RETURNONLYFSDIRS = 0x00000001 elif sys.platform == 'darwin':
BIF_NEWDIALOGSTYLE = 0x00000040 subprocess.Popen(['open', target])
MAX_PATH = 260 else:
shell32 = ctypes.windll.shell32 # type: ignore[attr-defined] subprocess.Popen(['xdg-open', target])
# BROWSEINFOW return {'success': True}
class BROWSEINFOW(ctypes.Structure):
_fields_ = [
("hwndOwner", wintypes.HWND),
("pidlRoot", ctypes.c_void_p),
("pszDisplayName", ctypes.c_wchar_p),
("lpszTitle", ctypes.c_wchar_p),
("ulFlags", wintypes.UINT),
("lpfn", ctypes.c_void_p),
("lParam", wintypes.LPARAM),
("iImage", ctypes.c_int),
]
display_name_buf = ctypes.create_unicode_buffer(MAX_PATH)
bi = BROWSEINFOW()
bi.hwndOwner = 0
bi.pidlRoot = 0
bi.pszDisplayName = ctypes.cast(display_name_buf, ctypes.c_wchar_p)
bi.lpszTitle = "选择保存图片的文件夹"
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE
bi.lpfn = 0
bi.lParam = 0
bi.iImage = 0
pidl = shell32.SHBrowseForFolderW(ctypes.byref(bi))
if not pidl:
return ''
path_buf = ctypes.create_unicode_buffer(MAX_PATH)
if not shell32.SHGetPathFromIDListW(pidl, path_buf):
return ''
ole32 = ctypes.windll.ole32 # type: ignore[attr-defined]
ole32.CoTaskMemFree(pidl)
return path_buf.value or ''
except Exception as e: except Exception as e:
print("Windows 文件夹选择失败:", e) return {'success': False, 'error': str(e)}
return ''
def enqueue_json(self, data):
# def _select_folder_tk(): """保存任务到队列"""
# """使用 tkinter 选择文件夹(在非 Windows 或作为后备)"""
# try:
#
# root = tkinter.Tk()
# root.withdraw()
# root.attributes('-topmost', True)
# path = filedialog.askdirectory(title='选择保存图片的文件夹')
# try:
# root.destroy()
# except Exception:
# pass
# return path if path else ''
# except Exception as e:
# print("tkinter 选择文件夹失败:", e)
# return ''
def _select_folder_tk():
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
# 使用 after 确保 askdirectory 在主循环启动后执行
def ask():
nonlocal path
path = filedialog.askdirectory(title='选择保存图片的文件夹')
root.quit() # 关闭主循环
path = ''
root.after(100, ask)
root.mainloop() # 启动主循环,直到 root.quit() 被调用
try: try:
root.destroy() print("==============================")
except: print(datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S"),"调用传入",data)
pass print("==================================")
return path payload = data
if isinstance(data, str):
payload = json.loads(data)
if not isinstance(payload, (dict, list)):
return {'success': False, 'error': '仅支持 JSON 对象或数组'}
if payload.get("type") == "delete-brand-run" and payload.get("data").get("taskId") in runing_task:
return {'success': False, 'error': '已存在正在执行的删除品牌任务'}
# 判断当前店铺是否正在运行中
if payload.get("data").get("items"):
shop_name = payload["data"]["items"][0]["shopName"]
if shop_name in runing_shop:
return {'success': False, 'error': '当前店铺正在执行中,请等待店铺完成之后重试'}
JSON_TASK_QUEUE.put(payload)
return {'success': True, 'queue_size': JSON_TASK_QUEUE.qsize()}
except Exception as e:
return {'success': False, 'error': str(e)}
def get_detail_del(self,task_id):
"""获取正在执行的删除品牌任务详情"""
task_info = runing_task.get(task_id)
if not task_info:
return {'success': False, 'error': '任务不存在'}
return {'success': True, 'task_info': task_info}
def select_folder(): def stop_task(self,task_id):
"""弹窗选择文件夹,返回路径(空字符串表示取消)。Windows 打包 exe 时优先用系统 API 避免 tkinter 不弹窗。""" """停止正在执行的删除品牌任务"""
# if sys.platform == 'win32': task_info = runing_task.get(task_id)
# path = _select_folder_win32() if not task_info:
# if path: return {'success': False, 'error': '任务不存在'}
# return path # 这里可以设置一个标志位,实际的删除品牌任务需要定期检查这个标志位来决定是否停止
return _select_folder_tk() task_info['stop_requested'] = True
return {'success': True, 'message': '已请求停止任务'}
def start_flask(): def start_flask():
@@ -356,7 +322,7 @@ def main():
) )
api = WindowAPI(window) api = WindowAPI(window)
window.expose(api.close, api.minimize, api.maximize, api.toggle_maximize, generate_images, api.save_image, api.save_image_to_folder, api.select_folder, api.select_brand_xlsx_files, api.select_brand_folder, window.expose(api.close, api.minimize, api.maximize, api.toggle_maximize, generate_images, api.save_image, api.save_image_to_folder, api.select_folder, api.select_brand_xlsx_files, api.select_brand_folder,
api.save_file_from_url, api.save_template_xlsx,api.save_template_zip,api.upload_file_to_java) api.save_file_from_url, api.save_template_xlsx,api.save_template_zip,api.upload_file_to_java,api.open_external_url,api.enqueue_json,api.get_detail_del)
webview.start( webview.start(
debug=True, debug=True,
storage_path=cache_path, storage_path=cache_path,
+2 -2
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>格式转换 - 数富AI</title> <title>格式转换 - 数富AI</title>
<script type="module" crossorigin src="/assets/convert.js"></script> <script type="module" crossorigin src="/assets/convert.js"></script>
<link rel="modulepreload" crossorigin href="/assets/pywebview-Bl6M97uH.js"> <link rel="modulepreload" crossorigin href="/assets/pywebview-Dee3nQjE.js">
<link rel="stylesheet" crossorigin href="/assets/pywebview-8G_9KMXd.css"> <link rel="stylesheet" crossorigin href="/assets/pywebview-MkjZQlBu.css">
<link rel="stylesheet" crossorigin href="/assets/convert-Cfr3mUjs.css"> <link rel="stylesheet" crossorigin href="/assets/convert-Cfr3mUjs.css">
</head> </head>
<body> <body>
+2 -2
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>数据去重 - 数富AI</title> <title>数据去重 - 数富AI</title>
<script type="module" crossorigin src="/assets/dedupe.js"></script> <script type="module" crossorigin src="/assets/dedupe.js"></script>
<link rel="modulepreload" crossorigin href="/assets/pywebview-Bl6M97uH.js"> <link rel="modulepreload" crossorigin href="/assets/pywebview-Dee3nQjE.js">
<link rel="stylesheet" crossorigin href="/assets/pywebview-8G_9KMXd.css"> <link rel="stylesheet" crossorigin href="/assets/pywebview-MkjZQlBu.css">
<link rel="stylesheet" crossorigin href="/assets/dedupe-CS18ls2z.css"> <link rel="stylesheet" crossorigin href="/assets/dedupe-CS18ls2z.css">
</head> </head>
<body> <body>
+3 -3
View File
@@ -5,9 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>删除品牌 - 数富AI</title> <title>删除品牌 - 数富AI</title>
<script type="module" crossorigin src="/assets/delete-brand.js"></script> <script type="module" crossorigin src="/assets/delete-brand.js"></script>
<link rel="modulepreload" crossorigin href="/assets/pywebview-Bl6M97uH.js"> <link rel="modulepreload" crossorigin href="/assets/pywebview-Dee3nQjE.js">
<link rel="stylesheet" crossorigin href="/assets/pywebview-8G_9KMXd.css"> <link rel="stylesheet" crossorigin href="/assets/pywebview-MkjZQlBu.css">
<link rel="stylesheet" crossorigin href="/assets/delete-brand-D1WtGorm.css"> <link rel="stylesheet" crossorigin href="/assets/delete-brand-CS44Bk-y.css">
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+2 -2
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>数据拆分 - 数富AI</title> <title>数据拆分 - 数富AI</title>
<script type="module" crossorigin src="/assets/split.js"></script> <script type="module" crossorigin src="/assets/split.js"></script>
<link rel="modulepreload" crossorigin href="/assets/pywebview-Bl6M97uH.js"> <link rel="modulepreload" crossorigin href="/assets/pywebview-Dee3nQjE.js">
<link rel="stylesheet" crossorigin href="/assets/pywebview-8G_9KMXd.css"> <link rel="stylesheet" crossorigin href="/assets/pywebview-MkjZQlBu.css">
<link rel="stylesheet" crossorigin href="/assets/split-mwLUJT1K.css"> <link rel="stylesheet" crossorigin href="/assets/split-mwLUJT1K.css">
</head> </head>
<body> <body>
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 3.9 MiB

Binary file not shown.
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1 +1 @@
{"version": "1.0.13"} {"version": "1.0.22"}
+269 -394
View File
@@ -1,17 +1,11 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>亚马逊 - 南日AI</title> <title>亚马逊 - 数富AI</title>
<style> <style>
* { * { margin: 0; padding: 0; box-sizing: border-box; }
margin: 0;
padding: 0;
box-sizing: border-box;
}
body { body {
font-family: "Microsoft YaHei", "Noto Serif SC", "SimSun", "Songti SC", "Times New Roman", serif; font-family: "Microsoft YaHei", "Noto Serif SC", "SimSun", "Songti SC", "Times New Roman", serif;
background: rgba(13, 13, 13, 1); background: rgba(13, 13, 13, 1);
@@ -20,7 +14,6 @@
height: 100vh; height: 100vh;
font-weight: bold; font-weight: bold;
} }
.top-bar { .top-bar {
height: 56px; height: 56px;
display: flex; display: flex;
@@ -29,19 +22,12 @@
padding: 0 16px; padding: 0 16px;
border-bottom: 1px solid #2a2a2a; border-bottom: 1px solid #2a2a2a;
} }
.logo-area { .logo-area {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
} }
.top-bar .app-name { font-size: 18px; font-weight: 600; color: #fff; }
.top-bar .app-name {
font-size: 18px;
font-weight: 600;
color: #fff;
}
.btn-home { .btn-home {
font-size: 13px; font-size: 13px;
color: #999; color: #999;
@@ -50,57 +36,101 @@
border-radius: 6px; border-radius: 6px;
transition: all 0.2s; transition: all 0.2s;
} }
.btn-home:hover { color: #fff; background: #2a2a2a; }
.btn-home:hover {
color: #fff;
background: #2a2a2a;
}
/* 顶部栏目导航(容器化,便于后续增加栏目) */
.nav-tabs { .nav-tabs {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0; gap: 12px;
} }
.nav-tab-group { .nav-tab-group {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 6px; gap: 12px;
background: rgba(77, 72, 72, 0.99); }
.nav-dropdown {
position: relative;
}
.nav-dropdown-trigger {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
min-width: 112px;
height: 38px;
padding: 0 16px;
border-radius: 10px; border-radius: 10px;
} border: 1px solid transparent;
.nav-tab-sep {
width: 1px;
height: 20px;
background: linear-gradient(to bottom, transparent, #444 15%, #444 85%, transparent);
margin: 0 10px;
flex-shrink: 0;
opacity: 0.9;
}
.nav-tab {
padding: 8px 14px;
font-size: 13px;
color: #999; color: #999;
background: transparent; background: transparent;
border: none; font-size: 13px;
border-radius: 6px; font-weight: 600;
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s ease;
} }
.nav-tab:hover { .nav-dropdown:hover .nav-dropdown-trigger,
.nav-dropdown.active .nav-dropdown-trigger {
color: #fff; color: #fff;
background: #2a2a2a; background: #2a2a2a;
} }
.nav-tab.active { .nav-dropdown.active .nav-dropdown-trigger {
color: #3498db;
background: rgba(52, 152, 219, 0.2);
border-color: rgba(52, 152, 219, 0.3);
}
.nav-dropdown-arrow {
font-size: 11px;
line-height: 1;
}
.nav-dropdown-menu {
position: absolute;
top: 100%;
left: 0;
min-width: 220px;
padding: 8px;
border: 1px solid #2a2a2a;
border-radius: 12px;
background: #171717;
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
display: none;
z-index: 20;
}
.nav-dropdown:hover .nav-dropdown-menu {
display: flex;
flex-direction: column;
gap: 4px;
}
.nav-dropdown-item {
display: flex;
align-items: center;
min-height: 38px;
padding: 0 12px;
border-radius: 8px;
color: #b8b8b8;
font-size: 13px;
font-weight: 600;
text-decoration: none;
transition: all 0.2s ease;
}
.nav-dropdown-item:hover {
color: #fff;
background: #2a2a2a;
}
.nav-dropdown-item.active {
color: #3498db; color: #3498db;
background: rgba(52, 152, 219, 0.2); background: rgba(52, 152, 219, 0.2);
} }
.top-right { .top-right {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -111,7 +141,6 @@
display: flex; display: flex;
height: calc(100vh - 56px); height: calc(100vh - 56px);
} }
/* 栏目内容容器:每个栏目一个 .tab-panel,通过 data-panel 与导航对应 */ /* 栏目内容容器:每个栏目一个 .tab-panel,通过 data-panel 与导航对应 */
.tab-panel { .tab-panel {
display: none; display: none;
@@ -119,11 +148,9 @@
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
} }
.tab-panel.active { .tab-panel.active {
display: flex; display: flex;
} }
.left-panel { .left-panel {
width: 380px; width: 380px;
background: #1e1e1e; background: #1e1e1e;
@@ -131,7 +158,6 @@
overflow-y: auto; overflow-y: auto;
border-right: 1px solid #2a2a2a; border-right: 1px solid #2a2a2a;
} }
.right-panel { .right-panel {
flex: 1; flex: 1;
display: flex; display: flex;
@@ -139,13 +165,11 @@
min-width: 0; min-width: 0;
background: #1a1a1a; background: #1a1a1a;
} }
.section-title { .section-title {
font-size: 13px; font-size: 13px;
color: #bbb; color: #bbb;
margin-bottom: 10px; margin-bottom: 10px;
} }
.upload-zone { .upload-zone {
border: 1px dashed #3a3a3a; border: 1px dashed #3a3a3a;
border-radius: 10px; border-radius: 10px;
@@ -155,25 +179,9 @@
margin-bottom: 20px; margin-bottom: 20px;
transition: all 0.2s; transition: all 0.2s;
} }
.upload-zone:hover { border-color: #3498db; background: #2a2a2a; }
.upload-zone:hover { .upload-zone .hint { color: #888; font-size: 13px; margin-bottom: 12px; }
border-color: #3498db; .upload-zone .btns { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
background: #2a2a2a;
}
.upload-zone .hint {
color: #888;
font-size: 13px;
margin-bottom: 12px;
}
.upload-zone .btns {
display: flex;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
}
.opt-btn { .opt-btn {
padding: 8px 16px; padding: 8px 16px;
font-size: 13px; font-size: 13px;
@@ -184,14 +192,7 @@
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s;
} }
.opt-btn:hover { color: #fff; background: #333; border-color: #3498db; color: #3498db; }
.opt-btn:hover {
color: #fff;
background: #333;
border-color: #3498db;
color: #3498db;
}
.selected-files { .selected-files {
margin-top: 12px; margin-top: 12px;
font-size: 12px; font-size: 12px;
@@ -199,17 +200,8 @@
max-height: 72px; max-height: 72px;
overflow-y: auto; overflow-y: auto;
} }
.selected-files span { display: block; margin: 4px 0; word-break: break-all; }
.selected-files span { .option-group { margin-bottom: 20px; }
display: block;
margin: 4px 0;
word-break: break-all;
}
.option-group {
margin-bottom: 20px;
}
.radio-item { .radio-item {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
@@ -221,35 +213,16 @@
border: 1px solid #2a2a2a; border: 1px solid #2a2a2a;
margin-bottom: 8px; margin-bottom: 8px;
} }
.radio-item:hover { background: #2a2a2a; }
.radio-item:hover { .radio-item input { margin-top: 3px; }
background: #2a2a2a; .radio-item .label { font-weight: 500; color: #e0e0e0; font-size: 13px; }
} .radio-item .desc { font-size: 12px; color: #888; margin-top: 2px; font-weight: normal; }
.radio-item input {
margin-top: 3px;
}
.radio-item .label {
font-weight: 500;
color: #e0e0e0;
font-size: 13px;
}
.radio-item .desc {
font-size: 12px;
color: #888;
margin-top: 2px;
font-weight: normal;
}
.run-row { .run-row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
margin-top: 16px; margin-top: 16px;
} }
.btn-run { .btn-run {
padding: 10px 22px; padding: 10px 22px;
background: #3498db; background: #3498db;
@@ -260,21 +233,9 @@
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s;
} }
.btn-run:hover { background: #2980b9; }
.btn-run:hover { .btn-run:disabled { background: #555; cursor: not-allowed; color: #999; }
background: #2980b9; .loading-msg { color: #3498db; font-size: 13px; }
}
.btn-run:disabled {
background: #555;
cursor: not-allowed;
color: #999;
}
.loading-msg {
color: #3498db;
font-size: 13px;
}
.template-download-row { .template-download-row {
margin-top: 16px; margin-top: 16px;
@@ -288,22 +249,16 @@
transition: all 0.25s ease; transition: all 0.25s ease;
cursor: pointer; cursor: pointer;
} }
.template-download-row:hover { .template-download-row:hover {
border-color: #2e7d32; border-color: #2e7d32;
background: linear-gradient(135deg, #2a2a2a 0%, #243324 100%); background: linear-gradient(135deg, #2a2a2a 0%, #243324 100%);
box-shadow: 0 4px 12px rgba(46, 125, 50, 0.15); box-shadow: 0 4px 12px rgba(46, 125, 50, 0.15);
} }
.template-download-row:hover .template-download-text .title { color: #2ecc71; }
.template-download-row:hover .template-download-text .title {
color: #2ecc71;
}
.template-download-row:hover .template-download-icon { .template-download-row:hover .template-download-icon {
transform: scale(1.05); transform: scale(1.05);
box-shadow: 0 6px 16px rgba(46, 125, 50, 0.45), inset 0 1px 0 rgba(255,255,255,0.15); box-shadow: 0 6px 16px rgba(46, 125, 50, 0.45), inset 0 1px 0 rgba(255,255,255,0.15);
} }
.template-download-icon { .template-download-icon {
width: 48px; width: 48px;
height: 48px; height: 48px;
@@ -316,25 +271,12 @@
box-shadow: 0 4px 12px rgba(46, 125, 50, 0.35), inset 0 1px 0 rgba(255,255,255,0.1); box-shadow: 0 4px 12px rgba(46, 125, 50, 0.35), inset 0 1px 0 rgba(255,255,255,0.1);
transition: transform 0.2s, box-shadow 0.2s; transition: transform 0.2s, box-shadow 0.2s;
} }
.template-download-icon svg { .template-download-icon svg {
width: 28px; width: 28px;
height: 28px; height: 28px;
} }
.template-download-text .title { font-size: 14px; color: #e0e0e0; font-weight: 600; display: block; }
.template-download-text .title { .template-download-text .hint { font-size: 12px; color: #888; margin-top: 2px; font-weight: normal; }
font-size: 14px;
color: #e0e0e0;
font-weight: 600;
display: block;
}
.template-download-text .hint {
font-size: 12px;
color: #888;
margin-top: 2px;
font-weight: normal;
}
.panel-header { .panel-header {
padding: 16px 20px; padding: 16px 20px;
@@ -347,11 +289,9 @@
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
} }
.panel-header-title { .panel-header-title {
flex: 1; flex: 1;
} }
.btn-refresh-tasks { .btn-refresh-tasks {
padding: 6px 14px; padding: 6px 14px;
font-size: 12px; font-size: 12px;
@@ -363,23 +303,17 @@
transition: all 0.2s; transition: all 0.2s;
white-space: nowrap; white-space: nowrap;
} }
.btn-refresh-tasks:hover { .btn-refresh-tasks:hover {
background: #333; background: #333;
border-color: #3498db; border-color: #3498db;
color: #3498db; color: #3498db;
} }
.task-list-wrap { .task-list-wrap {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
padding: 16px; padding: 16px;
} }
.task-list { list-style: none; }
.task-list {
list-style: none;
}
.task-item { .task-item {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -390,155 +324,38 @@
margin-bottom: 10px; margin-bottom: 10px;
background: #1e1e1e; background: #1e1e1e;
} }
.task-item .left { flex: 1; min-width: 0; }
.task-item .left { .task-item .id { font-weight: 600; color: #e0e0e0; font-size: 13px; }
flex: 1; .task-item .files { font-size: 12px; color: #888; margin-top: 4px; }
min-width: 0; .task-item .time { font-size: 12px; color: #666; margin-top: 2px; }
}
.task-item .id {
font-weight: 600;
color: #e0e0e0;
font-size: 13px;
}
.task-item .files {
font-size: 12px;
color: #888;
margin-top: 4px;
}
.task-item .time {
font-size: 12px;
color: #666;
margin-top: 2px;
}
.task-item .status { .task-item .status {
padding: 4px 10px; padding: 4px 10px;
border-radius: 6px; border-radius: 6px;
font-size: 12px; font-size: 12px;
margin-right: 12px; margin-right: 12px;
} }
.task-item .status.pending { background: rgba(255,193,7,0.2); color: #d4a500; }
.task-item .status.pending { .task-item .status.running { background: rgba(52,152,219,0.2); color: #3498db; }
background: rgba(255, 193, 7, 0.2); .task-item .status.success { background: rgba(46,204,113,0.2); color: #2ecc71; }
color: #d4a500; .task-item .status.failed { background: rgba(231,76,60,0.2); color: #e74c3c; }
} .task-item .status.cancelled { background: rgba(149,165,166,0.2); color: #95a5a6; }
.task-item .progress-wrap { margin-top: 8px; margin-right: 8px; flex-shrink: 0; width: 120px; }
.task-item .status.running { .task-item .progress-bar-bg { height: 6px; background: #2a2a2a; border-radius: 3px; overflow: hidden; }
background: rgba(52, 152, 219, 0.2); .task-item .progress-bar-fill { height: 100%; background: #3498db; border-radius: 3px; transition: width 0.2s; }
color: #3498db; .task-item .btn-cancel, .task-item .btn-delete {
} padding: 6px 12px; font-size: 12px; border-radius: 6px; cursor: pointer; border: none; margin-left: 6px;
.task-item .status.success {
background: rgba(46, 204, 113, 0.2);
color: #2ecc71;
}
.task-item .status.failed {
background: rgba(231, 76, 60, 0.2);
color: #e74c3c;
}
.task-item .status.cancelled {
background: rgba(149, 165, 166, 0.2);
color: #95a5a6;
}
.task-item .progress-wrap {
margin-top: 8px;
margin-right: 8px;
flex-shrink: 0;
width: 120px;
}
.task-item .progress-bar-bg {
height: 6px;
background: #2a2a2a;
border-radius: 3px;
overflow: hidden;
}
.task-item .progress-bar-fill {
height: 100%;
background: #3498db;
border-radius: 3px;
transition: width 0.2s;
}
.task-item .btn-cancel,
.task-item .btn-delete {
padding: 6px 12px;
font-size: 12px;
border-radius: 6px;
cursor: pointer;
border: none;
margin-left: 6px;
transition: all 0.2s; transition: all 0.2s;
} }
.task-item .btn-cancel { background: #e67e22; color: #fff; }
.task-item .btn-cancel { .task-item .btn-cancel:hover { background: #d35400; }
background: #e67e22; .task-item .btn-delete { background: #444; color: #ccc; }
color: #fff; .task-item .btn-delete:hover { background: #e74c3c; color: #fff; }
} .task-item .task-right { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.run-row .progress-wrap { margin-top: 10px; width: 100%; max-width: 280px; }
.task-item .btn-cancel:hover { .run-row .progress-bar-bg { height: 8px; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
background: #d35400; .run-row .progress-bar-fill { height: 100%; background: #3498db; border-radius: 4px; transition: width 0.2s; }
} .run-row .btn-cancel-run { margin-left: 12px; padding: 8px 16px; background: #e67e22; color: #fff; border: none; border-radius: 6px; font-size: 13px; cursor: pointer; }
.run-row .btn-cancel-run:hover { background: #d35400; }
.task-item .btn-delete {
background: #444;
color: #ccc;
}
.task-item .btn-delete:hover {
background: #e74c3c;
color: #fff;
}
.task-item .task-right {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.run-row .progress-wrap {
margin-top: 10px;
width: 100%;
max-width: 280px;
}
.run-row .progress-bar-bg {
height: 8px;
background: #2a2a2a;
border-radius: 4px;
overflow: hidden;
}
.run-row .progress-bar-fill {
height: 100%;
background: #3498db;
border-radius: 4px;
transition: width 0.2s;
}
.run-row .btn-cancel-run {
margin-left: 12px;
padding: 8px 16px;
background: #e67e22;
color: #fff;
border: none;
border-radius: 6px;
font-size: 13px;
cursor: pointer;
}
.run-row .btn-cancel-run:hover {
background: #d35400;
}
.task-item .download { .task-item .download {
padding: 6px 14px; padding: 6px 14px;
background: #3498db; background: #3498db;
@@ -551,23 +368,9 @@
white-space: nowrap; white-space: nowrap;
transition: all 0.2s; transition: all 0.2s;
} }
.task-item .download:hover { background: #2980b9; color: #fff; }
.task-item .download:hover { .task-item .download.hide { display: none; }
background: #2980b9; .empty-tasks { text-align: center; color: #666; padding: 32px; font-size: 13px; }
color: #fff;
}
.task-item .download.hide {
display: none;
}
.empty-tasks {
text-align: center;
color: #666;
padding: 32px;
font-size: 13px;
}
.toast { .toast {
position: fixed; position: fixed;
bottom: 32px; bottom: 32px;
@@ -583,13 +386,9 @@
transition: opacity 0.3s; transition: opacity 0.3s;
border: 1px solid #333; border: 1px solid #333;
} }
.toast.show { opacity: 1; }
.toast.show {
opacity: 1;
}
</style> </style>
</head> </head>
<body> <body>
<header class="top-bar"> <header class="top-bar">
<div class="logo-area"> <div class="logo-area">
@@ -597,16 +396,29 @@
<a href="/home" class="btn-home">返回首页</a> <a href="/home" class="btn-home">返回首页</a>
</div> </div>
<nav class="nav-tabs"> <nav class="nav-tabs">
<span class="nav-tab-group"> <div class="nav-tab-group">
<button type="button" class="nav-tab active" data-panel="brandCheck">品牌检测</button> <div class="nav-dropdown active">
<button type="button" class="nav-tab" <button type="button" class="nav-dropdown-trigger">
onclick="window.location='/new_web_source/dedupe.html'">总数据去重</button> <span>前端工具</span>
<button type="button" class="nav-tab" <span class="nav-dropdown-arrow">▾</span>
onclick="window.location='/new_web_source/convert.html'">格式转换</button> </button>
<button type="button" class="nav-tab" <div class="nav-dropdown-menu">
onclick="window.location='/new_web_source/split.html'">表格拆分</button> <button type="button" class="nav-dropdown-item active" data-panel="brandCheck">品牌检测</button>
</span> <a class="nav-dropdown-item" href="/new_web_source/dedupe.html">数据去重</a>
<!-- 多组栏目时可用分隔符:<span class="nav-tab-sep" aria-hidden="true"></span> --> <a class="nav-dropdown-item" href="/new_web_source/split.html">数据拆分</a>
<a class="nav-dropdown-item" href="/new_web_source/convert.html">格式转换</a>
</div>
</div>
<div class="nav-dropdown">
<button type="button" class="nav-dropdown-trigger">
<span>运营工具</span>
<span class="nav-dropdown-arrow">▾</span>
</button>
<div class="nav-dropdown-menu">
<a class="nav-dropdown-item" href="/new_web_source/delete-brand.html">删除指定ASIN和品牌</a>
</div>
</div>
</div>
</nav> </nav>
<div class="top-right"></div> <div class="top-right"></div>
</header> </header>
@@ -664,33 +476,23 @@
<button type="button" class="btn-run" id="btnRun">立即运行</button> <button type="button" class="btn-run" id="btnRun">立即运行</button>
<span class="loading-msg" id="loadingMsg" style="display:none;">生成中,请稍候…</span> <span class="loading-msg" id="loadingMsg" style="display:none;">生成中,请稍候…</span>
<div class="progress-wrap" id="runProgressWrap" style="display:none;"> <div class="progress-wrap" id="runProgressWrap" style="display:none;">
<div class="progress-bar-bg"> <div class="progress-bar-bg"><div class="progress-bar-fill" id="runProgressFill" style="width:0%;"></div></div>
<div class="progress-bar-fill" id="runProgressFill" style="width:0%;"></div>
</div>
<span class="hint" style="font-size:12px;color:#888;" id="runProgressText">0 / 0</span> <span class="hint" style="font-size:12px;color:#888;" id="runProgressText">0 / 0</span>
</div> </div>
<!-- 当前文件行级进度(不经数据库中转,只读内存接口) --> <!-- 当前文件行级进度(不经数据库中转,只读内存接口) -->
<div class="progress-wrap" id="runLineProgressWrap" style="display:none;"> <div class="progress-wrap" id="runLineProgressWrap" style="display:none;">
<div class="progress-bar-bg"> <div class="progress-bar-bg"><div class="progress-bar-fill" id="runLineProgressFill" style="width:0%;"></div></div>
<div class="progress-bar-fill" id="runLineProgressFill" style="width:0%;"></div>
</div>
<span class="hint" style="font-size:12px;color:#888;" id="runLineProgressText">0 / 0</span> <span class="hint" style="font-size:12px;color:#888;" id="runLineProgressText">0 / 0</span>
</div> </div>
<button type="button" class="btn-cancel-run" id="btnCancelRun" <button type="button" class="btn-cancel-run" id="btnCancelRun" style="display:none;">取消生成</button>
style="display:none;">取消生成</button>
</div> </div>
</div> </div>
<div class="template-download-row" id="templateDownloadRow" role="button" tabindex="0" <div class="template-download-row" id="templateDownloadRow" role="button" tabindex="0" title="下载品牌文档格式模板(选择保存位置)">
title="下载品牌文档格式模板(选择保存位置)">
<span class="template-download-icon" aria-hidden="true"> <span class="template-download-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" <path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke-linejoin="round" /> <path d="M8 13h8M8 17h5" stroke="rgba(255,255,255,0.85)" stroke-width="1.5" stroke-linecap="round"/>
<path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round"
stroke-linejoin="round" />
<path d="M8 13h8M8 17h5" stroke="rgba(255,255,255,0.85)" stroke-width="1.5"
stroke-linecap="round" />
</svg> </svg>
</span> </span>
<span class="template-download-text"> <span class="template-download-text">
@@ -698,17 +500,12 @@
<span class="hint">品牌文档格式_模板.xlsx · 点击选择保存位置</span> <span class="hint">品牌文档格式_模板.xlsx · 点击选择保存位置</span>
</span> </span>
</div> </div>
<div class="template-download-row" id="templateDownloadRow2" role="button" tabindex="0" <div class="template-download-row" id="templateDownloadRow2" role="button" tabindex="0" title="下载模板2(以文件夹方式上传)">
title="下载模板2(以文件夹方式上传)">
<span class="template-download-icon" aria-hidden="true"> <span class="template-download-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" <path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke-linejoin="round" /> <path d="M3 7v10h4v-4h2v4h8v-4h2v4h2V7H3z" stroke="rgba(255,255,255,0.85)" stroke-width="1.5" stroke-linecap="round"/>
<path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round"
stroke-linejoin="round" />
<path d="M3 7v10h4v-4h2v4h8v-4h2v4h2V7H3z" stroke="rgba(255,255,255,0.85)"
stroke-width="1.5" stroke-linecap="round" />
</svg> </svg>
</span> </span>
<span class="template-download-text"> <span class="template-download-text">
@@ -739,12 +536,22 @@
var cachedTasks = []; var cachedTasks = [];
var api = window.pywebview && window.pywebview.api; var api = window.pywebview && window.pywebview.api;
// 顶部栏目切换:点击 nav-tab 时显示对应 data-panel 的 tab-panel function getUid() {
document.querySelectorAll('.nav-tab').forEach(function (tab) { return localStorage.getItem('uid') || '';
}
function withUidHeaders(headers) {
headers = headers || {};
headers.uid = getUid();
return headers;
}
// 顶部栏目切换:点击当前页菜单项时显示对应 data-panel 的 tab-panel
document.querySelectorAll('.nav-dropdown-item[data-panel]').forEach(function(tab) {
tab.addEventListener('click', function() { tab.addEventListener('click', function() {
var panelId = this.getAttribute('data-panel'); var panelId = this.getAttribute('data-panel');
if (!panelId) return; if (!panelId) return;
document.querySelectorAll('.nav-tab').forEach(function (t) { t.classList.remove('active'); }); document.querySelectorAll('.nav-dropdown-item[data-panel]').forEach(function(t) { t.classList.remove('active'); });
document.querySelectorAll('.tab-panel').forEach(function(p) { document.querySelectorAll('.tab-panel').forEach(function(p) {
p.classList.toggle('active', p.getAttribute('data-panel') === panelId); p.classList.toggle('active', p.getAttribute('data-panel') === panelId);
}); });
@@ -844,8 +651,8 @@
if (!folder) return; if (!folder) return;
fetch('/api/brand/expand-folder', { fetch('/api/brand/expand-folder', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, headers: withUidHeaders({ 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }),
credentials: 'same-origin', credentials: 'include',
body: JSON.stringify({ folder: folder }) body: JSON.stringify({ folder: folder })
}) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
@@ -876,14 +683,14 @@
var pollTaskId = null; var pollTaskId = null;
var pollTimer = null; var pollTimer = null;
var runTaskEventSource = null; var runTaskEventAbortController = null;
function stopPollAndResetRunUI() { function stopPollAndResetRunUI() {
pollTaskId = null; pollTaskId = null;
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
if (runTaskEventSource) { if (runTaskEventAbortController) {
runTaskEventSource.close(); try { runTaskEventAbortController.abort(); } catch (e) {}
runTaskEventSource = null; runTaskEventAbortController = null;
} }
var btn = document.getElementById('btnRun'); var btn = document.getElementById('btnRun');
var loadingMsg = document.getElementById('loadingMsg'); var loadingMsg = document.getElementById('loadingMsg');
@@ -917,7 +724,7 @@
runProgressWrap.style.display = 'block'; runProgressWrap.style.display = 'block';
btnCancelRun.style.display = 'inline-block'; btnCancelRun.style.display = 'inline-block';
btnCancelRun.onclick = function() { btnCancelRun.onclick = function() {
fetch('/api/brand/tasks/' + taskId + '/cancel', { method: 'POST', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) fetch('/api/brand/tasks/' + taskId + '/cancel', { method: 'POST', credentials: 'include', headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res) { .then(function(res) {
if (res.success) onRunTaskFinished('cancelled'); if (res.success) onRunTaskFinished('cancelled');
@@ -925,28 +732,64 @@
}); });
}; };
// 通过 SSE 订阅任务完成事件,完成后由后端主动推送,前端收到后立即隐藏进度条和取消按钮 // 通过事件流订阅任务完成事件(使用 fetch 以便携带 uid 请求头)
var eventsUrl = '/api/brand/tasks/' + taskId + '/events'; var eventsUrl = '/api/brand/tasks/' + taskId + '/events';
runTaskEventSource = new EventSource(eventsUrl); runTaskEventAbortController = new AbortController();
runTaskEventSource.onmessage = function (e) { (async function() {
try { try {
var data = JSON.parse(e.data); var resp = await fetch(eventsUrl, {
method: 'GET',
credentials: 'include',
headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/event-stream' }),
signal: runTaskEventAbortController.signal
});
if (!resp.ok || !resp.body) return;
var reader = resp.body.getReader();
var decoder = new TextDecoder('utf-8');
var buffer = '';
while (true) {
var r = await reader.read();
if (!r || r.done) break;
buffer += decoder.decode(r.value, { stream: true });
var parts = buffer.split(/\n\n/);
buffer = parts.pop();
var terminalStatus = null;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (!part) continue;
var dataLine = part.split('\n').find(function(l) { return l.indexOf('data:') === 0; });
if (!dataLine) continue;
var dataStr = dataLine.slice(5).trim();
if (!dataStr) continue;
try {
var data = JSON.parse(dataStr);
if (data && (data.status === 'success' || data.status === 'failed' || data.status === 'cancelled')) { if (data && (data.status === 'success' || data.status === 'failed' || data.status === 'cancelled')) {
runTaskEventSource.close(); terminalStatus = data.status;
runTaskEventSource = null; break;
// tick();
onRunTaskFinished(data.status);
} }
} catch (err) {} } catch (err) {}
}; }
runTaskEventSource.onerror = function () {
runTaskEventSource.close(); if (terminalStatus) {
runTaskEventSource = null; try { runTaskEventAbortController.abort(); } catch (e2) {}
}; runTaskEventAbortController = null;
onRunTaskFinished(terminalStatus);
return;
}
}
} catch (err) {}
})();
function tick() { function tick() {
if (!pollTaskId) return; if (!pollTaskId) return;
fetch('/api/brand/tasks/' + taskId, { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) fetch('/api/brand/tasks/' + taskId, { credentials: 'include', headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res) { .then(function(res) {
if (!res.success || !res.task) return; if (!res.success || !res.task) return;
@@ -973,8 +816,8 @@
var st2 = (t.status || '').toLowerCase(); var st2 = (t.status || '').toLowerCase();
if (st2 === 'running') { if (st2 === 'running') {
fetch('/api/brand/tasks/' + taskId + '/line-progress', { fetch('/api/brand/tasks/' + taskId + '/line-progress', {
credentials: 'same-origin', credentials: 'include',
headers: { 'X-Requested-With': 'XMLHttpRequest' } headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' })
}) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res2) { .then(function(res2) {
@@ -1002,7 +845,7 @@
}); });
} }
tick(); tick();
pollTimer = setInterval(tick, 5000); pollTimer = setInterval(tick, 10000);
} }
document.getElementById('btnRun').onclick = function() { document.getElementById('btnRun').onclick = function() {
@@ -1020,8 +863,8 @@
loadingMsg.style.display = 'inline'; loadingMsg.style.display = 'inline';
fetch('/api/brand/run', { fetch('/api/brand/run', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, headers: withUidHeaders({ 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }),
credentials: 'same-origin', credentials: 'include',
body: JSON.stringify({ paths: selectedPaths, strategy: strategy, task_type: 1 }) body: JSON.stringify({ paths: selectedPaths, strategy: strategy, task_type: 1 })
}) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
@@ -1041,8 +884,8 @@
} else { } else {
fetch('/api/brand/tasks', { fetch('/api/brand/tasks', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, headers: withUidHeaders({ 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }),
credentials: 'same-origin', credentials: 'include',
body: JSON.stringify({ paths: selectedPaths, strategy: strategy, task_type: 2 }) body: JSON.stringify({ paths: selectedPaths, strategy: strategy, task_type: 2 })
}) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
@@ -1059,7 +902,7 @@
}; };
function loadTasks() { function loadTasks() {
fetch('/api/brand/tasks', { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) fetch('/api/brand/tasks', { credentials: 'include', headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res) { .then(function(res) {
var list = document.getElementById('taskList'); var list = document.getElementById('taskList');
@@ -1126,7 +969,7 @@
if (target.classList && (target.classList.contains('js-cancel-task') || target.closest('.js-cancel-task'))) { if (target.classList && (target.classList.contains('js-cancel-task') || target.closest('.js-cancel-task'))) {
var btn = target.classList.contains('js-cancel-task') ? target : target.closest('.js-cancel-task'); var btn = target.classList.contains('js-cancel-task') ? target : target.closest('.js-cancel-task');
if (!btn) return; if (!btn) return;
fetch('/api/brand/tasks/' + taskId + '/cancel', { method: 'POST', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) fetch('/api/brand/tasks/' + taskId + '/cancel', { method: 'POST', credentials: 'include', headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res) { .then(function(res) {
if (res.success) { showToast('已取消'); loadTasks(); } else { showToast(res.error || '取消失败'); } if (res.success) { showToast('已取消'); loadTasks(); } else { showToast(res.error || '取消失败'); }
@@ -1136,7 +979,7 @@
if (target.classList && (target.classList.contains('js-delete-task') || target.closest('.js-delete-task'))) { if (target.classList && (target.classList.contains('js-delete-task') || target.closest('.js-delete-task'))) {
var btn = target.classList.contains('js-delete-task') ? target : target.closest('.js-delete-task'); var btn = target.classList.contains('js-delete-task') ? target : target.closest('.js-delete-task');
if (!btn) return; if (!btn) return;
fetch('/api/brand/tasks/' + taskId, { method: 'DELETE', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) fetch('/api/brand/tasks/' + taskId, { method: 'DELETE', credentials: 'include', headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }) })
.then(function(r) { return r.json(); }) .then(function(r) { return r.json(); })
.then(function(res) { .then(function(res) {
if (res.success) { showToast('已删除'); loadTasks(); } else { showToast(res.error || '删除失败'); } if (res.success) { showToast('已删除'); loadTasks(); } else { showToast(res.error || '删除失败'); }
@@ -1174,7 +1017,40 @@
a.style.pointerEvents = ''; a.style.pointerEvents = '';
} }
} else { } else {
window.open('/api/brand/download/' + taskId, '_blank'); fetch('/api/brand/download/' + taskId, {
method: 'GET',
credentials: 'include',
headers: withUidHeaders({ 'X-Requested-With': 'XMLHttpRequest' }),
redirect: 'manual'
})
.then(function(res) {
if (res.status === 301 || res.status === 302) {
var loc = res.headers.get('Location');
if (loc) {
window.open(loc, '_blank');
return;
}
}
var ct = (res.headers && res.headers.get && res.headers.get('content-type')) ? res.headers.get('content-type') : '';
if (ct && ct.indexOf('application/json') >= 0) {
return res.json().then(function(errObj) {
throw new Error((errObj && (errObj.error || errObj.msg)) || '下载失败');
});
}
return res.blob().then(function(blob) {
var url = URL.createObjectURL(blob);
var a2 = document.createElement('a');
a2.href = url;
a2.download = 'brand_task_' + taskId + '.zip';
document.body.appendChild(a2);
a2.click();
a2.remove();
setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
});
})
.catch(function(err) {
showToast('下载失败:' + (err && err.message ? err.message : err));
});
} }
}); });
@@ -1190,5 +1066,4 @@
})(); })();
</script> </script>
</body> </body>
</html> </html>
+60 -336
View File
@@ -1,17 +1,11 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>亚马逊 - 南日AI</title> <title>亚马逊 - 南日AI</title>
<style> <style>
* { * { margin: 0; padding: 0; box-sizing: border-box; }
margin: 0;
padding: 0;
box-sizing: border-box;
}
body { body {
font-family: "Microsoft YaHei", "Noto Serif SC", "SimSun", "Songti SC", "Times New Roman", serif; font-family: "Microsoft YaHei", "Noto Serif SC", "SimSun", "Songti SC", "Times New Roman", serif;
background: rgba(13, 13, 13, 1); background: rgba(13, 13, 13, 1);
@@ -20,7 +14,6 @@
height: 100vh; height: 100vh;
font-weight: bold; font-weight: bold;
} }
.top-bar { .top-bar {
height: 56px; height: 56px;
display: flex; display: flex;
@@ -29,19 +22,12 @@
padding: 0 16px; padding: 0 16px;
border-bottom: 1px solid #2a2a2a; border-bottom: 1px solid #2a2a2a;
} }
.logo-area { .logo-area {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
} }
.top-bar .app-name { font-size: 18px; font-weight: 600; color: #fff; }
.top-bar .app-name {
font-size: 18px;
font-weight: 600;
color: #fff;
}
.btn-home { .btn-home {
font-size: 13px; font-size: 13px;
color: #999; color: #999;
@@ -50,11 +36,7 @@
border-radius: 6px; border-radius: 6px;
transition: all 0.2s; transition: all 0.2s;
} }
.btn-home:hover { color: #fff; background: #2a2a2a; }
.btn-home:hover {
color: #fff;
background: #2a2a2a;
}
/* 顶部栏目导航(容器化,便于后续增加栏目) */ /* 顶部栏目导航(容器化,便于后续增加栏目) */
.nav-tabs { .nav-tabs {
@@ -62,7 +44,6 @@
align-items: center; align-items: center;
gap: 0; gap: 0;
} }
.nav-tab-group { .nav-tab-group {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -70,7 +51,6 @@
background: rgba(77, 72, 72, 0.99); background: rgba(77, 72, 72, 0.99);
border-radius: 10px; border-radius: 10px;
} }
.nav-tab-sep { .nav-tab-sep {
width: 1px; width: 1px;
height: 20px; height: 20px;
@@ -79,7 +59,6 @@
flex-shrink: 0; flex-shrink: 0;
opacity: 0.9; opacity: 0.9;
} }
.nav-tab { .nav-tab {
padding: 8px 14px; padding: 8px 14px;
font-size: 13px; font-size: 13px;
@@ -90,17 +69,14 @@
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s;
} }
.nav-tab:hover { .nav-tab:hover {
color: #fff; color: #fff;
background: #2a2a2a; background: #2a2a2a;
} }
.nav-tab.active { .nav-tab.active {
color: #3498db; color: #3498db;
background: rgba(52, 152, 219, 0.2); background: rgba(52, 152, 219, 0.2);
} }
.top-right { .top-right {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -111,7 +87,6 @@
display: flex; display: flex;
height: calc(100vh - 56px); height: calc(100vh - 56px);
} }
/* 栏目内容容器:每个栏目一个 .tab-panel,通过 data-panel 与导航对应 */ /* 栏目内容容器:每个栏目一个 .tab-panel,通过 data-panel 与导航对应 */
.tab-panel { .tab-panel {
display: none; display: none;
@@ -119,11 +94,9 @@
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
} }
.tab-panel.active { .tab-panel.active {
display: flex; display: flex;
} }
.left-panel { .left-panel {
width: 380px; width: 380px;
background: #1e1e1e; background: #1e1e1e;
@@ -131,7 +104,6 @@
overflow-y: auto; overflow-y: auto;
border-right: 1px solid #2a2a2a; border-right: 1px solid #2a2a2a;
} }
.right-panel { .right-panel {
flex: 1; flex: 1;
display: flex; display: flex;
@@ -139,13 +111,11 @@
min-width: 0; min-width: 0;
background: #1a1a1a; background: #1a1a1a;
} }
.section-title { .section-title {
font-size: 13px; font-size: 13px;
color: #bbb; color: #bbb;
margin-bottom: 10px; margin-bottom: 10px;
} }
.upload-zone { .upload-zone {
border: 1px dashed #3a3a3a; border: 1px dashed #3a3a3a;
border-radius: 10px; border-radius: 10px;
@@ -155,25 +125,9 @@
margin-bottom: 20px; margin-bottom: 20px;
transition: all 0.2s; transition: all 0.2s;
} }
.upload-zone:hover { border-color: #3498db; background: #2a2a2a; }
.upload-zone:hover { .upload-zone .hint { color: #888; font-size: 13px; margin-bottom: 12px; }
border-color: #3498db; .upload-zone .btns { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
background: #2a2a2a;
}
.upload-zone .hint {
color: #888;
font-size: 13px;
margin-bottom: 12px;
}
.upload-zone .btns {
display: flex;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
}
.opt-btn { .opt-btn {
padding: 8px 16px; padding: 8px 16px;
font-size: 13px; font-size: 13px;
@@ -184,14 +138,7 @@
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s;
} }
.opt-btn:hover { color: #fff; background: #333; border-color: #3498db; color: #3498db; }
.opt-btn:hover {
color: #fff;
background: #333;
border-color: #3498db;
color: #3498db;
}
.selected-files { .selected-files {
margin-top: 12px; margin-top: 12px;
font-size: 12px; font-size: 12px;
@@ -199,17 +146,8 @@
max-height: 72px; max-height: 72px;
overflow-y: auto; overflow-y: auto;
} }
.selected-files span { display: block; margin: 4px 0; word-break: break-all; }
.selected-files span { .option-group { margin-bottom: 20px; }
display: block;
margin: 4px 0;
word-break: break-all;
}
.option-group {
margin-bottom: 20px;
}
.radio-item { .radio-item {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
@@ -221,35 +159,16 @@
border: 1px solid #2a2a2a; border: 1px solid #2a2a2a;
margin-bottom: 8px; margin-bottom: 8px;
} }
.radio-item:hover { background: #2a2a2a; }
.radio-item:hover { .radio-item input { margin-top: 3px; }
background: #2a2a2a; .radio-item .label { font-weight: 500; color: #e0e0e0; font-size: 13px; }
} .radio-item .desc { font-size: 12px; color: #888; margin-top: 2px; font-weight: normal; }
.radio-item input {
margin-top: 3px;
}
.radio-item .label {
font-weight: 500;
color: #e0e0e0;
font-size: 13px;
}
.radio-item .desc {
font-size: 12px;
color: #888;
margin-top: 2px;
font-weight: normal;
}
.run-row { .run-row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
margin-top: 16px; margin-top: 16px;
} }
.btn-run { .btn-run {
padding: 10px 22px; padding: 10px 22px;
background: #3498db; background: #3498db;
@@ -260,21 +179,9 @@
cursor: pointer; cursor: pointer;
transition: all 0.2s; transition: all 0.2s;
} }
.btn-run:hover { background: #2980b9; }
.btn-run:hover { .btn-run:disabled { background: #555; cursor: not-allowed; color: #999; }
background: #2980b9; .loading-msg { color: #3498db; font-size: 13px; }
}
.btn-run:disabled {
background: #555;
cursor: not-allowed;
color: #999;
}
.loading-msg {
color: #3498db;
font-size: 13px;
}
.template-download-row { .template-download-row {
margin-top: 16px; margin-top: 16px;
@@ -288,22 +195,16 @@
transition: all 0.25s ease; transition: all 0.25s ease;
cursor: pointer; cursor: pointer;
} }
.template-download-row:hover { .template-download-row:hover {
border-color: #2e7d32; border-color: #2e7d32;
background: linear-gradient(135deg, #2a2a2a 0%, #243324 100%); background: linear-gradient(135deg, #2a2a2a 0%, #243324 100%);
box-shadow: 0 4px 12px rgba(46, 125, 50, 0.15); box-shadow: 0 4px 12px rgba(46, 125, 50, 0.15);
} }
.template-download-row:hover .template-download-text .title { color: #2ecc71; }
.template-download-row:hover .template-download-text .title {
color: #2ecc71;
}
.template-download-row:hover .template-download-icon { .template-download-row:hover .template-download-icon {
transform: scale(1.05); transform: scale(1.05);
box-shadow: 0 6px 16px rgba(46, 125, 50, 0.45), inset 0 1px 0 rgba(255,255,255,0.15); box-shadow: 0 6px 16px rgba(46, 125, 50, 0.45), inset 0 1px 0 rgba(255,255,255,0.15);
} }
.template-download-icon { .template-download-icon {
width: 48px; width: 48px;
height: 48px; height: 48px;
@@ -316,25 +217,12 @@
box-shadow: 0 4px 12px rgba(46, 125, 50, 0.35), inset 0 1px 0 rgba(255,255,255,0.1); box-shadow: 0 4px 12px rgba(46, 125, 50, 0.35), inset 0 1px 0 rgba(255,255,255,0.1);
transition: transform 0.2s, box-shadow 0.2s; transition: transform 0.2s, box-shadow 0.2s;
} }
.template-download-icon svg { .template-download-icon svg {
width: 28px; width: 28px;
height: 28px; height: 28px;
} }
.template-download-text .title { font-size: 14px; color: #e0e0e0; font-weight: 600; display: block; }
.template-download-text .title { .template-download-text .hint { font-size: 12px; color: #888; margin-top: 2px; font-weight: normal; }
font-size: 14px;
color: #e0e0e0;
font-weight: 600;
display: block;
}
.template-download-text .hint {
font-size: 12px;
color: #888;
margin-top: 2px;
font-weight: normal;
}
.panel-header { .panel-header {
padding: 16px 20px; padding: 16px 20px;
@@ -347,11 +235,9 @@
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
} }
.panel-header-title { .panel-header-title {
flex: 1; flex: 1;
} }
.btn-refresh-tasks { .btn-refresh-tasks {
padding: 6px 14px; padding: 6px 14px;
font-size: 12px; font-size: 12px;
@@ -363,23 +249,17 @@
transition: all 0.2s; transition: all 0.2s;
white-space: nowrap; white-space: nowrap;
} }
.btn-refresh-tasks:hover { .btn-refresh-tasks:hover {
background: #333; background: #333;
border-color: #3498db; border-color: #3498db;
color: #3498db; color: #3498db;
} }
.task-list-wrap { .task-list-wrap {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
padding: 16px; padding: 16px;
} }
.task-list { list-style: none; }
.task-list {
list-style: none;
}
.task-item { .task-item {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -390,155 +270,38 @@
margin-bottom: 10px; margin-bottom: 10px;
background: #1e1e1e; background: #1e1e1e;
} }
.task-item .left { flex: 1; min-width: 0; }
.task-item .left { .task-item .id { font-weight: 600; color: #e0e0e0; font-size: 13px; }
flex: 1; .task-item .files { font-size: 12px; color: #888; margin-top: 4px; }
min-width: 0; .task-item .time { font-size: 12px; color: #666; margin-top: 2px; }
}
.task-item .id {
font-weight: 600;
color: #e0e0e0;
font-size: 13px;
}
.task-item .files {
font-size: 12px;
color: #888;
margin-top: 4px;
}
.task-item .time {
font-size: 12px;
color: #666;
margin-top: 2px;
}
.task-item .status { .task-item .status {
padding: 4px 10px; padding: 4px 10px;
border-radius: 6px; border-radius: 6px;
font-size: 12px; font-size: 12px;
margin-right: 12px; margin-right: 12px;
} }
.task-item .status.pending { background: rgba(255,193,7,0.2); color: #d4a500; }
.task-item .status.pending { .task-item .status.running { background: rgba(52,152,219,0.2); color: #3498db; }
background: rgba(255, 193, 7, 0.2); .task-item .status.success { background: rgba(46,204,113,0.2); color: #2ecc71; }
color: #d4a500; .task-item .status.failed { background: rgba(231,76,60,0.2); color: #e74c3c; }
} .task-item .status.cancelled { background: rgba(149,165,166,0.2); color: #95a5a6; }
.task-item .progress-wrap { margin-top: 8px; margin-right: 8px; flex-shrink: 0; width: 120px; }
.task-item .status.running { .task-item .progress-bar-bg { height: 6px; background: #2a2a2a; border-radius: 3px; overflow: hidden; }
background: rgba(52, 152, 219, 0.2); .task-item .progress-bar-fill { height: 100%; background: #3498db; border-radius: 3px; transition: width 0.2s; }
color: #3498db; .task-item .btn-cancel, .task-item .btn-delete {
} padding: 6px 12px; font-size: 12px; border-radius: 6px; cursor: pointer; border: none; margin-left: 6px;
.task-item .status.success {
background: rgba(46, 204, 113, 0.2);
color: #2ecc71;
}
.task-item .status.failed {
background: rgba(231, 76, 60, 0.2);
color: #e74c3c;
}
.task-item .status.cancelled {
background: rgba(149, 165, 166, 0.2);
color: #95a5a6;
}
.task-item .progress-wrap {
margin-top: 8px;
margin-right: 8px;
flex-shrink: 0;
width: 120px;
}
.task-item .progress-bar-bg {
height: 6px;
background: #2a2a2a;
border-radius: 3px;
overflow: hidden;
}
.task-item .progress-bar-fill {
height: 100%;
background: #3498db;
border-radius: 3px;
transition: width 0.2s;
}
.task-item .btn-cancel,
.task-item .btn-delete {
padding: 6px 12px;
font-size: 12px;
border-radius: 6px;
cursor: pointer;
border: none;
margin-left: 6px;
transition: all 0.2s; transition: all 0.2s;
} }
.task-item .btn-cancel { background: #e67e22; color: #fff; }
.task-item .btn-cancel { .task-item .btn-cancel:hover { background: #d35400; }
background: #e67e22; .task-item .btn-delete { background: #444; color: #ccc; }
color: #fff; .task-item .btn-delete:hover { background: #e74c3c; color: #fff; }
} .task-item .task-right { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.run-row .progress-wrap { margin-top: 10px; width: 100%; max-width: 280px; }
.task-item .btn-cancel:hover { .run-row .progress-bar-bg { height: 8px; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
background: #d35400; .run-row .progress-bar-fill { height: 100%; background: #3498db; border-radius: 4px; transition: width 0.2s; }
} .run-row .btn-cancel-run { margin-left: 12px; padding: 8px 16px; background: #e67e22; color: #fff; border: none; border-radius: 6px; font-size: 13px; cursor: pointer; }
.run-row .btn-cancel-run:hover { background: #d35400; }
.task-item .btn-delete {
background: #444;
color: #ccc;
}
.task-item .btn-delete:hover {
background: #e74c3c;
color: #fff;
}
.task-item .task-right {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.run-row .progress-wrap {
margin-top: 10px;
width: 100%;
max-width: 280px;
}
.run-row .progress-bar-bg {
height: 8px;
background: #2a2a2a;
border-radius: 4px;
overflow: hidden;
}
.run-row .progress-bar-fill {
height: 100%;
background: #3498db;
border-radius: 4px;
transition: width 0.2s;
}
.run-row .btn-cancel-run {
margin-left: 12px;
padding: 8px 16px;
background: #e67e22;
color: #fff;
border: none;
border-radius: 6px;
font-size: 13px;
cursor: pointer;
}
.run-row .btn-cancel-run:hover {
background: #d35400;
}
.task-item .download { .task-item .download {
padding: 6px 14px; padding: 6px 14px;
background: #3498db; background: #3498db;
@@ -551,23 +314,9 @@
white-space: nowrap; white-space: nowrap;
transition: all 0.2s; transition: all 0.2s;
} }
.task-item .download:hover { background: #2980b9; color: #fff; }
.task-item .download:hover { .task-item .download.hide { display: none; }
background: #2980b9; .empty-tasks { text-align: center; color: #666; padding: 32px; font-size: 13px; }
color: #fff;
}
.task-item .download.hide {
display: none;
}
.empty-tasks {
text-align: center;
color: #666;
padding: 32px;
font-size: 13px;
}
.toast { .toast {
position: fixed; position: fixed;
bottom: 32px; bottom: 32px;
@@ -583,13 +332,9 @@
transition: opacity 0.3s; transition: opacity 0.3s;
border: 1px solid #333; border: 1px solid #333;
} }
.toast.show { opacity: 1; }
.toast.show {
opacity: 1;
}
</style> </style>
</head> </head>
<body> <body>
<header class="top-bar"> <header class="top-bar">
<div class="logo-area"> <div class="logo-area">
@@ -599,12 +344,7 @@
<nav class="nav-tabs"> <nav class="nav-tabs">
<span class="nav-tab-group"> <span class="nav-tab-group">
<button type="button" class="nav-tab active" data-panel="brandCheck">品牌检测</button> <button type="button" class="nav-tab active" data-panel="brandCheck">品牌检测</button>
<button type="button" class="nav-tab" <!-- 后续增加栏目时在此添加,例如:<button type="button" class="nav-tab" data-panel="other">其他栏目</button> -->
onclick="window.location='/new_web_source/dedupe.html'">总数据去重</button>
<button type="button" class="nav-tab"
onclick="window.location='/new_web_source/convert.html'">格式转换</button>
<button type="button" class="nav-tab"
onclick="window.location='/new_web_source/split.html'">表格拆分</button>
</span> </span>
<!-- 多组栏目时可用分隔符:<span class="nav-tab-sep" aria-hidden="true"></span> --> <!-- 多组栏目时可用分隔符:<span class="nav-tab-sep" aria-hidden="true"></span> -->
</nav> </nav>
@@ -664,33 +404,23 @@
<button type="button" class="btn-run" id="btnRun">立即运行</button> <button type="button" class="btn-run" id="btnRun">立即运行</button>
<span class="loading-msg" id="loadingMsg" style="display:none;">生成中,请稍候…</span> <span class="loading-msg" id="loadingMsg" style="display:none;">生成中,请稍候…</span>
<div class="progress-wrap" id="runProgressWrap" style="display:none;"> <div class="progress-wrap" id="runProgressWrap" style="display:none;">
<div class="progress-bar-bg"> <div class="progress-bar-bg"><div class="progress-bar-fill" id="runProgressFill" style="width:0%;"></div></div>
<div class="progress-bar-fill" id="runProgressFill" style="width:0%;"></div>
</div>
<span class="hint" style="font-size:12px;color:#888;" id="runProgressText">0 / 0</span> <span class="hint" style="font-size:12px;color:#888;" id="runProgressText">0 / 0</span>
</div> </div>
<!-- 当前文件行级进度(不经数据库中转,只读内存接口) --> <!-- 当前文件行级进度(不经数据库中转,只读内存接口) -->
<div class="progress-wrap" id="runLineProgressWrap" style="display:none;"> <div class="progress-wrap" id="runLineProgressWrap" style="display:none;">
<div class="progress-bar-bg"> <div class="progress-bar-bg"><div class="progress-bar-fill" id="runLineProgressFill" style="width:0%;"></div></div>
<div class="progress-bar-fill" id="runLineProgressFill" style="width:0%;"></div>
</div>
<span class="hint" style="font-size:12px;color:#888;" id="runLineProgressText">0 / 0</span> <span class="hint" style="font-size:12px;color:#888;" id="runLineProgressText">0 / 0</span>
</div> </div>
<button type="button" class="btn-cancel-run" id="btnCancelRun" <button type="button" class="btn-cancel-run" id="btnCancelRun" style="display:none;">取消生成</button>
style="display:none;">取消生成</button>
</div> </div>
</div> </div>
<div class="template-download-row" id="templateDownloadRow" role="button" tabindex="0" <div class="template-download-row" id="templateDownloadRow" role="button" tabindex="0" title="下载品牌文档格式模板(选择保存位置)">
title="下载品牌文档格式模板(选择保存位置)">
<span class="template-download-icon" aria-hidden="true"> <span class="template-download-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" <path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke-linejoin="round" /> <path d="M8 13h8M8 17h5" stroke="rgba(255,255,255,0.85)" stroke-width="1.5" stroke-linecap="round"/>
<path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round"
stroke-linejoin="round" />
<path d="M8 13h8M8 17h5" stroke="rgba(255,255,255,0.85)" stroke-width="1.5"
stroke-linecap="round" />
</svg> </svg>
</span> </span>
<span class="template-download-text"> <span class="template-download-text">
@@ -698,17 +428,12 @@
<span class="hint">品牌文档格式_模板.xlsx · 点击选择保存位置</span> <span class="hint">品牌文档格式_模板.xlsx · 点击选择保存位置</span>
</span> </span>
</div> </div>
<div class="template-download-row" id="templateDownloadRow2" role="button" tabindex="0" <div class="template-download-row" id="templateDownloadRow2" role="button" tabindex="0" title="下载模板2(以文件夹方式上传)">
title="下载模板2(以文件夹方式上传)">
<span class="template-download-icon" aria-hidden="true"> <span class="template-download-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" <path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
stroke-linejoin="round" /> <path d="M3 7v10h4v-4h2v4h8v-4h2v4h2V7H3z" stroke="rgba(255,255,255,0.85)" stroke-width="1.5" stroke-linecap="round"/>
<path d="M14 2v6h6" stroke="rgba(255,255,255,0.9)" stroke-width="1.8" stroke-linecap="round"
stroke-linejoin="round" />
<path d="M3 7v10h4v-4h2v4h8v-4h2v4h2V7H3z" stroke="rgba(255,255,255,0.85)"
stroke-width="1.5" stroke-linecap="round" />
</svg> </svg>
</span> </span>
<span class="template-download-text"> <span class="template-download-text">
@@ -1190,5 +915,4 @@
})(); })();
</script> </script>
</body> </body>
</html> </html>
@@ -0,0 +1,16 @@
package com.nanri.aiimage.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "aiimage.delete-brand-progress")
public class DeleteBrandProgressProperties {
private long heartbeatTimeoutMinutes = 15;
private String staleCheckCron = "0 */2 * * * *";
/**
* 定时补偿 finalize:用于“分片其实已齐,但最后一次提交断开导致没触发 finalize”的场景。
*/
private String finalizeCheckCron = "30 */2 * * * *";
}
@@ -4,6 +4,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
@EnableConfigurationProperties({OssProperties.class, StorageProperties.class, BrandProgressProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class}) @EnableConfigurationProperties({OssProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class})
public class PropertiesConfig { public class PropertiesConfig {
} }
@@ -28,4 +28,37 @@ public class ZiniaoProperties {
private long shopsCacheMinutes; private long shopsCacheMinutes;
private int connectTimeoutSeconds; private int connectTimeoutSeconds;
private int readTimeoutSeconds; private int readTimeoutSeconds;
/**
* 店铺匹配时最多尝试多少个 apiKey;
* null/空/<=0 表示不限制(不推荐)。
*/
private Integer keyScanMaxKeys;
/**
* 店铺匹配时最多扫描多少秒;
* null/空/<=0 表示不限制(不推荐)。
*/
private Integer keyScanMaxSeconds;
/**
* 店铺索引后台刷新 cron。
*/
private String shopIndexRefreshCron;
/**
* 店铺索引条目保鲜分钟数。
*/
private Integer shopIndexFreshMinutes;
/**
* 店铺索引条目 TTL 小时数。
*/
private Integer shopIndexEntryTtlHours;
/**
* 每次索引刷新最多扫描多少个 apiKey;
* null/空/<=0 表示不限制(不推荐)。
*/
private Integer shopIndexRefreshBatchSize;
} }
@@ -16,6 +16,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
@@ -27,6 +28,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/brand") @RequestMapping("/api/brand")
@@ -191,17 +197,34 @@ public class BrandTaskController {
@GetMapping("/tasks/{taskId}/download") @GetMapping("/tasks/{taskId}/download")
@Operation( @Operation(
summary = "下载品牌任务结果", summary = "下载品牌任务结果",
description = "根据任务 ID 读取 brand_crawl_tasks.result_paths,优先跳转 zip_url;若没有 zip_url,则跳转第一个可用结果 URL。" description = "根据任务 ID 读取 brand_crawl_tasks.result_paths,后端代理拉取 OSS 文件并直接返回给浏览器,避免跨域问题。"
) )
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "302", description = "重定向到 OSS 结果文件地址"), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "文件流(application/zip)"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "任务不存在或无结果可下载") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "任务不存在或无结果可下载")
}) })
public ResponseEntity<Void> download( public void download(
@Parameter(description = "品牌任务 ID", required = true) @PathVariable Long taskId) { @Parameter(description = "品牌任务 ID", required = true) @PathVariable Long taskId,
String url = brandTaskService.resolveDownloadUrl(taskId); HttpServletResponse response) throws Exception {
return ResponseEntity.status(302) String ossUrl = brandTaskService.resolveDownloadUrl(taskId);
.header(HttpHeaders.LOCATION, url) // 从 OSS URL 路径中取文件名
.build(); String rawPath = URI.create(ossUrl).getPath();
String filename = rawPath.substring(rawPath.lastIndexOf('/') + 1);
if (filename.isBlank()) {
filename = "brand_task_" + taskId + ".zip";
}
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"; filename*=UTF-8''" + encodedFilename);
// 后端代理拉取 OSS 文件并流式写出
try (InputStream in = URI.create(ossUrl).toURL().openStream()) {
byte[] buffer = new byte[65536];
int read;
while ((read = in.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, read);
}
response.getOutputStream().flush();
}
} }
} }
@@ -277,7 +277,11 @@ public class BrandTaskService {
String originalFilename = resolveOriginalFilename(sourceFile, sourceLocalFile); String originalFilename = resolveOriginalFilename(sourceFile, sourceLocalFile);
File outputFile = buildNamedOutputFile(outputDir, buildResultFilename(originalFilename)); File outputFile = buildNamedOutputFile(outputDir, buildResultFilename(originalFilename));
writeBrandWorkbook(outputFile, request.getStrategy(), cachedFile, resultFile); writeBrandWorkbook(outputFile, request.getStrategy(), cachedFile, resultFile);
outputEntries.add(new OutputEntry(sourceLocalFile, originalFilename, outputFile, outputFile.getName())); outputEntries.add(new OutputEntry(
sourceLocalFile,
originalFilename,
outputFile,
originalFilename));
} }
brandTaskProgressCacheService.updatePhase(taskId, BrandTaskProgressCacheService.PHASE_UPLOADING, finishedCount, totalCount); brandTaskProgressCacheService.updatePhase(taskId, BrandTaskProgressCacheService.PHASE_UPLOADING, finishedCount, totalCount);
@@ -338,19 +342,25 @@ public class BrandTaskService {
if (!(raw instanceof Map<?, ?> map)) { if (!(raw instanceof Map<?, ?> map)) {
throw new BusinessException("无结果可下载"); throw new BusinessException("无结果可下载");
} }
String stored = null;
Object zipUrl = map.get("zip_url"); Object zipUrl = map.get("zip_url");
if (zipUrl instanceof String zip && !zip.isBlank()) { if (zipUrl instanceof String zip && !zip.isBlank()) {
return zip; stored = zip;
} } else {
Object urls = map.get("urls"); Object urls = map.get("urls");
if (urls instanceof List<?> list && !list.isEmpty()) { if (urls instanceof List<?> list && !list.isEmpty()) {
Object first = list.get(0); Object first = list.get(0);
if (first instanceof String url && !url.isBlank()) { if (first instanceof String url && !url.isBlank()) {
return url; stored = url;
} }
} }
}
if (stored == null || stored.isBlank()) {
throw new BusinessException("无结果可下载"); throw new BusinessException("无结果可下载");
} }
// 统一通过 OssStorageService.generateFreshDownloadUrl 生成新鲜预签名 URL
return ossStorageService.generateFreshDownloadUrl(stored);
}
private List<BrandCrawlTaskEntity> listTaskEntities(Long userId) { private List<BrandCrawlTaskEntity> listTaskEntities(Long userId) {
if (userId == null || userId <= 0) { if (userId == null || userId <= 0) {
@@ -852,28 +862,29 @@ public class BrandTaskService {
if (entries.isEmpty()) { if (entries.isEmpty()) {
throw new BusinessException("没有可上传的结果文件"); throw new BusinessException("没有可上传的结果文件");
} }
List<String> urls = new ArrayList<>(); List<String> fullUrls = new ArrayList<>();
for (OutputEntry entry : entries) { for (OutputEntry entry : entries) {
// 存储完整公开地址,下载时会自动通过 resolveObjectKey 提取并重新签名(见 OssStorageService.resolveObjectKey)
String objectKey = ossStorageService.uploadResultFile(entry.resultFile(), "BRAND"); String objectKey = ossStorageService.uploadResultFile(entry.resultFile(), "BRAND");
urls.add(ossStorageService.generateDownloadUrl(objectKey)); fullUrls.add(ossStorageService.getPublicUrl(objectKey));
} }
Map<String, Object> result = new LinkedHashMap<>(); Map<String, Object> result = new LinkedHashMap<>();
result.put("urls", urls); result.put("urls", fullUrls);
File zipFile = packageAsZip(taskId, entries); File zipFile = packageAsZip(taskId, entries);
String zipObjectKey = ossStorageService.uploadResultFile(zipFile, "BRAND"); String zipObjectKey = ossStorageService.uploadResultFile(zipFile, "BRAND");
result.put("zip_url", ossStorageService.generateDownloadUrl(zipObjectKey)); result.put("zip_url", ossStorageService.getPublicUrl(zipObjectKey));
return result; return result;
} }
private File packageAsZip(Long taskId, List<OutputEntry> entries) throws IOException { private File packageAsZip(Long taskId, List<OutputEntry> entries) throws IOException {
File zipDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "brand-result", String.valueOf(taskId))); File zipDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "brand-result", String.valueOf(taskId)));
File zipFile = buildNamedOutputFile(zipDir, "brand_task_" + taskId + ".zip"); File zipFile = buildNamedOutputFile(zipDir, buildArchiveFilename(entries));
Set<String> zipEntryNames = new LinkedHashSet<>(); Set<String> zipEntryNames = new LinkedHashSet<>();
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
for (OutputEntry entry : entries) { for (OutputEntry entry : entries) {
writeZipEntry(zos, buffer, entry.sourceFile(), buildSourceZipEntry(entry.sourceFilename()), zipEntryNames); writeZipEntry(zos, buffer, entry.sourceFile(), buildSourceZipEntry(entry.zipSourceFilename()), zipEntryNames);
writeZipEntry(zos, buffer, entry.resultFile(), buildResultZipEntry(entry.resultFilename()), zipEntryNames); writeZipEntry(zos, buffer, entry.resultFile(), buildResultZipEntry(entry.zipResultFilename()), zipEntryNames);
} }
} }
return zipFile; return zipFile;
@@ -933,8 +944,15 @@ public class BrandTaskService {
} }
private String buildResultFilename(String originalFilename) { private String buildResultFilename(String originalFilename) {
String sourceName = blankToDefault(originalFilename, "brand.xlsx"); return blankToDefault(originalFilename, "brand.xlsx");
return FileUtil.mainName(sourceName) + "_result.xlsx"; }
private String buildArchiveFilename(List<OutputEntry> entries) {
if (entries == null || entries.isEmpty()) {
return "brand.zip";
}
String sourceFilename = blankToDefault(entries.get(0).zipSourceFilename(), "brand.xlsx");
return FileUtil.mainName(sourceFilename) + ".zip";
} }
private Integer defaultInteger(Integer value) { private Integer defaultInteger(Integer value) {
@@ -1062,6 +1080,6 @@ public class BrandTaskService {
List<String> uniqueBrands) { List<String> uniqueBrands) {
} }
private record OutputEntry(File sourceFile, String sourceFilename, File resultFile, String resultFilename) { private record OutputEntry(File sourceFile, String zipSourceFilename, File resultFile, String zipResultFilename) {
} }
} }
@@ -114,20 +114,19 @@ public class ConvertRunService {
String contentType = useZipPackage ? "application/zip" : "text/plain"; String contentType = useZipPackage ? "application/zip" : "text/plain";
String ossObjectKey = ossStorageService.uploadResultFile(packagedResultFile, MODULE_TYPE); String ossObjectKey = ossStorageService.uploadResultFile(packagedResultFile, MODULE_TYPE);
String downloadUrl = ossStorageService.generateDownloadUrl(ossObjectKey); // 只存 objectKey
ConvertResultItemVo item = new ConvertResultItemVo(); ConvertResultItemVo item = new ConvertResultItemVo();
item.setSourceFilename(inputName); item.setSourceFilename(inputName);
item.setSuccess(true); item.setSuccess(true);
item.setOutputFilename(packagedFilename); item.setOutputFilename(packagedFilename);
item.setDownloadUrl(downloadUrl); item.setDownloadUrl(ossStorageService.generateFreshDownloadUrl(ossObjectKey));
FileResultEntity resultEntity = new FileResultEntity(); FileResultEntity resultEntity = new FileResultEntity();
resultEntity.setTaskId(task.getId()); resultEntity.setTaskId(task.getId());
resultEntity.setModuleType(MODULE_TYPE); resultEntity.setModuleType(MODULE_TYPE);
resultEntity.setSourceFilename(inputName); resultEntity.setSourceFilename(inputName);
resultEntity.setResultFilename(packagedFilename); resultEntity.setResultFilename(packagedFilename);
resultEntity.setResultFileUrl(downloadUrl); resultEntity.setResultFileUrl(ossObjectKey); // 存 objectKey
resultEntity.setResultFileSize(packagedResultFile.length()); resultEntity.setResultFileSize(packagedResultFile.length());
resultEntity.setResultContentType(contentType); resultEntity.setResultContentType(contentType);
resultEntity.setSuccess(1); resultEntity.setSuccess(1);
@@ -161,20 +160,19 @@ public class ConvertRunService {
if (folderMode && !archiveEntries.isEmpty()) { if (folderMode && !archiveEntries.isEmpty()) {
File zipFile = packageFolderConvertResultsAsZip(request.getArchiveName(), archiveEntries); File zipFile = packageFolderConvertResultsAsZip(request.getArchiveName(), archiveEntries);
String ossObjectKey = ossStorageService.uploadResultFile(zipFile, MODULE_TYPE); String ossObjectKey = ossStorageService.uploadResultFile(zipFile, MODULE_TYPE);
String downloadUrl = ossStorageService.generateDownloadUrl(ossObjectKey); // 只存 objectKey
ConvertResultItemVo item = new ConvertResultItemVo(); ConvertResultItemVo item = new ConvertResultItemVo();
item.setSourceFilename(request.getArchiveName()); item.setSourceFilename(request.getArchiveName());
item.setOutputFilename(zipFile.getName()); item.setOutputFilename(zipFile.getName());
item.setSuccess(true); item.setSuccess(true);
item.setDownloadUrl(downloadUrl); item.setDownloadUrl(ossStorageService.generateFreshDownloadUrl(ossObjectKey));
FileResultEntity resultEntity = new FileResultEntity(); FileResultEntity resultEntity = new FileResultEntity();
resultEntity.setTaskId(task.getId()); resultEntity.setTaskId(task.getId());
resultEntity.setModuleType(MODULE_TYPE); resultEntity.setModuleType(MODULE_TYPE);
resultEntity.setSourceFilename(request.getArchiveName()); resultEntity.setSourceFilename(request.getArchiveName());
resultEntity.setResultFilename(zipFile.getName()); resultEntity.setResultFilename(zipFile.getName());
resultEntity.setResultFileUrl(downloadUrl); resultEntity.setResultFileUrl(ossObjectKey); // 存 objectKey
resultEntity.setResultFileSize(zipFile.length()); resultEntity.setResultFileSize(zipFile.length());
resultEntity.setResultContentType("application/zip"); resultEntity.setResultContentType("application/zip");
resultEntity.setSuccess(1); resultEntity.setSuccess(1);
@@ -211,7 +209,9 @@ public class ConvertRunService {
vo.setResultId(entity.getId()); vo.setResultId(entity.getId());
vo.setSourceFilename(entity.getSourceFilename()); vo.setSourceFilename(entity.getSourceFilename());
vo.setOutputFilename(entity.getResultFilename()); vo.setOutputFilename(entity.getResultFilename());
vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1 ? entity.getResultFileUrl() : null); vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1
? ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl())
: null);
vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1); vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1);
vo.setError(entity.getErrorMessage()); vo.setError(entity.getErrorMessage());
return vo; return vo;
@@ -106,13 +106,12 @@ public class DedupeRunService {
} }
String ossObjectKey = ossStorageService.uploadResultFile(outputFile, "DEDUPE"); String ossObjectKey = ossStorageService.uploadResultFile(outputFile, "DEDUPE");
String downloadUrl = ossStorageService.generateDownloadUrl(ossObjectKey); // 只存 objectKey,不存预签名 URL
String downloadFilename = request.getFiles().size() == 1 ? inputName : outputFile.getName(); String downloadFilename = request.getFiles().size() == 1 ? inputName : outputFile.getName();
item.setSuccess(true); item.setSuccess(true);
item.setOutputFilename(downloadFilename); item.setOutputFilename(downloadFilename);
item.setDownloadUrl(downloadUrl); item.setDownloadUrl(ossStorageService.generateFreshDownloadUrl(ossObjectKey));
successCount++; successCount++;
FileResultEntity resultEntity = new FileResultEntity(); FileResultEntity resultEntity = new FileResultEntity();
@@ -120,7 +119,7 @@ public class DedupeRunService {
resultEntity.setModuleType("DEDUPE"); resultEntity.setModuleType("DEDUPE");
resultEntity.setSourceFilename(inputName); resultEntity.setSourceFilename(inputName);
resultEntity.setResultFilename(downloadFilename); resultEntity.setResultFilename(downloadFilename);
resultEntity.setResultFileUrl(downloadUrl); resultEntity.setResultFileUrl(ossObjectKey); // 存 objectKey
resultEntity.setResultFileSize(outputFile.length()); resultEntity.setResultFileSize(outputFile.length());
resultEntity.setResultContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); resultEntity.setResultContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resultEntity.setSuccess(1); resultEntity.setSuccess(1);
@@ -148,20 +147,19 @@ public class DedupeRunService {
if (folderMode && !archiveEntries.isEmpty()) { if (folderMode && !archiveEntries.isEmpty()) {
File zipFile = packageFolderDedupeResultsAsZip(request.getArchiveName(), archiveEntries); File zipFile = packageFolderDedupeResultsAsZip(request.getArchiveName(), archiveEntries);
String ossObjectKey = ossStorageService.uploadResultFile(zipFile, "DEDUPE"); String ossObjectKey = ossStorageService.uploadResultFile(zipFile, "DEDUPE");
String downloadUrl = ossStorageService.generateDownloadUrl(ossObjectKey); // 只存 objectKey
DedupeResultItemVo item = new DedupeResultItemVo(); DedupeResultItemVo item = new DedupeResultItemVo();
item.setSourceFilename(request.getArchiveName()); item.setSourceFilename(request.getArchiveName());
item.setOutputFilename(zipFile.getName()); item.setOutputFilename(zipFile.getName());
item.setSuccess(true); item.setSuccess(true);
item.setDownloadUrl(downloadUrl); item.setDownloadUrl(ossStorageService.generateFreshDownloadUrl(ossObjectKey));
FileResultEntity resultEntity = new FileResultEntity(); FileResultEntity resultEntity = new FileResultEntity();
resultEntity.setTaskId(task.getId()); resultEntity.setTaskId(task.getId());
resultEntity.setModuleType("DEDUPE"); resultEntity.setModuleType("DEDUPE");
resultEntity.setSourceFilename(request.getArchiveName()); resultEntity.setSourceFilename(request.getArchiveName());
resultEntity.setResultFilename(zipFile.getName()); resultEntity.setResultFilename(zipFile.getName());
resultEntity.setResultFileUrl(downloadUrl); resultEntity.setResultFileUrl(ossObjectKey); // 存 objectKey
resultEntity.setResultFileSize(zipFile.length()); resultEntity.setResultFileSize(zipFile.length());
resultEntity.setResultContentType("application/zip"); resultEntity.setResultContentType("application/zip");
resultEntity.setSuccess(1); resultEntity.setSuccess(1);
@@ -198,7 +196,9 @@ public class DedupeRunService {
vo.setResultId(entity.getId()); vo.setResultId(entity.getId());
vo.setSourceFilename(entity.getSourceFilename()); vo.setSourceFilename(entity.getSourceFilename());
vo.setOutputFilename(entity.getResultFilename()); vo.setOutputFilename(entity.getResultFilename());
vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1 ? entity.getResultFileUrl() : null); vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1
? ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl())
: null);
vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1); vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1);
vo.setError(entity.getErrorMessage()); vo.setError(entity.getErrorMessage());
return vo; return vo;
@@ -2,8 +2,12 @@ package com.nanri.aiimage.modules.deletebrand.controller;
import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandRunRequest; import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandRunRequest;
import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandSubmitResultRequest;
import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandTaskBatchRequest;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandHistoryVo; import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandHistoryVo;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandRunVo; import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandRunVo;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskDeletionStatusVo;
import com.nanri.aiimage.modules.deletebrand.service.DeleteBrandRunService; import com.nanri.aiimage.modules.deletebrand.service.DeleteBrandRunService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
@@ -14,6 +18,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@@ -22,17 +28,24 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/delete-brand") @RequestMapping("/api/delete-brand")
@Tag(name = "删除品牌", description = "按每个上传 Excel 的文件名匹配紫鸟店铺,并解析删除品牌表格预览。") @Tag(name = "删除品牌", description = "解析固定格式 Excel 的删除ASIN数据(暂不联动紫鸟)。")
public class DeleteBrandRunController { public class DeleteBrandRunController {
private final DeleteBrandRunService deleteBrandRunService; private final DeleteBrandRunService deleteBrandRunService;
@PostMapping("/run") @PostMapping("/run")
@Operation(summary = "执行删除品牌解析", description = "读取上传的删除品牌 Excel,按每个 Excel 文件名匹配紫鸟店铺,并返回受限预览数据和紫鸟店铺打开链接。") @Operation(summary = "执行删除品牌解析", description = "读取上传的删除品牌 Excel,按国家分组解析并在每个国家内按 ASIN 去重,返回完整 payload。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "执行成功", content = @Content(schema = @Schema(implementation = DeleteBrandRunVo.class))) @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "执行成功", content = @Content(schema = @Schema(implementation = DeleteBrandRunVo.class)))
}) })
@@ -57,4 +70,66 @@ public class DeleteBrandRunController {
deleteBrandRunService.deleteHistory(resultId, userId); deleteBrandRunService.deleteHistory(resultId, userId);
return ApiResponse.success(null); return ApiResponse.success(null);
} }
@GetMapping("/tasks/{taskId}")
@Operation(summary = "获取删除品牌任务详情", description = "根据任务ID返回任务基础信息 + Redis 中的实时行级进度(文件/国家/ASIN)。")
public ApiResponse<com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskDetailVo> getTask(
@PathVariable Long taskId) {
return ApiResponse.success(deleteBrandRunService.getTaskDetail(taskId));
}
@PostMapping("/tasks/batch")
@Operation(summary = "批量获取删除品牌任务详情", description = "合并多个 taskId 的详情查询,减少轮询期对 DB/Redis 的压力。")
public ApiResponse<DeleteBrandTaskBatchVo> getTasksBatch(@Valid @RequestBody DeleteBrandTaskBatchRequest request) {
return ApiResponse.success(deleteBrandRunService.getTaskDetails(request.getTaskIds()));
}
@GetMapping("/tasks/{taskId}/deletion-status")
@Operation(summary = "获取删除品牌任务删除状态", description = "供 Python/插件按 taskId 查询该删除品牌任务是否已被前端删空。")
public ApiResponse<DeleteBrandTaskDeletionStatusVo> getTaskDeletionStatus(
@PathVariable Long taskId,
@Parameter(name = "user_id", description = "当前登录用户 ID", required = true, in = ParameterIn.QUERY)
@RequestParam("user_id") Long userId) {
return ApiResponse.success(deleteBrandRunService.getTaskDeletionStatus(taskId, userId));
}
@PostMapping("/tasks/{taskId}/result")
@Operation(summary = "提交删除品牌处理结果", description = "插件/前端分片回传处理结果;后端累计分片并推进进度,全部完成后再执行最终组装与落库。")
public ApiResponse<Void> submitResult(
@PathVariable Long taskId,
@Valid @RequestBody DeleteBrandSubmitResultRequest request) {
deleteBrandRunService.submitResult(taskId, request);
return ApiResponse.success(null);
}
@GetMapping("/tasks/{taskId}/download")
@Operation(summary = "下载删除品牌任务结果", description = "返回任务结果文件流,便于桌面端通过 save_file_from_url 直接保存。")
public void download(@PathVariable Long taskId, jakarta.servlet.http.HttpServletResponse response) {
String url = deleteBrandRunService.resolveTaskDownloadUrl(taskId);
String filename = deleteBrandRunService.resolveTaskDownloadFilename(taskId);
if (url == null || url.isBlank()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "任务无可下载结果");
}
if (filename == null || filename.isBlank()) {
String rawPath = URI.create(url).getPath();
filename = rawPath == null ? "delete-brand_" + taskId + ".xlsx" : rawPath.substring(rawPath.lastIndexOf('/') + 1);
}
try {
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
response.setContentType("application/octet-stream");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"; filename*=UTF-8''" + encodedFilename);
try (InputStream in = URI.create(url).toURL().openStream()) {
byte[] buffer = new byte[65536];
int read;
while ((read = in.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, read);
}
response.getOutputStream().flush();
}
} catch (Exception ex) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "下载失败");
}
}
} }
@@ -0,0 +1,18 @@
package com.nanri.aiimage.modules.deletebrand.model.cache;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandCountryGroupVo;
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandPreviewRowVo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class DeleteBrandParsedFileCacheDto {
private String fileKey;
private String sourceFilename;
private String shopName;
private Integer totalRows;
private List<DeleteBrandCountryGroupVo> countries = new ArrayList<>();
private List<DeleteBrandPreviewRowVo> previewRows = new ArrayList<>();
}
@@ -0,0 +1,16 @@
package com.nanri.aiimage.modules.deletebrand.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "删除品牌插件处理后的 ASIN 结果项")
public class DeleteBrandCountryResultItemDto {
@NotBlank(message = "asin 不能为空")
@Schema(description = "删除ASIN")
private String asin;
@Schema(description = "状态")
private String status;
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.deletebrand.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌插件处理后的国家结果")
public class DeleteBrandProcessedCountryDto {
@NotBlank(message = "country 不能为空")
@Schema(description = "国家")
private String country;
@Valid
@Schema(description = "处理后的 ASIN 列表")
private List<DeleteBrandCountryResultItemDto> items = new ArrayList<>();
}
@@ -0,0 +1,48 @@
package com.nanri.aiimage.modules.deletebrand.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌单文件结果回传")
public class DeleteBrandResultFileDto {
@Schema(description = "稳定文件标识,优先使用 run 阶段返回的 fileKey")
private String fileKey;
@NotBlank(message = "sourceFilename 不能为空")
@Schema(description = "源文件名")
private String sourceFilename;
@Schema(description = "当前是第几个文件,从 1 开始")
private Integer fileIndex;
@Schema(description = "总文件数")
private Integer fileTotal;
@Schema(description = "当前分片序号,从 1 开始")
private Integer chunkIndex;
@Schema(description = "当前文件总分片数")
private Integer chunkTotal;
@Schema(description = "当前文件已处理行数")
private Integer processedRows;
@Schema(description = "当前文件总行数")
private Integer totalRows;
@Schema(description = "当前国家")
private String currentCountry;
@Schema(description = "当前 ASIN")
private String currentAsin;
@Valid
@Schema(description = "按国家分组的处理结果")
private List<DeleteBrandProcessedCountryDto> countries = new ArrayList<>();
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.deletebrand.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌结果提交请求")
public class DeleteBrandSubmitResultRequest {
@Schema(description = "可选的提交批次ID,用于幂等追踪")
private String submissionId;
@Valid
@NotEmpty(message = "files 不能为空")
@Schema(description = "按源文件维度提交结果")
private List<DeleteBrandResultFileDto> files = new ArrayList<>();
}
@@ -0,0 +1,17 @@
package com.nanri.aiimage.modules.deletebrand.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌任务批量详情请求")
public class DeleteBrandTaskBatchRequest {
@NotEmpty(message = "taskIds 不能为空")
@Schema(description = "任务ID列表")
private List<Long> taskIds = new ArrayList<>();
}
@@ -0,0 +1,17 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "删除品牌国家维度 ASIN 项")
public class DeleteBrandCountryAsinVo {
@Schema(description = "行号")
private Integer rowIndex;
@Schema(description = "删除ASIN")
private String asin;
@Schema(description = "状态")
private String status;
}
@@ -0,0 +1,20 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌国家分组")
public class DeleteBrandCountryGroupVo {
@Schema(description = "国家")
private String country;
@Schema(description = "去重后 ASIN 数")
private Integer asinCount;
@Schema(description = "ASIN 列表")
private List<DeleteBrandCountryAsinVo> items = new ArrayList<>();
}
@@ -0,0 +1,35 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "删除品牌任务实时进度详情")
public class DeleteBrandLineProgressInfoVo {
@Schema(description = "当前处理到第几个文件,从 1 开始")
private Integer file_index;
@Schema(description = "本次任务总文件数")
private Integer file_total;
@Schema(description = "当前处理文件名")
private String file_name;
@Schema(description = "当前文件已处理行数")
private Integer current_line;
@Schema(description = "当前文件总行数")
private Integer total_lines;
@Schema(description = "当前国家")
private String current_country;
@Schema(description = "当前 ASIN")
private String current_asin;
@Schema(description = "已完成文件数")
private Integer finished_files;
@Schema(description = "当前阶段:crawling/assembling/uploading/failed")
private String phase;
}
@@ -0,0 +1,14 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "删除品牌任务实时行级进度")
public class DeleteBrandLineProgressVo {
@Schema(description = "当前是否存在实时进度")
private boolean has_progress;
@Schema(description = "实时进度详情")
private DeleteBrandLineProgressInfoVo info;
}
@@ -12,6 +12,9 @@ public class DeleteBrandResultItemVo {
@Schema(description = "结果记录ID") @Schema(description = "结果记录ID")
private Long resultId; private Long resultId;
@Schema(description = "上传文件 key / 稳定文件标识")
private String fileKey;
@Schema(description = "源文件名") @Schema(description = "源文件名")
private String sourceFilename; private String sourceFilename;
@@ -30,9 +33,30 @@ public class DeleteBrandResultItemVo {
@Schema(description = "紫鸟打开链接") @Schema(description = "紫鸟打开链接")
private String openStoreUrl; private String openStoreUrl;
@Schema(description = "匹配状态: MATCHED / PENDING / CONFLICT")
private String matchStatus;
@Schema(description = "匹配说明")
private String matchMessage;
@Schema(description = "总行数") @Schema(description = "总行数")
private Integer totalRows; private Integer totalRows;
@Schema(description = "输出文件名")
private String outputFilename;
@Schema(description = "下载地址")
private String downloadUrl;
@Schema(description = "任务ID")
private Long taskId;
@Schema(description = "国家数量")
private Integer countryCount;
@Schema(description = "按国家分组的数据")
private List<DeleteBrandCountryGroupVo> countries = new ArrayList<>();
@Schema(description = "是否已截断") @Schema(description = "是否已截断")
private boolean truncated; private boolean truncated;
@@ -44,4 +68,7 @@ public class DeleteBrandResultItemVo {
@Schema(description = "错误信息") @Schema(description = "错误信息")
private String error; private String error;
@Schema(description = "由于列表来自 history 接口,增加所属任务的状态(RUNNING/SUCCESS/FAILED),协助前端准确定位执行中任务")
private String taskStatus;
} }
@@ -0,0 +1,18 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌任务批量详情响应")
public class DeleteBrandTaskBatchVo {
@Schema(description = "任务详情列表,按请求顺序返回")
private List<DeleteBrandTaskDetailVo> items = new ArrayList<>();
@Schema(description = "不存在/无权限的 taskId")
private List<Long> missingTaskIds = new ArrayList<>();
}
@@ -0,0 +1,17 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "删除品牌任务删除状态响应")
public class DeleteBrandTaskDeletionStatusVo {
@Schema(description = "任务ID")
private Long taskId;
@Schema(description = "该任务的结果记录是否已被全部删除")
private boolean deleted;
@Schema(description = "该任务当前剩余的结果记录数量")
private long remainingResultCount;
}
@@ -0,0 +1,20 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "删除品牌任务详情响应")
public class DeleteBrandTaskDetailVo {
@Schema(description = "任务基础信息")
private DeleteBrandTaskItemVo task;
@Schema(description = "实时行级进度信息,来自 Redis")
private DeleteBrandLineProgressVo line_progress;
@Schema(description = "任务结果项快照")
private List<DeleteBrandResultItemVo> items = new ArrayList<>();
}
@@ -0,0 +1,46 @@
package com.nanri.aiimage.modules.deletebrand.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Schema(description = "删除品牌任务基础信息")
public class DeleteBrandTaskItemVo {
@Schema(description = "任务ID")
private Long id;
@Schema(description = "任务编号")
private String taskNo;
@Schema(description = "任务状态")
private String status;
@Schema(description = "源文件数")
private Integer sourceFileCount;
@Schema(description = "成功文件数")
private Integer successFileCount;
@Schema(description = "失败文件数")
private Integer failedFileCount;
@Schema(description = "错误信息")
private String errorMessage;
@Schema(description = "创建时间")
private LocalDateTime createdAt;
@Schema(description = "更新时间")
private LocalDateTime updatedAt;
@Schema(description = "完成时间")
private LocalDateTime finishedAt;
@Schema(description = "下载地址(任务级)")
private String downloadUrl;
@Schema(description = "下载文件名(任务级)")
private String downloadFilename;
}
@@ -0,0 +1,108 @@
package com.nanri.aiimage.modules.deletebrand.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.config.DeleteBrandProgressProperties;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
@Service
@RequiredArgsConstructor
public class DeleteBrandStaleTaskService {
private static final String MODULE_TYPE = "DELETE_BRAND";
private final FileTaskMapper fileTaskMapper;
private final DeleteBrandTaskCacheService deleteBrandTaskCacheService;
private final DeleteBrandRunService deleteBrandRunService;
private final DeleteBrandProgressProperties deleteBrandProgressProperties;
@Scheduled(cron = "${aiimage.delete-brand-progress.stale-check-cron:0 */2 * * * *}")
public void failStaleRunningTasks() {
LocalDateTime threshold = LocalDateTime.now().minusMinutes(deleteBrandProgressProperties.getHeartbeatTimeoutMinutes());
// 先按 DB updatedAt 粗筛,避免全表扫描
java.util.List<FileTaskEntity> runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, "RUNNING")
.lt(FileTaskEntity::getUpdatedAt, threshold)
.last("limit 200"));
for (FileTaskEntity task : runningTasks) {
Map<Object, Object> progress = deleteBrandTaskCacheService.getProgress(task.getId());
boolean hasProgress = progress != null && !progress.isEmpty() && progress.containsKey("last_heartbeat_at");
boolean isActive = false;
if (progress != null && progress.containsKey("has_progress")) {
Object hpObj = progress.get("has_progress");
if (hpObj instanceof Boolean) {
isActive = (Boolean) hpObj;
} else if (hpObj instanceof String) {
isActive = Boolean.parseBoolean((String) hpObj);
}
}
long lastHeartbeatAt = 0L;
if (hasProgress) {
try {
lastHeartbeatAt = Long.parseLong(String.valueOf(progress.get("last_heartbeat_at")));
} catch (Exception ignored) {
}
}
LocalDateTime lastActivityTime;
// 只有当 has_progress 为 true 且超过 15 分钟没心跳,才认为是异常卡死
if (lastHeartbeatAt > 0 && isActive) {
// 有心跳,用最后心跳时间对比 15 分钟 (threshold 是 now - 15)
lastActivityTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastHeartbeatAt), ZoneId.systemDefault());
if (lastActivityTime.isAfter(threshold)) {
continue; // 没超时
}
} else {
// 没有心跳,或者当前处在 has_progress: false (等待用户点击下一个任务推送的静默期)
// 静默期和排队期的宽限期一样,设为 12 个小时
LocalDateTime queuedThreshold = LocalDateTime.now().minusHours(12);
if (task.getCreatedAt() != null && task.getCreatedAt().isAfter(queuedThreshold)) {
continue; // 等待下个队列推送中,不要杀它!
}
}
int updated = fileTaskMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, "RUNNING")
.set(FileTaskEntity::getStatus, "FAILED")
.set(FileTaskEntity::getErrorMessage, "结果回传长时间无响应,任务已自动失败")
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated > 0) {
deleteBrandTaskCacheService.delete(task.getId());
}
}
}
@Scheduled(cron = "${aiimage.delete-brand-progress.finalize-check-cron:30 */2 * * * *}")
public void finalizeCompletedRunningTasks() {
java.util.List<FileTaskEntity> runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, "RUNNING")
.orderByAsc(FileTaskEntity::getUpdatedAt)
.last("limit 100"));
for (FileTaskEntity task : runningTasks) {
try {
deleteBrandRunService.tryFinalizeTask(task.getId(), true);
} catch (Exception ignored) {
// 定时补偿不影响主流程;下次调度或人工重试时再处理
}
}
}
}
@@ -0,0 +1,239 @@
package com.nanri.aiimage.modules.deletebrand.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
@Service
@RequiredArgsConstructor
public class DeleteBrandTaskCacheService {
public static final String PHASE_CRAWLING = "crawling";
public static final String PHASE_ASSEMBLING = "assembling";
public static final String PHASE_UPLOADING = "uploading";
public static final String PHASE_FAILED = "failed";
private static final long PAYLOAD_TTL_HOURS = 24;
private static final long LOCAL_PARSED_PAYLOAD_CACHE_MILLIS = 3000;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final ConcurrentHashMap<Long, LocalParsedPayloadCacheEntry> parsedPayloadLocalCache = new ConcurrentHashMap<>();
public void saveParsedPayload(Long taskId, Object payload) {
try {
stringRedisTemplate.opsForValue().set(buildPayloadKey(taskId), objectMapper.writeValueAsString(payload), Duration.ofHours(PAYLOAD_TTL_HOURS));
parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(System.currentTimeMillis(), payload));
} catch (Exception ex) {
throw new BusinessException("暂存删除品牌原始数据失败");
}
}
public <T> T getParsedPayload(Long taskId, TypeReference<T> typeReference) {
if (taskId == null || taskId <= 0) {
return null;
}
long now = System.currentTimeMillis();
LocalParsedPayloadCacheEntry cached = parsedPayloadLocalCache.get(taskId);
if (cached != null && cached.isFresh(now) && cached.value() != null) {
try {
return objectMapper.convertValue(cached.value(), typeReference);
} catch (Exception ignored) {
// fallthrough to redis
}
}
String raw = stringRedisTemplate.opsForValue().get(buildPayloadKey(taskId));
if (raw == null || raw.isBlank()) {
parsedPayloadLocalCache.remove(taskId);
return null;
}
try {
T parsed = objectMapper.readValue(raw, typeReference);
parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(now, parsed));
return parsed;
} catch (Exception ex) {
throw new BusinessException("读取删除品牌原始数据失败");
}
}
public void saveProgress(Long taskId, java.util.Map<String, String> values) {
String key = buildProgressKey(taskId);
stringRedisTemplate.opsForHash().putAll(key, values);
stringRedisTemplate.expire(key, Duration.ofHours(PAYLOAD_TTL_HOURS));
}
public java.util.Map<Object, Object> getProgress(Long taskId) {
return stringRedisTemplate.opsForHash().entries(buildProgressKey(taskId));
}
public java.util.Map<Long, java.util.Map<Object, Object>> getProgressBatch(java.util.List<Long> taskIds) {
java.util.Map<Long, java.util.Map<Object, Object>> result = new java.util.LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
java.util.List<Object> pipelineResults = stringRedisTemplate.executePipelined((org.springframework.data.redis.core.RedisCallback<Object>) connection -> {
org.springframework.data.redis.serializer.RedisSerializer<String> serializer = stringRedisTemplate.getStringSerializer();
for (Long taskId : normalizedTaskIds) {
connection.hGetAll(serializer.serialize(buildProgressKey(taskId)));
}
return null;
});
for (int i = 0; i < normalizedTaskIds.size(); i++) {
Long taskId = normalizedTaskIds.get(i);
Object raw = pipelineResults != null && i < pipelineResults.size() ? pipelineResults.get(i) : null;
if (raw instanceof java.util.Map<?, ?> rawMap) {
java.util.Map<Object, Object> converted = new java.util.LinkedHashMap<>();
for (java.util.Map.Entry<?, ?> entry : rawMap.entrySet()) {
converted.put(entry.getKey(), entry.getValue());
}
result.put(taskId, converted);
} else {
result.put(taskId, java.util.Collections.emptyMap());
}
}
return result;
}
public boolean hasSameResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) {
if (chunkIndex == null || chunkIndex <= 0) {
throw new BusinessException("chunkIndex 不合法");
}
if (fileIdentity == null || fileIdentity.isBlank()) {
throw new BusinessException("fileIdentity 不能为空");
}
String field = fileIdentity.trim() + "#" + chunkIndex;
String chunkJson;
try {
chunkJson = objectMapper.writeValueAsString(chunk);
} catch (Exception ex) {
throw new BusinessException("读取删除品牌结果分片失败");
}
Object existing = stringRedisTemplate.opsForHash().get(buildResultChunksKey(taskId), field);
if (chunkJson.equals(existing)) {
stringRedisTemplate.expire(buildResultChunksKey(taskId), Duration.ofHours(PAYLOAD_TTL_HOURS));
return true;
}
return false;
}
public boolean mergeResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) {
String resultKey = buildResultChunksKey(taskId);
if (chunkIndex == null || chunkIndex <= 0) {
throw new BusinessException("chunkIndex 不合法");
}
if (fileIdentity == null || fileIdentity.isBlank()) {
throw new BusinessException("fileIdentity 不能为空");
}
String field = fileIdentity.trim() + "#" + chunkIndex;
String chunkJson;
try {
chunkJson = objectMapper.writeValueAsString(chunk);
} catch (Exception ex) {
throw new BusinessException("暂存删除品牌结果分片失败");
}
Object existing = stringRedisTemplate.opsForHash().get(resultKey, field);
if (chunkJson.equals(existing)) {
stringRedisTemplate.expire(resultKey, Duration.ofHours(PAYLOAD_TTL_HOURS));
return false;
}
stringRedisTemplate.opsForHash().put(resultKey, field, chunkJson);
stringRedisTemplate.expire(resultKey, Duration.ofHours(PAYLOAD_TTL_HOURS));
return true;
}
public java.util.Map<String, java.util.List<String>> groupResultChunkJsonByFile(Long taskId) {
java.util.Map<Object, Object> stored = stringRedisTemplate.opsForHash().entries(buildResultChunksKey(taskId));
java.util.Map<String, java.util.List<String>> grouped = new java.util.LinkedHashMap<>();
for (java.util.Map.Entry<Object, Object> entry : stored.entrySet()) {
if (!(entry.getKey() instanceof String field) || !(entry.getValue() instanceof String raw) || raw.isBlank()) {
continue;
}
int sep = field.lastIndexOf('#');
if (sep <= 0) {
continue;
}
String fileIdentity = field.substring(0, sep);
grouped.computeIfAbsent(fileIdentity, ignored -> new java.util.ArrayList<>()).add(raw);
}
return grouped;
}
public void delete(Long taskId) {
parsedPayloadLocalCache.remove(taskId);
stringRedisTemplate.delete(buildPayloadKey(taskId));
stringRedisTemplate.delete(buildProgressKey(taskId));
stringRedisTemplate.delete(buildResultChunksKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
}
public void saveTaskCache(com.nanri.aiimage.modules.task.model.entity.FileTaskEntity task) {
if (task == null || task.getId() == null) return;
try {
stringRedisTemplate.opsForValue().set(buildTaskEntityKey(task.getId()), objectMapper.writeValueAsString(task), Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ignored) {
}
}
public java.util.Map<Long, com.nanri.aiimage.modules.task.model.entity.FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
java.util.Map<Long, com.nanri.aiimage.modules.task.model.entity.FileTaskEntity> result = new java.util.LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) return result;
java.util.List<Long> normalized = taskIds.stream().filter(id -> id != null && id > 0).distinct().toList();
if (normalized.isEmpty()) return result;
java.util.List<String> keys = normalized.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values = stringRedisTemplate.opsForValue().multiGet(keys);
for (int i = 0; i < normalized.size(); i++) {
Long taskId = normalized.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val != null && !val.isBlank()) {
try {
result.put(taskId, objectMapper.readValue(val, com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class));
} catch (Exception ignored) {
}
}
}
return result;
}
private String buildTaskEntityKey(Long taskId) {
return "delete-brand:task:entity:" + taskId;
}
private record LocalParsedPayloadCacheEntry(long cachedAtMillis, Object value) {
private boolean isFresh(long now) {
return now - cachedAtMillis <= LOCAL_PARSED_PAYLOAD_CACHE_MILLIS;
}
}
private String buildPayloadKey(Long taskId) {
return "delete-brand:task:parsed-payload:" + taskId;
}
private String buildProgressKey(Long taskId) {
return "delete-brand:task:progress:" + taskId;
}
private String buildResultChunksKey(Long taskId) {
return "delete-brand:task:result-chunks:" + taskId;
}
}
@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.net.URI;
import java.net.URL; import java.net.URL;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
@@ -17,13 +18,13 @@ public class OssStorageService {
private final OssProperties ossProperties; private final OssProperties ossProperties;
/**
* 上传结果文件到 OSS,返回 objectKey(非预签名 URL)。
* 调用方应存储 objectKey,下载时通过 generateFreshDownloadUrl 按需生成链接。
*/
public String uploadResultFile(File file, String moduleType) { public String uploadResultFile(File file, String moduleType) {
String objectKey = String.format("result/%s/%s/%s", moduleType.toLowerCase(), UUID.randomUUID(), file.getName()); String objectKey = String.format("result/%s/%s/%s", moduleType.toLowerCase(), UUID.randomUUID(), file.getName());
OSS ossClient = new OSSClientBuilder().build( OSS ossClient = buildClient();
"https://" + ossProperties.getEndpoint(),
ossProperties.getAccessKeyId(),
ossProperties.getAccessKeySecret()
);
try { try {
ossClient.putObject(ossProperties.getBucket(), objectKey, file); ossClient.putObject(ossProperties.getBucket(), objectKey, file);
return objectKey; return objectKey;
@@ -32,12 +33,11 @@ public class OssStorageService {
} }
} }
/**
* 根据 objectKey 生成预签名下载 URL(1小时有效)。
*/
public String generateDownloadUrl(String objectKey) { public String generateDownloadUrl(String objectKey) {
OSS ossClient = new OSSClientBuilder().build( OSS ossClient = buildClient();
"https://" + ossProperties.getEndpoint(),
ossProperties.getAccessKeyId(),
ossProperties.getAccessKeySecret()
);
try { try {
Date expiration = new Date(System.currentTimeMillis() + 3600_000L); Date expiration = new Date(System.currentTimeMillis() + 3600_000L);
URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), objectKey, expiration); URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), objectKey, expiration);
@@ -46,4 +46,52 @@ public class OssStorageService {
ossClient.shutdown(); ossClient.shutdown();
} }
} }
/**
* 获取公开(无签名)URL,格式:https://{bucket}.{endpoint}/{objectKey}
*/
public String getPublicUrl(String objectKey) {
if (objectKey == null || objectKey.isBlank()) {
return null;
}
return String.format("https://%s.%s/%s", ossProperties.getBucket(), ossProperties.getEndpoint(), objectKey);
}
/**
* 从存储值中解析出 objectKey,兼容两种格式:
* - 旧格式:完整预签名 URL(https://bucket.endpoint/objectKey?Expires=...)
* - 新格式:直接是 objectKey(如 result/dedupe/uuid/file.xlsx)
*/
public String resolveObjectKey(String value) {
if (value == null || value.isBlank()) {
return value;
}
try {
if (value.startsWith("http://") || value.startsWith("https://")) {
String path = URI.create(value).getPath();
return path.startsWith("/") ? path.substring(1) : path;
}
} catch (Exception ignored) {
}
return value;
}
/**
* 根据存储值(objectKey 或旧格式预签名 URL)生成新鲜的预签名下载 URL。
* 供各模块 listHistory 使用,每次按需生成,避免旧 URL 1小时后过期。
*/
public String generateFreshDownloadUrl(String value) {
if (value == null || value.isBlank()) {
return null;
}
return generateDownloadUrl(resolveObjectKey(value));
}
private OSS buildClient() {
return new OSSClientBuilder().build(
"https://" + ossProperties.getEndpoint(),
ossProperties.getAccessKeyId(),
ossProperties.getAccessKeySecret()
);
}
} }
@@ -0,0 +1,79 @@
package com.nanri.aiimage.modules.shopkey.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyPageVo;
import com.nanri.aiimage.modules.shopkey.service.ShopKeyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin/shop-keys")
@Tag(name = "店铺密钥管理", description = "维护店铺密钥,支持增删改查。")
public class ShopKeyController {
private final ShopKeyService shopKeyService;
@GetMapping
@Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class)))
})
public ApiResponse<ShopKeyPageVo> page(
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) {
return ApiResponse.success(shopKeyService.page(page, pageSize));
}
@PostMapping
@Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法")
})
public ApiResponse<ShopKeyItemVo> create(@Valid @RequestBody ShopKeyCreateRequest request) {
return ApiResponse.success("创建成功", shopKeyService.create(request));
}
@PutMapping("/{id}")
@Operation(summary = "更新店铺密钥", description = "按 ID 更新一条店铺密钥记录。")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
})
public ApiResponse<ShopKeyItemVo> update(
@Parameter(description = "主键ID", required = true) @PathVariable Long id,
@Valid @RequestBody ShopKeyUpdateRequest request) {
return ApiResponse.success("更新成功", shopKeyService.update(id, request));
}
@DeleteMapping("/{id}")
@Operation(summary = "删除店铺密钥", description = "按 ID 删除一条店铺密钥记录。")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
})
public ApiResponse<Void> delete(@Parameter(description = "主键ID", required = true) @PathVariable Long id) {
shopKeyService.delete(id);
return ApiResponse.success("删除成功", null);
}
}
@@ -0,0 +1,9 @@
package com.nanri.aiimage.modules.shopkey.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ShopKeyMapper extends BaseMapper<ShopKeyEntity> {
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.shopkey.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
@Schema(description = "店铺密钥新增请求")
public class ShopKeyCreateRequest {
@NotBlank(message = "紫鸟账号名称不能为空")
@Size(max = 128, message = "紫鸟账号名称长度不能超过128个字符")
@Schema(description = "紫鸟账号名称", requiredMode = Schema.RequiredMode.REQUIRED)
private String ziniaoAccountName;
@NotBlank(message = "紫鸟令牌不能为空")
@Size(max = 512, message = "紫鸟令牌长度不能超过512个字符")
@Schema(description = "紫鸟令牌", requiredMode = Schema.RequiredMode.REQUIRED)
private String ziniaoToken;
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.shopkey.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
@Schema(description = "店铺密钥更新请求")
public class ShopKeyUpdateRequest {
@NotBlank(message = "紫鸟账号名称不能为空")
@Size(max = 128, message = "紫鸟账号名称长度不能超过128个字符")
@Schema(description = "紫鸟账号名称", requiredMode = Schema.RequiredMode.REQUIRED)
private String ziniaoAccountName;
@NotBlank(message = "紫鸟令牌不能为空")
@Size(max = 512, message = "紫鸟令牌长度不能超过512个字符")
@Schema(description = "紫鸟令牌", requiredMode = Schema.RequiredMode.REQUIRED)
private String ziniaoToken;
}
@@ -0,0 +1,20 @@
package com.nanri.aiimage.modules.shopkey.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("biz_shop_key")
public class ShopKeyEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String ziniaoAccountName;
private String ziniaoToken;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,26 @@
package com.nanri.aiimage.modules.shopkey.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Schema(description = "店铺密钥项")
public class ShopKeyItemVo {
@Schema(description = "主键ID")
private Long id;
@Schema(description = "紫鸟账号名称")
private String ziniaoAccountName;
@Schema(description = "紫鸟令牌")
private String ziniaoToken;
@Schema(description = "创建时间")
private LocalDateTime createdAt;
@Schema(description = "修改时间")
private LocalDateTime updatedAt;
}
@@ -0,0 +1,23 @@
package com.nanri.aiimage.modules.shopkey.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(description = "店铺密钥分页结果")
public class ShopKeyPageVo {
@Schema(description = "列表")
private List<ShopKeyItemVo> items;
@Schema(description = "总数")
private Long total;
@Schema(description = "页码")
private Long page;
@Schema(description = "每页数量")
private Long pageSize;
}
@@ -0,0 +1,109 @@
package com.nanri.aiimage.modules.shopkey.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyPageVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopKeyService {
private final ShopKeyMapper shopKeyMapper;
private final ZiniaoShopIndexService ziniaoShopIndexService;
public ShopKeyPageVo page(long page, long pageSize) {
long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
LambdaQueryWrapper<ShopKeyEntity> query = new LambdaQueryWrapper<ShopKeyEntity>()
.orderByDesc(ShopKeyEntity::getId);
Long total = shopKeyMapper.selectCount(query);
List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize))
.stream()
.map(this::toItemVo)
.toList();
ShopKeyPageVo vo = new ShopKeyPageVo();
vo.setItems(items);
vo.setTotal(total);
vo.setPage(safePage);
vo.setPageSize(safePageSize);
return vo;
}
@Transactional
public ShopKeyItemVo create(ShopKeyCreateRequest request) {
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
String ziniaoToken = normalizeRequired(request.getZiniaoToken(), "紫鸟令牌不能为空");
ShopKeyEntity entity = new ShopKeyEntity();
entity.setZiniaoAccountName(ziniaoAccountName);
entity.setZiniaoToken(ziniaoToken);
shopKeyMapper.insert(entity);
triggerShopIndexRefresh();
return toItemVo(getById(entity.getId()));
}
@Transactional
public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request) {
ShopKeyEntity entity = getById(id);
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
String ziniaoToken = normalizeRequired(request.getZiniaoToken(), "紫鸟令牌不能为空");
entity.setZiniaoAccountName(ziniaoAccountName);
entity.setZiniaoToken(ziniaoToken);
shopKeyMapper.updateById(entity);
triggerShopIndexRefresh();
return toItemVo(getById(id));
}
@Transactional
public void delete(Long id) {
ShopKeyEntity entity = getById(id);
shopKeyMapper.deleteById(entity.getId());
triggerShopIndexRefresh();
}
private ShopKeyEntity getById(Long id) {
ShopKeyEntity entity = shopKeyMapper.selectById(id);
if (entity == null) {
throw new BusinessException("店铺密钥不存在");
}
return entity;
}
private String normalizeRequired(String value, String message) {
String normalized = value == null ? "" : value.trim();
if (normalized.isEmpty()) {
throw new BusinessException(message);
}
return normalized;
}
private ShopKeyItemVo toItemVo(ShopKeyEntity entity) {
ShopKeyItemVo vo = new ShopKeyItemVo();
vo.setId(entity.getId());
vo.setZiniaoAccountName(entity.getZiniaoAccountName());
vo.setZiniaoToken(entity.getZiniaoToken());
vo.setCreatedAt(entity.getCreatedAt());
vo.setUpdatedAt(entity.getUpdatedAt());
return vo;
}
private void triggerShopIndexRefresh() {
try {
ziniaoShopIndexService.invalidateIndex();
} catch (Exception ex) {
log.warn("[ziniao-index] refresh trigger failed after shop key change: {}", ex.getMessage());
}
}
}
@@ -123,8 +123,7 @@ public class SplitRunService {
if (!allChunkResults.isEmpty()) { if (!allChunkResults.isEmpty()) {
File zipFile = packageTaskSplitResultsAsZip(request.getArchiveName(), successSourceNames, allChunkResults); File zipFile = packageTaskSplitResultsAsZip(request.getArchiveName(), successSourceNames, allChunkResults);
String ossObjectKey = ossStorageService.uploadResultFile(zipFile, MODULE_TYPE); String ossObjectKey = ossStorageService.uploadResultFile(zipFile, MODULE_TYPE);
String downloadUrl = ossStorageService.generateDownloadUrl(ossObjectKey); // 只存 objectKey
SplitResultItemVo item = new SplitResultItemVo(); SplitResultItemVo item = new SplitResultItemVo();
item.setSourceFilename(folderMode && request.getArchiveName() != null && !request.getArchiveName().isBlank() item.setSourceFilename(folderMode && request.getArchiveName() != null && !request.getArchiveName().isBlank()
? request.getArchiveName() ? request.getArchiveName()
@@ -132,7 +131,7 @@ public class SplitRunService {
item.setOutputFilename(zipFile.getName()); item.setOutputFilename(zipFile.getName());
item.setSuccess(true); item.setSuccess(true);
item.setRowCount(allChunkResults.stream().mapToInt(TaskSplitChunkResult::rowCount).sum()); item.setRowCount(allChunkResults.stream().mapToInt(TaskSplitChunkResult::rowCount).sum());
item.setDownloadUrl(downloadUrl); item.setDownloadUrl(ossStorageService.generateFreshDownloadUrl(ossObjectKey));
item.setEntryCount(allChunkResults.size()); item.setEntryCount(allChunkResults.size());
item.setEntries(allChunkResults.stream().map(this::toArchiveEntry).toList()); item.setEntries(allChunkResults.stream().map(this::toArchiveEntry).toList());
@@ -141,7 +140,7 @@ public class SplitRunService {
resultEntity.setModuleType(MODULE_TYPE); resultEntity.setModuleType(MODULE_TYPE);
resultEntity.setSourceFilename(item.getSourceFilename()); resultEntity.setSourceFilename(item.getSourceFilename());
resultEntity.setResultFilename(zipFile.getName()); resultEntity.setResultFilename(zipFile.getName());
resultEntity.setResultFileUrl(downloadUrl); resultEntity.setResultFileUrl(ossObjectKey); // 存 objectKey
resultEntity.setResultFileSize(zipFile.length()); resultEntity.setResultFileSize(zipFile.length());
resultEntity.setResultContentType(ZIP_CONTENT_TYPE); resultEntity.setResultContentType(ZIP_CONTENT_TYPE);
resultEntity.setRowCount(item.getRowCount()); resultEntity.setRowCount(item.getRowCount());
@@ -179,7 +178,9 @@ public class SplitRunService {
vo.setResultId(entity.getId()); vo.setResultId(entity.getId());
vo.setSourceFilename(entity.getSourceFilename()); vo.setSourceFilename(entity.getSourceFilename());
vo.setOutputFilename(entity.getResultFilename()); vo.setOutputFilename(entity.getResultFilename());
vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1 ? entity.getResultFileUrl() : null); vo.setDownloadUrl(entity.getSuccess() != null && entity.getSuccess() == 1
? ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl())
: null);
vo.setRowCount(entity.getRowCount()); vo.setRowCount(entity.getRowCount());
vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1); vo.setSuccess(entity.getSuccess() != null && entity.getSuccess() == 1);
vo.setError(entity.getErrorMessage()); vo.setError(entity.getErrorMessage());
@@ -6,13 +6,11 @@ import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo;
import java.util.List; import java.util.List;
public interface ZiniaoClient { public interface ZiniaoClient {
String getAppToken(); Long getCompanyIdByApiKey(String apiKey);
Long getCompanyIdByApiKey(); List<ZiniaoStaffItemVo> listStaff(String apiKey, Long companyId);
List<ZiniaoStaffItemVo> listStaff(Long companyId); List<ZiniaoShopCacheDto> listUserStores(String apiKey, Long companyId, Long userId);
List<ZiniaoShopCacheDto> listUserStores(Long companyId, Long userId, String userToken); String getUserLoginToken(String apiKey, Long companyId, Long userId);
String getUserLoginToken(Long companyId, Long userId);
} }
@@ -6,8 +6,8 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.ZiniaoProperties; import com.nanri.aiimage.config.ZiniaoProperties;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopCacheDto; import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopCacheDto;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoSessionCacheService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -24,39 +24,10 @@ public class ZiniaoClientImpl implements ZiniaoClient {
private final ZiniaoProperties ziniaoProperties; private final ZiniaoProperties ziniaoProperties;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final ZiniaoSessionCacheService ziniaoSessionCacheService;
@Override @Override
public String getAppToken() { public Long getCompanyIdByApiKey(String apiKey) {
String cachedToken = ziniaoSessionCacheService.getAppToken(); String raw = getWithApiKey(apiKey, "/app/builtin/company", "获取 companyId");
if (cachedToken != null && !cachedToken.isBlank()) {
return cachedToken;
}
String raw = postWithApiKeyEmptyJsonBody(ziniaoProperties.getAppTokenPath(), "获取 appToken");
try {
JsonNode root = objectMapper.readTree(raw);
JsonNode data = firstNonNull(root.get("data"), root.get("result"), root);
String token = text(firstNonNull(
data == null ? null : data.get("appAuthToken"),
data == null ? null : data.get("appToken"),
root.get("appAuthToken"),
root.get("appToken")
));
if (token == null || token.isBlank()) {
throw new BusinessException("紫鸟 appToken 响应缺少 token");
}
ziniaoSessionCacheService.saveAppToken(token);
return token;
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
throw new BusinessException("解析紫鸟 appToken 响应失败");
}
}
@Override
public Long getCompanyIdByApiKey() {
String raw = getWithApiKey("/app/builtin/company", "获取 companyId");
try { try {
JsonNode root = objectMapper.readTree(raw); JsonNode root = objectMapper.readTree(raw);
JsonNode data = firstNonNull(root.get("data"), root.get("result"), root); JsonNode data = firstNonNull(root.get("data"), root.get("result"), root);
@@ -73,8 +44,8 @@ public class ZiniaoClientImpl implements ZiniaoClient {
} }
@Override @Override
public List<ZiniaoStaffItemVo> listStaff(Long companyId) { public List<ZiniaoStaffItemVo> listStaff(String apiKey, Long companyId) {
String raw = postWithApiKey(ziniaoProperties.getStaffListPath(), Map.of( String raw = postWithApiKey(apiKey, ziniaoProperties.getStaffListPath(), Map.of(
"companyId", String.valueOf(companyId), "companyId", String.valueOf(companyId),
"level", "", "level", "",
"isAccurate", "", "isAccurate", "",
@@ -104,21 +75,21 @@ public class ZiniaoClientImpl implements ZiniaoClient {
} }
@Override @Override
public List<ZiniaoShopCacheDto> listUserStores(Long companyId, Long userId, String userToken) { public List<ZiniaoShopCacheDto> listUserStores(String apiKey, Long companyId, Long userId) {
String raw = postWithAuthorization(ziniaoProperties.getUserStoresPath(), userToken, Map.of( String raw = postWithApiKey(apiKey, ziniaoProperties.getUserStoresPath(), Map.of(
"companyId", companyId, "companyId", String.valueOf(companyId),
"userId", userId, "isAccurate", "",
"limit", "100",
"storeName", "", "storeName", "",
"isAccurate", 1, "page", "1",
"page", 1, "userId", String.valueOf(userId)
"limit", 10
), "获取员工店铺列表"); ), "获取员工店铺列表");
return parseUserStores(raw); return parseUserStores(raw);
} }
@Override @Override
public String getUserLoginToken(Long companyId, Long userId) { public String getUserLoginToken(String apiKey, Long companyId, Long userId) {
String raw = postWithApiKey(ziniaoProperties.getUserLoginTokenPath(), Map.of( String raw = postWithApiKey(apiKey, ziniaoProperties.getUserLoginTokenPath(), Map.of(
"companyId", String.valueOf(companyId), "companyId", String.valueOf(companyId),
"userId", String.valueOf(userId) "userId", String.valueOf(userId)
), "获取员工登录 token"); ), "获取员工登录 token");
@@ -128,7 +99,15 @@ public class ZiniaoClientImpl implements ZiniaoClient {
throw new BusinessException("获取紫鸟员工登录 token 失败: " + Objects.toString(text(root.get("msg")), "未知错误")); throw new BusinessException("获取紫鸟员工登录 token 失败: " + Objects.toString(text(root.get("msg")), "未知错误"));
} }
JsonNode data = firstNonNull(root.get("data"), root.get("result")); JsonNode data = firstNonNull(root.get("data"), root.get("result"));
JsonNode payload = firstNonNull(
data == null ? null : data.get("data"),
data == null ? null : data.get("result"),
data,
root
);
String token = text(firstNonNull( String token = text(firstNonNull(
payload == null ? null : payload.get("token"),
payload == null ? null : payload.get("loginToken"),
data == null ? null : data.get("token"), data == null ? null : data.get("token"),
data == null ? null : data.get("loginToken"), data == null ? null : data.get("loginToken"),
root.get("token"), root.get("token"),
@@ -146,38 +125,24 @@ public class ZiniaoClientImpl implements ZiniaoClient {
} }
private String getWithApiKey(String path, String action) { private String getWithApiKey(String apiKey, String path, String action) {
String apiKey = requireText(ziniaoProperties.getApiKey(), "紫鸟 apiKey 未配置");
String raw = getRestClient().get() String raw = getRestClient().get()
.uri(joinUrl(ziniaoProperties.getBaseUrl(), path)) .uri(joinUrl(ziniaoProperties.getBaseUrl(), path))
.headers(headers -> headers.setBearerAuth(apiKey)) .headers(headers -> applyAuthorization(headers, apiKey))
.retrieve() .retrieve()
.body(String.class); .onStatus(HttpStatusCode::isError, (req, res) -> {
validateSuccess(raw, action, path); // 保留响应体,交给后续 validateSuccess 统一解析
return raw;
}
private String postWithApiKeyEmptyJsonBody(String path, String action) {
String apiKey = requireText(ziniaoProperties.getApiKey(), "紫鸟 apiKey 未配置");
String raw = getRestClient().post()
.uri(joinUrl(ziniaoProperties.getBaseUrl(), path))
.headers(headers -> {
headers.setBearerAuth(apiKey);
headers.setContentType(MediaType.APPLICATION_JSON);
}) })
.body("")
.retrieve()
.body(String.class); .body(String.class);
validateSuccess(raw, action, path); validateSuccess(raw, action, path);
return raw; return raw;
} }
private String postWithApiKey(String path, Map<String, Object> body, String action) { private String postWithApiKey(String apiKey, String path, Map<String, Object> body, String action) {
String apiKey = requireText(ziniaoProperties.getApiKey(), "紫鸟 apiKey 未配置");
RestClient.RequestBodySpec request = getRestClient().post() RestClient.RequestBodySpec request = getRestClient().post()
.uri(joinUrl(ziniaoProperties.getBaseUrl(), path)) .uri(joinUrl(ziniaoProperties.getBaseUrl(), path))
.headers(headers -> { .headers(headers -> {
headers.setBearerAuth(apiKey); applyAuthorization(headers, apiKey);
headers.setContentType(MediaType.APPLICATION_JSON); headers.setContentType(MediaType.APPLICATION_JSON);
}); });
if (body != null) { if (body != null) {
@@ -185,6 +150,9 @@ public class ZiniaoClientImpl implements ZiniaoClient {
} }
String raw = request String raw = request
.retrieve() .retrieve()
.onStatus(HttpStatusCode::isError, (req, res) -> {
// 保留响应体,交给后续 validateSuccess 统一解析 code/sub_code/sub_msg
})
.body(String.class); .body(String.class);
validateSuccess(raw, action, path); validateSuccess(raw, action, path);
return raw; return raw;
@@ -195,7 +163,11 @@ public class ZiniaoClientImpl implements ZiniaoClient {
RestClient.RequestBodySpec request = getRestClient().post() RestClient.RequestBodySpec request = getRestClient().post()
.uri(joinUrl(ziniaoProperties.getBaseUrl(), path)) .uri(joinUrl(ziniaoProperties.getBaseUrl(), path))
.headers(headers -> { .headers(headers -> {
if (token.regionMatches(true, 0, "Bearer ", 0, 7)) {
headers.set("Authorization", token); headers.set("Authorization", token);
} else {
headers.setBearerAuth(token);
}
headers.setContentType(MediaType.APPLICATION_JSON); headers.setContentType(MediaType.APPLICATION_JSON);
}); });
if (body != null) { if (body != null) {
@@ -208,11 +180,42 @@ public class ZiniaoClientImpl implements ZiniaoClient {
return raw; return raw;
} }
private void applyAuthorization(org.springframework.http.HttpHeaders headers, String apiKey) {
String token = requireText(apiKey, "紫鸟 apiKey 未配置");
if (token.regionMatches(true, 0, "Bearer ", 0, 7)) {
headers.set("Authorization", token);
} else {
headers.setBearerAuth(token);
}
}
private void validateSuccess(String raw, String action, String path) { private void validateSuccess(String raw, String action, String path) {
try { try {
JsonNode root = objectMapper.readTree(raw); JsonNode root = objectMapper.readTree(raw);
if (!success(root)) { if (!success(root)) {
throw new BusinessException("紫鸟接口返回失败(" + action + ", " + path + "): " + Objects.toString(text(root.get("msg")), "未知错误")); String code = Objects.toString(text(root.get("code")), "");
String msg = Objects.toString(text(root.get("msg")), "未知错误");
String subCode = Objects.toString(text(root.get("sub_code")), "");
String subMsg = Objects.toString(text(root.get("sub_msg")), "");
StringBuilder detail = new StringBuilder();
if (!code.isBlank()) {
detail.append("code=").append(code);
}
if (!subCode.isBlank()) {
if (!detail.isEmpty()) detail.append(", ");
detail.append("sub_code=").append(subCode);
}
if (!subMsg.isBlank()) {
if (!detail.isEmpty()) detail.append(", ");
detail.append("sub_msg=").append(subMsg);
}
if (!detail.isEmpty()) {
detail.append(", ");
}
detail.append("msg=").append(msg);
throw new BusinessException("紫鸟接口返回失败(" + action + ", " + path + "): " + detail);
} }
} catch (BusinessException ex) { } catch (BusinessException ex) {
throw ex; throw ex;
@@ -284,7 +287,13 @@ public class ZiniaoClientImpl implements ZiniaoClient {
private List<ZiniaoShopCacheDto> parseUserStores(String raw) { private List<ZiniaoShopCacheDto> parseUserStores(String raw) {
try { try {
JsonNode root = objectMapper.readTree(raw); JsonNode root = objectMapper.readTree(raw);
JsonNode itemsNode = firstNonNull(root.get("data"), root.get("result")); JsonNode wrapper = firstNonNull(root.get("data"), root.get("result"), root);
JsonNode itemsNode = firstNonNull(
wrapper == null ? null : wrapper.get("data"),
wrapper == null ? null : wrapper.get("items"),
wrapper
);
List<ZiniaoShopCacheDto> items = new ArrayList<>(); List<ZiniaoShopCacheDto> items = new ArrayList<>();
if (itemsNode != null && itemsNode.isArray()) { if (itemsNode != null && itemsNode.isArray()) {
for (JsonNode itemNode : itemsNode) { for (JsonNode itemNode : itemsNode) {
@@ -1,12 +1,14 @@
package com.nanri.aiimage.modules.ziniao.controller; package com.nanri.aiimage.modules.ziniao.controller;
import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopIndexRefreshCursorDto;
import com.nanri.aiimage.modules.ziniao.model.dto.ZiniaoOpenShopRequest; import com.nanri.aiimage.modules.ziniao.model.dto.ZiniaoOpenShopRequest;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoOpenShopVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoOpenShopVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoSessionVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoSessionVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopListVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopListVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffListVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffListVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoAuthService; import com.nanri.aiimage.modules.ziniao.service.ZiniaoAuthService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
@@ -28,6 +30,7 @@ import org.springframework.web.bind.annotation.RestController;
public class ZiniaoAuthController { public class ZiniaoAuthController {
private final ZiniaoAuthService ziniaoAuthService; private final ZiniaoAuthService ziniaoAuthService;
private final ZiniaoShopIndexService ziniaoShopIndexService;
@GetMapping("/session") @GetMapping("/session")
@Operation(summary = "获取紫鸟会话状态", description = "自动获取或复用 appToken,并返回 companyId、当前员工 userId、脱敏 token 和当前店铺信息。") @Operation(summary = "获取紫鸟会话状态", description = "自动获取或复用 appToken,并返回 companyId、当前员工 userId、脱敏 token 和当前店铺信息。")
@@ -47,6 +50,12 @@ public class ZiniaoAuthController {
return ApiResponse.success(ziniaoAuthService.listStaff()); return ApiResponse.success(ziniaoAuthService.listStaff());
} }
@GetMapping("/index-refresh")
@Operation(summary = "获取紫鸟店铺索引刷新状态", description = "返回后台定时刷新紫鸟店铺索引的最近一次执行状态、时间和无效 userId 样本。")
public ApiResponse<ZiniaoShopIndexRefreshCursorDto> getIndexRefreshStatus() {
return ApiResponse.success(ziniaoShopIndexService.getRefreshCursor());
}
@GetMapping("/shops") @GetMapping("/shops")
@Operation(summary = "获取员工可见店铺列表", description = "先通过 API Key 获取 companyId,再按员工 userId 查询该员工有权限的店铺列表,并缓存到当前 session。") @Operation(summary = "获取员工可见店铺列表", description = "先通过 API Key 获取 companyId,再按员工 userId 查询该员工有权限的店铺列表,并缓存到当前 session。")
@ApiResponses({ @ApiResponses({
@@ -0,0 +1,9 @@
package com.nanri.aiimage.modules.ziniao.memory.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.ziniao.memory.model.entity.ZiniaoMemoryStoreEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ZiniaoMemoryStoreMapper extends BaseMapper<ZiniaoMemoryStoreEntity> {
}
@@ -0,0 +1,22 @@
package com.nanri.aiimage.modules.ziniao.memory.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("biz_ziniao_memory_store")
public class ZiniaoMemoryStoreEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String cacheType;
private String cacheKey;
private String payloadJson;
private LocalDateTime expiresAt;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,187 @@
package com.nanri.aiimage.modules.ziniao.memory.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.ziniao.memory.mapper.ZiniaoMemoryStoreMapper;
import com.nanri.aiimage.modules.ziniao.memory.model.entity.ZiniaoMemoryStoreEntity;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ZiniaoMemoryStoreService {
private final ZiniaoMemoryStoreMapper ziniaoMemoryStoreMapper;
private final ObjectMapper objectMapper;
public <T> Optional<T> get(String cacheType, String cacheKey, Class<T> valueType) {
ZiniaoMemoryStoreEntity entity = findOne(cacheType, cacheKey);
if (entity == null) {
return Optional.empty();
}
if (isExpired(entity)) {
ziniaoMemoryStoreMapper.deleteById(entity.getId());
return Optional.empty();
}
try {
return Optional.ofNullable(objectMapper.readValue(entity.getPayloadJson(), valueType));
} catch (Exception ex) {
throw new BusinessException("读取紫鸟记忆存储失败");
}
}
public <T> Optional<T> get(String cacheType, String cacheKey, JavaType javaType) {
ZiniaoMemoryStoreEntity entity = findOne(cacheType, cacheKey);
if (entity == null) {
return Optional.empty();
}
if (isExpired(entity)) {
ziniaoMemoryStoreMapper.deleteById(entity.getId());
return Optional.empty();
}
try {
@SuppressWarnings("unchecked")
T value = (T) objectMapper.readValue(entity.getPayloadJson(), javaType);
return Optional.ofNullable(value);
} catch (Exception ex) {
throw new BusinessException("读取紫鸟记忆存储失败");
}
}
public <E> Optional<List<E>> getList(String cacheType, String cacheKey, Class<E> elementType) {
JavaType type = objectMapper.getTypeFactory().constructCollectionType(List.class, elementType);
return get(cacheType, cacheKey, type);
}
public <T> List<T> listByType(String cacheType, Class<T> valueType, int limit) {
String normalizedType = normalizeRequired(cacheType, "cacheType 不能为空");
int safeLimit = Math.max(limit, 1);
List<ZiniaoMemoryStoreEntity> entities = ziniaoMemoryStoreMapper.selectList(new LambdaQueryWrapper<ZiniaoMemoryStoreEntity>()
.eq(ZiniaoMemoryStoreEntity::getCacheType, normalizedType)
.orderByAsc(ZiniaoMemoryStoreEntity::getCacheKey)
.last("LIMIT " + safeLimit));
if (entities.isEmpty()) {
return List.of();
}
LocalDateTime now = LocalDateTime.now();
return entities.stream()
.filter(entity -> entity.getExpiresAt() != null && entity.getExpiresAt().isAfter(now))
.map(entity -> deserialize(entity.getPayloadJson(), valueType))
.filter(Objects::nonNull)
.toList();
}
@Transactional
public void put(String cacheType, String cacheKey, Object payload, Duration ttl) {
String normalizedType = normalizeRequired(cacheType, "cacheType 不能为空");
String normalizedKey = normalizeRequired(cacheKey, "cacheKey 不能为空");
if (ttl == null || ttl.isZero() || ttl.isNegative()) {
throw new BusinessException("ttl 不合法");
}
String payloadJson;
try {
payloadJson = objectMapper.writeValueAsString(payload);
} catch (Exception ex) {
throw new BusinessException("写入紫鸟记忆存储失败");
}
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = now.plusSeconds(ttl.getSeconds());
ZiniaoMemoryStoreEntity entity = findOne(normalizedType, normalizedKey);
if (entity == null) {
entity = new ZiniaoMemoryStoreEntity();
entity.setCacheType(normalizedType);
entity.setCacheKey(normalizedKey);
entity.setPayloadJson(payloadJson);
entity.setExpiresAt(expiresAt);
entity.setCreatedAt(now);
entity.setUpdatedAt(now);
ziniaoMemoryStoreMapper.insert(entity);
return;
}
entity.setPayloadJson(payloadJson);
entity.setExpiresAt(expiresAt);
entity.setUpdatedAt(now);
ziniaoMemoryStoreMapper.updateById(entity);
}
@Transactional
public void delete(String cacheType, String cacheKey) {
ZiniaoMemoryStoreEntity entity = findOne(cacheType, cacheKey);
if (entity != null) {
ziniaoMemoryStoreMapper.deleteById(entity.getId());
}
}
@Transactional
public int deleteByType(String cacheType, int limit) {
String normalizedType = normalizeRequired(cacheType, "cacheType 不能为空");
int safeLimit = Math.max(limit, 1);
List<ZiniaoMemoryStoreEntity> entities = ziniaoMemoryStoreMapper.selectList(new LambdaQueryWrapper<ZiniaoMemoryStoreEntity>()
.eq(ZiniaoMemoryStoreEntity::getCacheType, normalizedType)
.orderByAsc(ZiniaoMemoryStoreEntity::getCacheKey)
.last("LIMIT " + safeLimit));
if (entities.isEmpty()) {
return 0;
}
int deleted = 0;
for (ZiniaoMemoryStoreEntity entity : entities) {
deleted += ziniaoMemoryStoreMapper.deleteById(entity.getId());
}
return deleted;
}
@Transactional
public int deleteExpired(int limit) {
int safeLimit = Math.max(limit, 1);
List<ZiniaoMemoryStoreEntity> expired = ziniaoMemoryStoreMapper.selectList(new LambdaQueryWrapper<ZiniaoMemoryStoreEntity>()
.lt(ZiniaoMemoryStoreEntity::getExpiresAt, LocalDateTime.now())
.orderByAsc(ZiniaoMemoryStoreEntity::getExpiresAt)
.last("LIMIT " + safeLimit));
if (expired.isEmpty()) {
return 0;
}
int deleted = 0;
for (ZiniaoMemoryStoreEntity entity : expired) {
deleted += ziniaoMemoryStoreMapper.deleteById(entity.getId());
}
return deleted;
}
private ZiniaoMemoryStoreEntity findOne(String cacheType, String cacheKey) {
String normalizedType = normalizeRequired(cacheType, "cacheType 不能为空");
String normalizedKey = normalizeRequired(cacheKey, "cacheKey 不能为空");
return ziniaoMemoryStoreMapper.selectOne(new LambdaQueryWrapper<ZiniaoMemoryStoreEntity>()
.eq(ZiniaoMemoryStoreEntity::getCacheType, normalizedType)
.eq(ZiniaoMemoryStoreEntity::getCacheKey, normalizedKey)
.last("LIMIT 1"));
}
private <T> T deserialize(String payloadJson, Class<T> valueType) {
try {
return objectMapper.readValue(payloadJson, valueType);
} catch (Exception ex) {
throw new BusinessException("读取紫鸟记忆存储失败");
}
}
private boolean isExpired(ZiniaoMemoryStoreEntity entity) {
return entity.getExpiresAt() == null || !entity.getExpiresAt().isAfter(LocalDateTime.now());
}
private String normalizeRequired(String value, String message) {
String normalized = Objects.toString(value, "").trim();
if (normalized.isEmpty()) {
throw new BusinessException(message);
}
return normalized;
}
}
@@ -5,6 +5,7 @@ import lombok.Data;
@Data @Data
public class ZiniaoSessionCacheDto { public class ZiniaoSessionCacheDto {
private String sessionId; private String sessionId;
private String apiKey;
private String accessToken; private String accessToken;
private String refreshToken; private String refreshToken;
private String tokenType; private String tokenType;
@@ -0,0 +1,24 @@
package com.nanri.aiimage.modules.ziniao.model.cache;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class ZiniaoShopIndexEntryDto {
private String normalizedShopName;
private String shopId;
private String shopName;
private String platform;
private Long matchedUserId;
private Long companyId;
private String apiKeyHash;
private String status;
private String message;
private Integer candidateCount;
private List<String> sampleShopIds = new ArrayList<>();
private List<Long> sampleUserIds = new ArrayList<>();
private Long lastSeenAt;
private Long lastRefreshedAt;
}
@@ -0,0 +1,18 @@
package com.nanri.aiimage.modules.ziniao.model.cache;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class ZiniaoShopIndexRefreshCursorDto {
private String scopeKey;
private String status;
private String message;
private Long lastStartedAt;
private Long lastFinishedAt;
private Long lastSuccessAt;
private Integer invalidUserCount;
private List<Long> sampleInvalidUserIds = new ArrayList<>();
}
@@ -0,0 +1,36 @@
package com.nanri.aiimage.modules.ziniao.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "紫鸟店铺匹配结果")
public class ZiniaoShopMatchResultVo {
@Schema(description = "是否匹配成功")
private boolean matched;
@Schema(description = "店铺ID")
private String shopId;
@Schema(description = "店铺名称")
private String shopName;
@Schema(description = "平台")
private String platform;
@Schema(description = "匹配到的员工 userId")
private Long matchedUserId;
@Schema(description = "打开店铺链接")
private String openStoreUrl;
@Schema(description = "匹配状态: MATCHED / PENDING / CONFLICT")
private String matchStatus;
@Schema(description = "匹配说明")
private String matchMessage;
}
@@ -0,0 +1,43 @@
package com.nanri.aiimage.modules.ziniao.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ZiniaoApiKeyProvider {
private final ShopKeyMapper shopKeyMapper;
public List<String> listApiKeys() {
return shopKeyMapper.selectList(new LambdaQueryWrapper<ShopKeyEntity>()
.orderByDesc(ShopKeyEntity::getId))
.stream()
.map(ShopKeyEntity::getZiniaoToken)
.filter(token -> token != null && !token.isBlank())
.map(String::trim)
.map(token -> token.regionMatches(true, 0, "Bearer ", 0, 7) ? token.substring(7).trim() : token)
.filter(token -> !token.isBlank())
.distinct()
.toList();
}
public String getRequiredApiKey() {
List<String> keys = listApiKeys();
if (keys.isEmpty()) {
throw new BusinessException("紫鸟 apiKey 未配置,请先在店铺密钥管理中维护可用令牌");
}
return keys.get(0);
}
public boolean hasApiKey() {
Long total = shopKeyMapper.selectCount(new LambdaQueryWrapper<ShopKeyEntity>());
return total != null && total > 0;
}
}
@@ -3,8 +3,10 @@ package com.nanri.aiimage.modules.ziniao.service;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.ZiniaoProperties; import com.nanri.aiimage.config.ZiniaoProperties;
import com.nanri.aiimage.modules.ziniao.client.ZiniaoClient; import com.nanri.aiimage.modules.ziniao.client.ZiniaoClient;
import com.nanri.aiimage.modules.ziniao.memory.service.ZiniaoMemoryStoreService;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoSessionCacheDto; import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoSessionCacheDto;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopCacheDto; import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopCacheDto;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoApiKeyProvider;
import com.nanri.aiimage.modules.ziniao.model.dto.ZiniaoOpenShopRequest; import com.nanri.aiimage.modules.ziniao.model.dto.ZiniaoOpenShopRequest;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoOpenShopVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoOpenShopVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoSessionVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoSessionVo;
@@ -13,10 +15,12 @@ import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopListVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffListVo; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffListVo;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
@@ -24,11 +28,176 @@ import java.util.UUID;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class ZiniaoAuthService { public class ZiniaoAuthService {
private static final String CACHE_TYPE_COMPANY_ID = "COMPANY_ID";
private static final String CACHE_TYPE_STAFF_LIST = "STAFF_LIST";
private static final String CACHE_TYPE_USER_STORES = "USER_STORES";
private static final String CACHE_TYPE_SHOP_MATCH = "SHOP_MATCH";
private static final Duration COMPANY_ID_CACHE_TTL = Duration.ofHours(12);
private static final Duration STAFF_LIST_CACHE_TTL = Duration.ofMinutes(30);
private static final Duration USER_STORES_CACHE_TTL = Duration.ofMinutes(30);
private static final Duration SHOP_MATCH_CACHE_TTL = Duration.ofMinutes(30);
public StoreMatchResult matchStoreByNameAcrossStaff(String targetShopName, Long preferUserId) {
ensureEnabled();
String normalizedTarget = normalizeShopName(targetShopName);
if (normalizedTarget.isBlank()) {
return new StoreMatchResult(false, null, null, null, null, null);
}
List<String> apiKeys = getScanApiKeys();
long startedAt = System.currentTimeMillis();
int scannedKeys = 0;
for (String apiKey : apiKeys) {
if (isScanLimitExceeded(startedAt, scannedKeys)) {
throw new BusinessException("紫鸟 key 轮询超出扫描限制,请缩小范围或提高扫描上限");
}
scannedKeys++;
Long companyId;
try {
companyId = resolveCompanyId(apiKey);
} catch (BusinessException ex) {
// key 无效/不可用时继续尝试下一个 key
if (isInvalidApiKeyError(ex)) {
log.info("[ziniao-match] skip invalid apiKey while resolving companyId, keyHash={}", shortKeyHash(apiKey));
continue;
}
throw ex;
}
StoreMatchResult cachedMatch = getCachedShopMatch(apiKey, companyId, normalizedTarget);
if (cachedMatch != null) {
log.info("[ziniao-match] hit shop-match cache, keyHash={}, companyId={}, shopName={}, shopId={}, userId={}",
shortKeyHash(apiKey), companyId, normalizedTarget, cachedMatch.shopId(), cachedMatch.matchedUserId());
String openStoreUrl = buildOpenStoreUrl(cachedMatch.shopId(), cachedMatch.matchedUserId(),
ziniaoClient.getUserLoginToken(apiKey, companyId, cachedMatch.matchedUserId()));
return new StoreMatchResult(true, cachedMatch.shopId(), cachedMatch.shopName(), cachedMatch.platform(), cachedMatch.matchedUserId(), openStoreUrl);
}
List<ZiniaoStaffItemVo> staff = getOrLoadStaff(apiKey, companyId);
List<Long> userIds = buildUserIds(staff, preferUserId);
for (Long staffUserId : userIds) {
if (staffUserId == null || staffUserId <= 0) {
continue;
}
List<ZiniaoShopCacheDto> stores;
try {
stores = getOrLoadUserStores(apiKey, companyId, staffUserId);
} catch (BusinessException ex) {
if (isSkippableUserStoresError(ex)) {
continue;
}
throw ex;
}
for (ZiniaoShopCacheDto store : stores) {
String storeName = normalizeShopName(store == null ? null : store.getShopName());
if (!storeName.isBlank() && storeName.equals(normalizedTarget)) {
log.info("[ziniao-match] matched via upstream scan, keyHash={}, companyId={}, shopName={}, shopId={}, userId={}",
shortKeyHash(apiKey), companyId, normalizedTarget, store.getShopId(), staffUserId);
cacheShopMatch(apiKey, companyId, normalizedTarget,
new StoreMatchResult(true, store.getShopId(), store.getShopName(), store.getPlatform(), staffUserId, null),
SHOP_MATCH_CACHE_TTL);
String openStoreUrl = buildOpenStoreUrl(store.getShopId(), staffUserId,
ziniaoClient.getUserLoginToken(apiKey, companyId, staffUserId));
return new StoreMatchResult(true, store.getShopId(), store.getShopName(), store.getPlatform(), staffUserId, openStoreUrl);
}
}
}
}
return new StoreMatchResult(false, null, null, null, null, null);
}
public String buildOpenStoreUrlByScope(String apiKey, Long companyId, Long userId, String shopId) {
ensureEnabled();
if (apiKey == null || apiKey.isBlank()) {
throw new BusinessException("紫鸟 apiKey 未配置");
}
if (companyId == null || companyId <= 0) {
throw new BusinessException("紫鸟 companyId 不合法");
}
if (userId == null || userId <= 0) {
throw new BusinessException("紫鸟 userId 不合法");
}
if (shopId == null || shopId.isBlank()) {
throw new BusinessException("店铺不存在");
}
String loginToken = ziniaoClient.getUserLoginToken(apiKey, companyId, userId);
return buildOpenStoreUrl(shopId, userId, loginToken);
}
public Long resolveCompanyIdForIndex(String apiKey) {
return resolveCompanyId(apiKey);
}
public List<ZiniaoStaffItemVo> getOrLoadStaffForIndex(String apiKey, Long companyId) {
return getOrLoadStaff(apiKey, companyId);
}
public List<ZiniaoShopCacheDto> getOrLoadUserStoresForIndex(String apiKey, Long companyId, Long userId) {
return getOrLoadUserStores(apiKey, companyId, userId);
}
public boolean isInvalidUserStoresError(BusinessException ex) {
String message = ex == null ? null : ex.getMessage();
if (message == null || message.isBlank()) {
return false;
}
return message.contains("code=40004")
|| message.contains("userId存在无效的参数值");
}
public void evictInvalidUserForIndex(String apiKey, Long companyId, Long userId) {
if (apiKey == null || apiKey.isBlank() || companyId == null || companyId <= 0 || userId == null || userId <= 0) {
return;
}
String staffCacheKey = buildApiKeyHash(apiKey) + ":" + companyId;
ziniaoMemoryStoreService.getList(CACHE_TYPE_STAFF_LIST, staffCacheKey, ZiniaoStaffItemVo.class)
.ifPresent(staff -> {
List<ZiniaoStaffItemVo> filtered = staff.stream()
.filter(item -> item != null && !userId.equals(item.getUserId()))
.toList();
if (filtered.isEmpty()) {
ziniaoMemoryStoreService.delete(CACHE_TYPE_STAFF_LIST, staffCacheKey);
} else {
ziniaoMemoryStoreService.put(CACHE_TYPE_STAFF_LIST, staffCacheKey, filtered, STAFF_LIST_CACHE_TTL);
}
});
ziniaoMemoryStoreService.delete(CACHE_TYPE_USER_STORES, buildApiKeyHash(apiKey) + ":" + companyId + ":" + userId);
}
private boolean isSkippableUserStoresError(BusinessException ex) {
String message = ex == null ? null : ex.getMessage();
if (message == null || message.isBlank()) {
return false;
}
return message.contains("code=40004")
|| message.contains("userId存在无效的参数值")
|| message.contains("无权限")
|| message.contains("没有权限");
}
private String normalizeShopName(String value) {
if (value == null) {
return "";
}
return value.replace("\u3000", " ")
.trim();
}
public record StoreMatchResult(boolean matched, String shopId, String shopName, String platform, Long matchedUserId,
String openStoreUrl) {
}
private final ZiniaoProperties ziniaoProperties; private final ZiniaoProperties ziniaoProperties;
private final ZiniaoClient ziniaoClient; private final ZiniaoClient ziniaoClient;
private final ZiniaoSessionCacheService ziniaoSessionCacheService; private final ZiniaoSessionCacheService ziniaoSessionCacheService;
private final ZiniaoMemoryStoreService ziniaoMemoryStoreService;
private final ZiniaoApiKeyProvider ziniaoApiKeyProvider;
public ZiniaoSessionVo getSession(String sessionId, Long userId) { public ZiniaoSessionVo getSession(String sessionId, Long userId) {
ensureEnabled(); ensureEnabled();
@@ -36,13 +205,13 @@ public class ZiniaoAuthService {
ZiniaoSessionVo vo = new ZiniaoSessionVo(); ZiniaoSessionVo vo = new ZiniaoSessionVo();
vo.setSessionId(session.getSessionId()); vo.setSessionId(session.getSessionId());
vo.setEnabled(ziniaoProperties.isEnabled()); vo.setEnabled(ziniaoProperties.isEnabled());
vo.setAuthenticated(session.getAccessToken() != null && !session.getAccessToken().isBlank()); vo.setAuthenticated(Boolean.TRUE);
vo.setCompanyId(session.getCompanyId()); vo.setCompanyId(session.getCompanyId());
vo.setCurrentUserId(session.getCurrentUserId()); vo.setCurrentUserId(session.getCurrentUserId());
vo.setZiniaoUserId(session.getZiniaoUserId()); vo.setZiniaoUserId(session.getZiniaoUserId());
vo.setNickname(session.getNickname()); vo.setNickname(session.getNickname());
vo.setAppToken(session.getAccessToken()); vo.setAppToken(null);
vo.setTokenType(session.getTokenType()); vo.setTokenType(null);
vo.setExpireAt(session.getExpireAt()); vo.setExpireAt(session.getExpireAt());
vo.setShopCount(ziniaoSessionCacheService.getShops(session.getSessionId()).size()); vo.setShopCount(ziniaoSessionCacheService.getShops(session.getSessionId()).size());
vo.setCurrentShopId(session.getDefaultShopId()); vo.setCurrentShopId(session.getDefaultShopId());
@@ -53,16 +222,18 @@ public class ZiniaoAuthService {
public ZiniaoStaffListVo listStaff() { public ZiniaoStaffListVo listStaff() {
ensureEnabled(); ensureEnabled();
ZiniaoStaffListVo vo = new ZiniaoStaffListVo(); ZiniaoStaffListVo vo = new ZiniaoStaffListVo();
Long companyId = resolveCompanyIdForStaff(); String apiKey = resolveAvailableApiKey();
vo.getItems().addAll(ziniaoClient.listStaff(companyId)); Long companyId = resolveCompanyIdForStaff(apiKey);
vo.getItems().addAll(ziniaoClient.listStaff(apiKey, companyId));
return vo; return vo;
} }
public ZiniaoShopListVo listShops(String sessionId, Long userId) { public ZiniaoShopListVo listShops(String sessionId, Long userId) {
ZiniaoSessionCacheDto session = requireOrInitSession(sessionId, userId); ZiniaoSessionCacheDto session = requireOrInitSession(sessionId, userId);
Long currentUserId = requireUserId(session.getCurrentUserId()); Long currentUserId = requireUserId(session.getCurrentUserId());
String userToken = ziniaoClient.getUserLoginToken(resolveCompanyId(), currentUserId); String apiKey = resolveSessionApiKey(session);
List<ZiniaoShopCacheDto> shops = ziniaoClient.listUserStores(resolveCompanyId(), currentUserId, userToken); Long companyId = resolveCompanyId(apiKey);
List<ZiniaoShopCacheDto> shops = ziniaoClient.listUserStores(apiKey, companyId, currentUserId);
ziniaoSessionCacheService.saveShops(session.getSessionId(), shops); ziniaoSessionCacheService.saveShops(session.getSessionId(), shops);
if (!shops.isEmpty() && (session.getDefaultShopId() == null || session.getDefaultShopId().isBlank())) { if (!shops.isEmpty() && (session.getDefaultShopId() == null || session.getDefaultShopId().isBlank())) {
session.setDefaultShopId(shops.get(0).getShopId()); session.setDefaultShopId(shops.get(0).getShopId());
@@ -83,10 +254,12 @@ public class ZiniaoAuthService {
public ZiniaoOpenShopVo openShop(ZiniaoOpenShopRequest request) { public ZiniaoOpenShopVo openShop(ZiniaoOpenShopRequest request) {
ZiniaoSessionCacheDto session = requireOrInitSession(request.getSessionId(), request.getUserId()); ZiniaoSessionCacheDto session = requireOrInitSession(request.getSessionId(), request.getUserId());
Long currentUserId = requireUserId(request.getUserId() != null ? request.getUserId() : session.getCurrentUserId()); Long currentUserId = requireUserId(request.getUserId() != null ? request.getUserId() : session.getCurrentUserId());
String userToken = ziniaoClient.getUserLoginToken(resolveCompanyId(), currentUserId); String apiKey = resolveSessionApiKey(session);
Long companyId = resolveCompanyId(apiKey);
String userToken = ziniaoClient.getUserLoginToken(apiKey, companyId, currentUserId);
List<ZiniaoShopCacheDto> shops = ziniaoSessionCacheService.getShops(session.getSessionId()); List<ZiniaoShopCacheDto> shops = ziniaoSessionCacheService.getShops(session.getSessionId());
if (shops.isEmpty()) { if (shops.isEmpty()) {
shops = ziniaoClient.listUserStores(resolveCompanyId(), currentUserId, userToken); shops = ziniaoClient.listUserStores(apiKey, companyId, currentUserId);
ziniaoSessionCacheService.saveShops(session.getSessionId(), shops); ziniaoSessionCacheService.saveShops(session.getSessionId(), shops);
} }
ZiniaoShopCacheDto targetShop = shops.stream() ZiniaoShopCacheDto targetShop = shops.stream()
@@ -110,8 +283,8 @@ public class ZiniaoAuthService {
public List<ZiniaoShopCacheDto> listShopsForConfiguredUser() { public List<ZiniaoShopCacheDto> listShopsForConfiguredUser() {
ensureEnabled(); ensureEnabled();
Long userId = parseConfiguredOpenStoreUserId(); Long userId = parseConfiguredOpenStoreUserId();
String userToken = ziniaoClient.getUserLoginToken(resolveCompanyId(), userId); String apiKey = resolveAvailableApiKey();
return ziniaoClient.listUserStores(resolveCompanyId(), userId, userToken); return ziniaoClient.listUserStores(apiKey, resolveCompanyId(apiKey), userId);
} }
public String buildOpenStoreUrlForShop(ZiniaoShopCacheDto shop) { public String buildOpenStoreUrlForShop(ZiniaoShopCacheDto shop) {
@@ -120,7 +293,8 @@ public class ZiniaoAuthService {
throw new BusinessException("店铺不存在"); throw new BusinessException("店铺不存在");
} }
Long userId = parseConfiguredOpenStoreUserId(); Long userId = parseConfiguredOpenStoreUserId();
String loginToken = ziniaoClient.getUserLoginToken(resolveCompanyId(), userId); String apiKey = resolveAvailableApiKey();
String loginToken = ziniaoClient.getUserLoginToken(apiKey, resolveCompanyId(apiKey), userId);
return buildOpenStoreUrl(shop.getShopId(), userId, loginToken); return buildOpenStoreUrl(shop.getShopId(), userId, loginToken);
} }
@@ -128,11 +302,10 @@ public class ZiniaoAuthService {
String sessionId = "ziniao_" + UUID.randomUUID().toString().replace("-", ""); String sessionId = "ziniao_" + UUID.randomUUID().toString().replace("-", "");
ZiniaoSessionCacheDto session = new ZiniaoSessionCacheDto(); ZiniaoSessionCacheDto session = new ZiniaoSessionCacheDto();
session.setSessionId(sessionId); session.setSessionId(sessionId);
String appToken = ziniaoClient.getAppToken();
session.setAccessToken(maskToken(appToken));
session.setTokenType("Bearer");
session.setExpireAt(Instant.now().plusSeconds(ziniaoProperties.getSessionTtlHours() * 3600).toEpochMilli()); session.setExpireAt(Instant.now().plusSeconds(ziniaoProperties.getSessionTtlHours() * 3600).toEpochMilli());
session.setCompanyId(resolveCompanyId()); String apiKey = resolveAvailableApiKey();
session.setApiKey(apiKey);
session.setCompanyId(resolveCompanyId(apiKey));
session.setCurrentUserId(userId); session.setCurrentUserId(userId);
session.setZiniaoUserId(String.valueOf(userId == null ? 0L : userId)); session.setZiniaoUserId(String.valueOf(userId == null ? 0L : userId));
session.setNickname("API Key模式"); session.setNickname("API Key模式");
@@ -151,8 +324,12 @@ public class ZiniaoAuthService {
if (userId != null && userId > 0) { if (userId != null && userId > 0) {
session.setCurrentUserId(userId); session.setCurrentUserId(userId);
session.setZiniaoUserId(String.valueOf(userId)); session.setZiniaoUserId(String.valueOf(userId));
ziniaoSessionCacheService.saveSession(session);
} }
// 旧 session 可能没有保存 apiKey,补齐后续请求所需
if (session.getApiKey() == null || session.getApiKey().isBlank()) {
session.setApiKey(resolveAvailableApiKey());
}
ziniaoSessionCacheService.saveSession(session);
return session; return session;
} }
@@ -184,20 +361,22 @@ public class ZiniaoAuthService {
builder.queryParam("forceDownloadPath", encodedPath); builder.queryParam("forceDownloadPath", encodedPath);
} }
if (ziniaoProperties.getOpenStoreExtraArgs() != null && !ziniaoProperties.getOpenStoreExtraArgs().isBlank()) { if (ziniaoProperties.getOpenStoreExtraArgs() != null && !ziniaoProperties.getOpenStoreExtraArgs().isBlank()) {
builder.queryParam("extraArgs", ziniaoProperties.getOpenStoreExtraArgs()); builder.queryParam("options_argument", ziniaoProperties.getOpenStoreExtraArgs());
} }
return builder.build(true).toUriString(); return builder.build().encode().toUriString();
} }
private void ensureEnabled() { private void ensureEnabled() {
if (!ziniaoProperties.isEnabled()) { if (!ziniaoProperties.isEnabled()) {
throw new BusinessException("紫鸟集成未启用,请先配置环境变量"); throw new BusinessException("紫鸟集成未启用,请先配置环境变量");
} }
requireText(ziniaoProperties.getApiKey(), "紫鸟 apiKey 未配置"); if (!ziniaoApiKeyProvider.hasApiKey()) {
throw new BusinessException("紫鸟 apiKey 未配置,请先在店铺密钥管理中维护可用令牌");
}
} }
private Long resolveCompanyIdForStaff() { private Long resolveCompanyIdForStaff(String apiKey) {
return resolveCompanyId(); return resolveCompanyId(apiKey);
} }
private Long requireUserId(Long userId) { private Long requireUserId(Long userId) {
@@ -207,15 +386,166 @@ public class ZiniaoAuthService {
return userId; return userId;
} }
private Long resolveCompanyId() { private Long resolveCompanyId(String apiKey) {
if (ziniaoProperties.getCompanyId() != null && ziniaoProperties.getCompanyId() > 0) { if (ziniaoProperties.getCompanyId() != null && ziniaoProperties.getCompanyId() > 0) {
return ziniaoProperties.getCompanyId(); return ziniaoProperties.getCompanyId();
} }
return ziniaoClient.getCompanyIdByApiKey();
String normalizedApiKey = requireText(apiKey, "紫鸟 apiKey 未配置");
String cacheKey = buildApiKeyHash(normalizedApiKey);
Long cached = ziniaoMemoryStoreService.get(CACHE_TYPE_COMPANY_ID, cacheKey, Long.class).orElse(null);
if (cached != null && cached > 0) {
log.info("[ziniao-company] hit cache, keyHash={}, companyId={}", shortKeyHash(apiKey), cached);
return cached;
}
log.info("[ziniao-company] cache miss, requesting upstream, keyHash={}", shortKeyHash(apiKey));
Long companyId = ziniaoClient.getCompanyIdByApiKey(normalizedApiKey);
ziniaoMemoryStoreService.put(CACHE_TYPE_COMPANY_ID, cacheKey, companyId, COMPANY_ID_CACHE_TTL);
log.info("[ziniao-company] cached upstream result, keyHash={}, companyId={}", shortKeyHash(apiKey), companyId);
return companyId;
} }
private Long requireCompanyId() {
return resolveCompanyId(); private List<ZiniaoStaffItemVo> getOrLoadStaff(String apiKey, Long companyId) {
String cacheKey = buildApiKeyHash(apiKey) + ":" + companyId;
List<ZiniaoStaffItemVo> cached = ziniaoMemoryStoreService.getList(CACHE_TYPE_STAFF_LIST, cacheKey, ZiniaoStaffItemVo.class)
.orElse(null);
if (cached != null) {
log.info("[ziniao-staff] hit cache, keyHash={}, companyId={}, size={}", shortKeyHash(apiKey), companyId, cached.size());
return cached;
}
log.info("[ziniao-staff] cache miss, requesting upstream, keyHash={}, companyId={}", shortKeyHash(apiKey), companyId);
List<ZiniaoStaffItemVo> staff = ziniaoClient.listStaff(apiKey, companyId);
ziniaoMemoryStoreService.put(CACHE_TYPE_STAFF_LIST, cacheKey, staff, STAFF_LIST_CACHE_TTL);
log.info("[ziniao-staff] cached upstream result, keyHash={}, companyId={}, size={}", shortKeyHash(apiKey), companyId, staff.size());
return staff;
}
private List<ZiniaoShopCacheDto> getOrLoadUserStores(String apiKey, Long companyId, Long userId) {
String cacheKey = buildApiKeyHash(apiKey) + ":" + companyId + ":" + userId;
List<ZiniaoShopCacheDto> cached = ziniaoMemoryStoreService.getList(CACHE_TYPE_USER_STORES, cacheKey, ZiniaoShopCacheDto.class)
.orElse(null);
if (cached != null) {
log.info("[ziniao-stores] hit cache, keyHash={}, companyId={}, userId={}, size={}", shortKeyHash(apiKey), companyId, userId, cached.size());
return cached;
}
log.info("[ziniao-stores] cache miss, requesting upstream, keyHash={}, companyId={}, userId={}", shortKeyHash(apiKey), companyId, userId);
List<ZiniaoShopCacheDto> stores = ziniaoClient.listUserStores(apiKey, companyId, userId);
ziniaoMemoryStoreService.put(CACHE_TYPE_USER_STORES, cacheKey, stores, USER_STORES_CACHE_TTL);
log.info("[ziniao-stores] cached upstream result, keyHash={}, companyId={}, userId={}, size={}", shortKeyHash(apiKey), companyId, userId, stores.size());
return stores;
}
private StoreMatchResult getCachedShopMatch(String apiKey, Long companyId, String normalizedShopName) {
StoreMatchResult cached = ziniaoMemoryStoreService.get(CACHE_TYPE_SHOP_MATCH, buildShopMatchCacheKey(apiKey, companyId, normalizedShopName), StoreMatchResult.class)
.orElse(null);
if (cached == null || !cached.matched() || cached.shopId() == null || cached.matchedUserId() == null) {
return null;
}
return cached;
}
private void cacheShopMatch(String apiKey, Long companyId, String normalizedShopName, StoreMatchResult result, Duration ttl) {
ziniaoMemoryStoreService.put(CACHE_TYPE_SHOP_MATCH, buildShopMatchCacheKey(apiKey, companyId, normalizedShopName), result, ttl);
}
private String buildShopMatchCacheKey(String apiKey, Long companyId, String normalizedShopName) {
return buildApiKeyHash(apiKey) + ":" + companyId + ":" + normalizedShopName;
}
private String buildApiKeyHash(String apiKey) {
try {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(apiKey.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (Exception ex) {
throw new BusinessException("生成紫鸟 apiKey 缓存键失败");
}
}
private String shortKeyHash(String apiKey) {
String hash = buildApiKeyHash(apiKey);
return hash.length() <= 12 ? hash : hash.substring(0, 12);
}
private List<Long> buildUserIds(List<ZiniaoStaffItemVo> staff, Long preferUserId) {
List<Long> userIds = new java.util.ArrayList<>();
if (preferUserId != null && preferUserId > 0) {
userIds.add(preferUserId);
}
for (ZiniaoStaffItemVo item : staff) {
if (item != null && item.getUserId() != null && item.getUserId() > 0 && (userIds.isEmpty() || !userIds.contains(item.getUserId()))) {
userIds.add(item.getUserId());
}
}
return userIds;
}
private List<String> getScanApiKeys() {
List<String> keys = ziniaoApiKeyProvider.listApiKeys();
if (keys.isEmpty()) {
throw new BusinessException("紫鸟 apiKey 未配置,请先在店铺密钥管理中维护可用令牌");
}
Integer maxKeys = ziniaoProperties.getKeyScanMaxKeys();
if (maxKeys == null || maxKeys <= 0 || keys.size() <= maxKeys) {
return keys;
}
return keys.subList(0, maxKeys);
}
private String resolveAvailableApiKey() {
BusinessException lastError = null;
List<String> apiKeys = getScanApiKeys();
for (String apiKey : apiKeys) {
try {
resolveCompanyId(apiKey);
return apiKey;
} catch (BusinessException ex) {
if (isInvalidApiKeyError(ex)) {
lastError = ex;
continue;
}
throw ex;
}
}
if (lastError != null) {
throw lastError;
}
throw new BusinessException("未找到可用的紫鸟 apiKey");
}
private String resolveSessionApiKey(ZiniaoSessionCacheDto session) {
if (session != null && session.getApiKey() != null && !session.getApiKey().isBlank()) {
return session.getApiKey().trim();
}
return resolveAvailableApiKey();
}
private boolean isInvalidApiKeyError(BusinessException ex) {
String message = ex == null ? null : ex.getMessage();
if (message == null || message.isBlank()) {
return false;
}
if (message.contains("白名单") || message.contains("IP") || message.contains("whitelist")) {
return false;
}
return message.contains("isv.invalid-api-key")
|| message.contains("无效的apiKey参数")
|| message.contains("非法的参数");
}
private boolean isScanLimitExceeded(long startedAt, int scannedKeys) {
Integer maxKeys = ziniaoProperties.getKeyScanMaxKeys();
if (maxKeys != null && maxKeys > 0 && scannedKeys >= maxKeys) {
return true;
}
Integer maxSeconds = ziniaoProperties.getKeyScanMaxSeconds();
return maxSeconds != null && maxSeconds > 0
&& System.currentTimeMillis() - startedAt >= maxSeconds * 1000L;
} }
private Long parseConfiguredOpenStoreUserId() { private Long parseConfiguredOpenStoreUserId() {
@@ -17,27 +17,10 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class ZiniaoSessionCacheService { public class ZiniaoSessionCacheService {
private static final String APP_TOKEN_KEY = "ziniao:app-token";
private final StringRedisTemplate stringRedisTemplate; private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final ZiniaoProperties ziniaoProperties; private final ZiniaoProperties ziniaoProperties;
public void saveAppToken(String appToken) {
if (appToken == null || appToken.isBlank()) {
return;
}
stringRedisTemplate.opsForValue().set(APP_TOKEN_KEY, appToken.trim(), Duration.ofHours(ziniaoProperties.getSessionTtlHours()));
}
public String getAppToken() {
String value = stringRedisTemplate.opsForValue().get(APP_TOKEN_KEY);
if (value == null || value.isBlank()) {
return null;
}
return value.trim();
}
public void saveSession(ZiniaoSessionCacheDto session) { public void saveSession(ZiniaoSessionCacheDto session) {
try { try {
stringRedisTemplate.opsForValue().set(buildSessionKey(session.getSessionId()), objectMapper.writeValueAsString(session), Duration.ofHours(ziniaoProperties.getSessionTtlHours())); stringRedisTemplate.opsForValue().set(buildSessionKey(session.getSessionId()), objectMapper.writeValueAsString(session), Duration.ofHours(ziniaoProperties.getSessionTtlHours()));
@@ -0,0 +1,23 @@
package com.nanri.aiimage.modules.ziniao.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
public class ZiniaoShopIndexRefreshService {
private final ZiniaoShopIndexService ziniaoShopIndexService;
@Scheduled(cron = "${aiimage.ziniao.shop-index-refresh-cron:0 */10 * * * *}")
public void refreshShopIndex() {
try {
ziniaoShopIndexService.refreshShopIndex();
} catch (Exception ex) {
log.warn("[ziniao-index] refresh failed: {}", ex.getMessage());
}
}
}
@@ -0,0 +1,414 @@
package com.nanri.aiimage.modules.ziniao.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.ZiniaoProperties;
import com.nanri.aiimage.modules.ziniao.memory.service.ZiniaoMemoryStoreService;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopIndexEntryDto;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopIndexRefreshCursorDto;
import com.nanri.aiimage.modules.ziniao.model.cache.ZiniaoShopCacheDto;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoStaffItemVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@Service
@RequiredArgsConstructor
@Slf4j
public class ZiniaoShopIndexService {
public static final String STATUS_ACTIVE = "ACTIVE";
public static final String STATUS_STALE = "STALE";
public static final String STATUS_CONFLICT = "CONFLICT";
public static final String STATUS_PENDING = "PENDING";
public static final String MATCH_STATUS_MATCHED = "MATCHED";
public static final String MATCH_STATUS_PENDING = "PENDING";
public static final String MATCH_STATUS_CONFLICT = "CONFLICT";
public static final String MATCH_STATUS_STALE = "INDEX_STALE";
private static final String CACHE_TYPE_SHOP_INDEX_ENTRY = "SHOP_INDEX_ENTRY";
private static final String CACHE_TYPE_SHOP_INDEX_SCOPE_SNAPSHOT = "SHOP_INDEX_SCOPE_SNAPSHOT";
private static final String CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR = "SHOP_INDEX_REFRESH_CURSOR";
private static final Duration DEFAULT_ENTRY_TTL = Duration.ofHours(12);
private static final Duration DEFAULT_CURSOR_TTL = Duration.ofHours(24);
private static final int DEFAULT_REFRESH_BATCH_SIZE = 100;
private static final int DEFAULT_LIST_BY_TYPE_LIMIT = 5000;
private final ZiniaoMemoryStoreService ziniaoMemoryStoreService;
private final ZiniaoApiKeyProvider ziniaoApiKeyProvider;
private final ZiniaoAuthService ziniaoAuthService;
private final ZiniaoProperties ziniaoProperties;
public ZiniaoShopIndexRefreshCursorDto getRefreshCursor() {
ZiniaoShopIndexRefreshCursorDto cursor = ziniaoMemoryStoreService
.get(CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR, "global", ZiniaoShopIndexRefreshCursorDto.class)
.orElse(null);
if (cursor == null) {
cursor = new ZiniaoShopIndexRefreshCursorDto();
cursor.setScopeKey("global");
cursor.setStatus("IDLE");
cursor.setMessage("索引刷新任务尚未执行");
}
return cursor;
}
public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName) {
String normalizedShopName = normalizeShopName(targetShopName);
if (normalizedShopName.isBlank()) {
return pendingResult("店铺名为空,无法匹配索引");
}
ZiniaoShopIndexEntryDto entry = ziniaoMemoryStoreService
.get(CACHE_TYPE_SHOP_INDEX_ENTRY, normalizedShopName, ZiniaoShopIndexEntryDto.class)
.orElse(null);
if (entry == null) {
return pendingResult("店铺索引未命中,请等待后台刷新");
}
if (STATUS_CONFLICT.equals(entry.getStatus())) {
return conflictResult(entry.getMessage() == null || entry.getMessage().isBlank()
? "存在多个同名店铺,请人工确认"
: entry.getMessage());
}
if (!STATUS_ACTIVE.equals(entry.getStatus())) {
return staleOrPendingResult(entry.getMessage() == null || entry.getMessage().isBlank()
? "店铺索引暂不可用,请等待后台刷新"
: entry.getMessage(), entry);
}
if (entry.getShopId() == null || entry.getShopId().isBlank() || entry.getMatchedUserId() == null || entry.getMatchedUserId() <= 0) {
return pendingResult("店铺索引信息不完整,请等待后台刷新");
}
String apiKey = findApiKeyByHash(entry.getApiKeyHash());
if (apiKey == null) {
return pendingResult("店铺索引所依赖的紫鸟 key 已失效,请等待后台刷新");
}
Long companyId = entry.getCompanyId();
if (companyId == null || companyId <= 0) {
return pendingResult("店铺索引缺少 companyId,请等待后台刷新");
}
String openStoreUrl = ziniaoAuthService.buildOpenStoreUrlByScope(apiKey, companyId, entry.getMatchedUserId(), entry.getShopId());
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(true);
vo.setShopId(entry.getShopId());
vo.setShopName(entry.getShopName());
vo.setPlatform(entry.getPlatform());
vo.setMatchedUserId(entry.getMatchedUserId());
vo.setOpenStoreUrl(openStoreUrl);
vo.setMatchStatus(isFresh(entry) ? MATCH_STATUS_MATCHED : MATCH_STATUS_STALE);
vo.setMatchMessage(isFresh(entry) ? null : "店铺索引已过保鲜期,请等待后台刷新");
return vo;
}
public void refreshShopIndex() {
long now = Instant.now().toEpochMilli();
ZiniaoShopIndexRefreshCursorDto cursor = new ZiniaoShopIndexRefreshCursorDto();
cursor.setScopeKey("global");
cursor.setStatus("RUNNING");
cursor.setLastStartedAt(now);
ziniaoMemoryStoreService.put(CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR, "global", cursor, DEFAULT_CURSOR_TTL);
Map<String, List<ZiniaoShopIndexEntryDto>> grouped = new LinkedHashMap<>();
Set<Long> allInvalidUserIds = new LinkedHashSet<>();
int refreshBatchSize = resolveRefreshBatchSize();
try {
List<String> apiKeys = ziniaoApiKeyProvider.listApiKeys();
if (refreshBatchSize > 0 && apiKeys.size() > refreshBatchSize) {
apiKeys = apiKeys.subList(0, refreshBatchSize);
}
for (String apiKey : apiKeys) {
Long companyId;
try {
companyId = ziniaoAuthService.resolveCompanyIdForIndex(apiKey);
} catch (BusinessException ex) {
log.warn("[ziniao-index] skip apiKey while resolving companyId, msg={}", ex.getMessage());
continue;
}
Set<Long> invalidUserIds = new LinkedHashSet<>();
List<ZiniaoStaffItemVo> staff = ziniaoAuthService.getOrLoadStaffForIndex(apiKey, companyId);
for (Long userId : buildUserIds(staff)) {
if (invalidUserIds.contains(userId)) {
continue;
}
List<ZiniaoShopCacheDto> stores;
try {
stores = ziniaoAuthService.getOrLoadUserStoresForIndex(apiKey, companyId, userId);
} catch (BusinessException ex) {
if (ziniaoAuthService.isInvalidUserStoresError(ex)) {
invalidUserIds.add(userId);
allInvalidUserIds.add(userId);
ziniaoAuthService.evictInvalidUserForIndex(apiKey, companyId, userId);
}
log.warn("[ziniao-index] skip user stores, companyId={}, userId={}, msg={}", companyId, userId, ex.getMessage());
continue;
}
ziniaoMemoryStoreService.put(
CACHE_TYPE_SHOP_INDEX_SCOPE_SNAPSHOT,
buildScopeSnapshotKey(apiKey, companyId, userId),
stores,
resolveEntryTtl()
);
for (ZiniaoShopCacheDto store : stores) {
String normalizedShopName = normalizeShopName(store == null ? null : store.getShopName());
if (normalizedShopName.isBlank()) {
continue;
}
ZiniaoShopIndexEntryDto entry = new ZiniaoShopIndexEntryDto();
entry.setNormalizedShopName(normalizedShopName);
entry.setShopId(store.getShopId());
entry.setShopName(store.getShopName());
entry.setPlatform(store.getPlatform());
entry.setMatchedUserId(userId);
entry.setCompanyId(companyId);
entry.setApiKeyHash(buildApiKeyHash(apiKey));
entry.setStatus(STATUS_ACTIVE);
entry.setLastSeenAt(now);
entry.setLastRefreshedAt(now);
List<ZiniaoShopIndexEntryDto> candidates = grouped.computeIfAbsent(normalizedShopName, ignored -> new ArrayList<>());
if (candidates.stream().noneMatch(existing -> sameCandidate(existing, entry))) {
candidates.add(entry);
}
}
}
if (!invalidUserIds.isEmpty()) {
for (Long invalidUserId : invalidUserIds) {
ziniaoMemoryStoreService.delete(
CACHE_TYPE_SHOP_INDEX_SCOPE_SNAPSHOT,
buildScopeSnapshotKey(apiKey, companyId, invalidUserId)
);
}
}
}
for (Map.Entry<String, List<ZiniaoShopIndexEntryDto>> groupedEntry : grouped.entrySet()) {
String normalizedShopName = groupedEntry.getKey();
List<ZiniaoShopIndexEntryDto> candidates = groupedEntry.getValue();
ZiniaoShopIndexEntryDto entryToStore = candidates.get(0);
if (candidates.size() > 1) {
entryToStore = buildConflictEntry(normalizedShopName, candidates, now);
}
ziniaoMemoryStoreService.put(CACHE_TYPE_SHOP_INDEX_ENTRY, normalizedShopName, entryToStore, resolveEntryTtl());
}
markMissingEntriesAsStale(grouped.keySet(), now);
cursor.setStatus("SUCCESS");
cursor.setMessage(allInvalidUserIds.isEmpty()
? null
: "本轮刷新已跳过无效 userId 数: " + allInvalidUserIds.size());
cursor.setInvalidUserCount(allInvalidUserIds.size());
cursor.setSampleInvalidUserIds(allInvalidUserIds.stream().limit(20).toList());
cursor.setLastFinishedAt(now);
cursor.setLastSuccessAt(now);
ziniaoMemoryStoreService.put(CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR, "global", cursor, DEFAULT_CURSOR_TTL);
} catch (Exception ex) {
cursor.setStatus("FAILED");
cursor.setMessage(ex.getMessage());
cursor.setLastFinishedAt(now);
ziniaoMemoryStoreService.put(CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR, "global", cursor, DEFAULT_CURSOR_TTL);
if (ex instanceof BusinessException businessException) {
throw businessException;
}
throw new BusinessException("刷新紫鸟店铺索引失败");
}
}
public void invalidateIndex() {
ziniaoMemoryStoreService.delete(CACHE_TYPE_SHOP_INDEX_REFRESH_CURSOR, "global");
}
public String normalizeShopName(String value) {
if (value == null) {
return "";
}
return value.replace("\u3000", " ").trim();
}
private ZiniaoShopMatchResultVo pendingResult(String message) {
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(false);
vo.setMatchStatus(MATCH_STATUS_PENDING);
vo.setMatchMessage(message);
return vo;
}
private ZiniaoShopMatchResultVo conflictResult(String message) {
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(false);
vo.setMatchStatus(MATCH_STATUS_CONFLICT);
vo.setMatchMessage(message);
return vo;
}
private ZiniaoShopIndexEntryDto buildConflictEntry(String normalizedShopName, List<ZiniaoShopIndexEntryDto> candidates, long now) {
ZiniaoShopIndexEntryDto representative = candidates == null || candidates.isEmpty() ? null : candidates.get(0);
ZiniaoShopIndexEntryDto entry = new ZiniaoShopIndexEntryDto();
entry.setNormalizedShopName(normalizedShopName);
entry.setStatus(STATUS_CONFLICT);
entry.setShopName(representative == null ? normalizedShopName : representative.getShopName());
entry.setCompanyId(representative == null ? null : representative.getCompanyId());
entry.setApiKeyHash(representative == null ? null : representative.getApiKeyHash());
entry.setCandidateCount(candidates == null ? 0 : candidates.size());
entry.setMessage("存在多个同名店铺,请人工确认(候选数: " + entry.getCandidateCount() + ")");
entry.setLastSeenAt(now);
entry.setLastRefreshedAt(now);
if (candidates != null) {
for (ZiniaoShopIndexEntryDto candidate : candidates) {
if (candidate == null) {
continue;
}
if (candidate.getShopId() != null && !candidate.getShopId().isBlank() && !entry.getSampleShopIds().contains(candidate.getShopId())) {
entry.getSampleShopIds().add(candidate.getShopId());
}
if (candidate.getMatchedUserId() != null && candidate.getMatchedUserId() > 0 && !entry.getSampleUserIds().contains(candidate.getMatchedUserId())) {
entry.getSampleUserIds().add(candidate.getMatchedUserId());
}
}
}
return entry;
}
private ZiniaoShopMatchResultVo staleOrPendingResult(String defaultMessage, ZiniaoShopIndexEntryDto entry) {
if (entry != null && STATUS_STALE.equals(entry.getStatus())) {
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(false);
vo.setMatchStatus(MATCH_STATUS_STALE);
vo.setMatchMessage(defaultMessage);
return vo;
}
return pendingResult(defaultMessage);
}
private void markMissingEntriesAsStale(Set<String> activeNames, long now) {
List<ZiniaoShopIndexEntryDto> existingEntries = ziniaoMemoryStoreService.listByType(
CACHE_TYPE_SHOP_INDEX_ENTRY,
ZiniaoShopIndexEntryDto.class,
DEFAULT_LIST_BY_TYPE_LIMIT
);
if (existingEntries.isEmpty()) {
return;
}
for (ZiniaoShopIndexEntryDto existingEntry : existingEntries) {
if (existingEntry == null || existingEntry.getNormalizedShopName() == null || existingEntry.getNormalizedShopName().isBlank()) {
continue;
}
if (activeNames.contains(existingEntry.getNormalizedShopName())) {
continue;
}
if (STATUS_CONFLICT.equals(existingEntry.getStatus())
&& (existingEntry.getCandidateCount() == null || existingEntry.getCandidateCount() <= 0)
&& (existingEntry.getShopName() == null || existingEntry.getShopName().isBlank())
&& (existingEntry.getApiKeyHash() == null || existingEntry.getApiKeyHash().isBlank())
&& (existingEntry.getCompanyId() == null || existingEntry.getCompanyId() <= 0)) {
ziniaoMemoryStoreService.delete(CACHE_TYPE_SHOP_INDEX_ENTRY, existingEntry.getNormalizedShopName());
continue;
}
existingEntry.setStatus(STATUS_STALE);
existingEntry.setMessage("店铺索引已过期,请等待后台刷新");
existingEntry.setLastRefreshedAt(now);
ziniaoMemoryStoreService.put(
CACHE_TYPE_SHOP_INDEX_ENTRY,
existingEntry.getNormalizedShopName(),
existingEntry,
resolveEntryTtl()
);
}
}
private boolean isFresh(ZiniaoShopIndexEntryDto entry) {
if (entry == null || entry.getLastRefreshedAt() == null || entry.getLastRefreshedAt() <= 0) {
return false;
}
Integer freshMinutes = ziniaoProperties.getShopIndexFreshMinutes();
if (freshMinutes == null || freshMinutes <= 0) {
return true;
}
long freshWindowMillis = Duration.ofMinutes(freshMinutes).toMillis();
return Instant.now().toEpochMilli() - entry.getLastRefreshedAt() <= freshWindowMillis;
}
private Duration resolveEntryTtl() {
Integer ttlHours = ziniaoProperties.getShopIndexEntryTtlHours();
if (ttlHours == null || ttlHours <= 0) {
return DEFAULT_ENTRY_TTL;
}
return Duration.ofHours(ttlHours);
}
private int resolveRefreshBatchSize() {
Integer batchSize = ziniaoProperties.getShopIndexRefreshBatchSize();
if (batchSize == null || batchSize <= 0) {
return DEFAULT_REFRESH_BATCH_SIZE;
}
return batchSize;
}
private List<Long> buildUserIds(List<ZiniaoStaffItemVo> staff) {
List<Long> userIds = new ArrayList<>();
for (ZiniaoStaffItemVo item : staff) {
if (item != null && item.getUserId() != null && item.getUserId() > 0 && !userIds.contains(item.getUserId())) {
userIds.add(item.getUserId());
}
}
return userIds;
}
private boolean sameCandidate(ZiniaoShopIndexEntryDto left, ZiniaoShopIndexEntryDto right) {
if (left == null || right == null) {
return false;
}
if (left.getShopId() != null && right.getShopId() != null) {
return Objects.equals(left.getShopId(), right.getShopId())
&& Objects.equals(left.getMatchedUserId(), right.getMatchedUserId())
&& Objects.equals(left.getCompanyId(), right.getCompanyId())
&& Objects.equals(left.getApiKeyHash(), right.getApiKeyHash());
}
return Objects.equals(left.getShopName(), right.getShopName())
&& Objects.equals(left.getMatchedUserId(), right.getMatchedUserId())
&& Objects.equals(left.getCompanyId(), right.getCompanyId())
&& Objects.equals(left.getApiKeyHash(), right.getApiKeyHash());
}
private String buildScopeSnapshotKey(String apiKey, Long companyId, Long userId) {
return buildApiKeyHash(apiKey) + ":" + companyId + ":" + userId;
}
private String findApiKeyByHash(String apiKeyHash) {
if (apiKeyHash == null || apiKeyHash.isBlank()) {
return null;
}
for (String apiKey : ziniaoApiKeyProvider.listApiKeys()) {
if (apiKeyHash.equals(buildApiKeyHash(apiKey))) {
return apiKey;
}
}
return null;
}
private String buildApiKeyHash(String apiKey) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(apiKey.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (Exception ex) {
throw new BusinessException("生成紫鸟 apiKey 缓存键失败");
}
}
}
@@ -0,0 +1,63 @@
package com.nanri.aiimage.modules.ziniao.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ZiniaoShopSwitchService {
private final ZiniaoAuthService ziniaoAuthService;
private final ZiniaoShopIndexService ziniaoShopIndexService;
public ZiniaoShopMatchResultVo matchStoreByNameAcrossStaff(String targetShopName, Long preferUserId) {
String normalizedShopName = normalizeShopName(targetShopName);
if (normalizedShopName.isBlank()) {
return emptyMatchResult();
}
ZiniaoAuthService.StoreMatchResult result = ziniaoAuthService.matchStoreByNameAcrossStaff(normalizedShopName, preferUserId);
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(result.matched());
vo.setShopId(result.shopId());
vo.setShopName(result.shopName());
vo.setPlatform(result.platform());
vo.setMatchedUserId(result.matchedUserId());
vo.setOpenStoreUrl(result.openStoreUrl());
vo.setMatchStatus(result.matched() ? ZiniaoShopIndexService.MATCH_STATUS_MATCHED : ZiniaoShopIndexService.MATCH_STATUS_PENDING);
return vo;
}
public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName) {
return ziniaoShopIndexService.findIndexedStoreByName(targetShopName);
}
public ZiniaoShopMatchResultVo emptyMatchResult() {
ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
vo.setMatched(false);
vo.setMatchStatus(ZiniaoShopIndexService.MATCH_STATUS_PENDING);
vo.setMatchMessage("店铺名为空,无法匹配索引");
return vo;
}
public String normalizeShopName(String value) {
if (value == null) {
return "";
}
return value.replace("\u3000", " ").trim();
}
public boolean isSkippableMatchError(BusinessException ex) {
String message = ex == null ? null : ex.getMessage();
if (message == null || message.isBlank()) {
return false;
}
return (message.contains("code=40004")
|| message.contains("userId\u5b58\u5728\u65e0\u6548\u7684\u53c2\u6570\u503c")
|| message.contains("\u65e0\u6743\u9650")
|| message.contains("\u6ca1\u6709\u6743\u9650"))
&& !message.contains("\u767d\u540d\u5355");
}
}
@@ -29,7 +29,7 @@ AIIMAGE_ZINIAO_APP_TOKEN_PATH=/auth/get_app_token
AIIMAGE_ZINIAO_STAFF_LIST_PATH=/superbrowser/rest/v1/erp/staff/list AIIMAGE_ZINIAO_STAFF_LIST_PATH=/superbrowser/rest/v1/erp/staff/list
AIIMAGE_ZINIAO_USER_STORES_PATH=/superbrowser/rest/v1/erp/user/stores AIIMAGE_ZINIAO_USER_STORES_PATH=/superbrowser/rest/v1/erp/user/stores
AIIMAGE_ZINIAO_USER_LOGIN_TOKEN_PATH=/superbrowser/rest/v1/token/user-login AIIMAGE_ZINIAO_USER_LOGIN_TOKEN_PATH=/superbrowser/rest/v1/token/user-login
AIIMAGE_ZINIAO_OPEN_STORE_SCHEME=superbrowser://OpenStrore AIIMAGE_ZINIAO_OPEN_STORE_SCHEME=superbrowser://OpenStore
AIIMAGE_ZINIAO_OPEN_STORE_USER_ID= AIIMAGE_ZINIAO_OPEN_STORE_USER_ID=
AIIMAGE_ZINIAO_OPEN_STORE_LAUNCH_URL=https://www.baidu.com AIIMAGE_ZINIAO_OPEN_STORE_LAUNCH_URL=https://www.baidu.com
AIIMAGE_ZINIAO_OPEN_STORE_AUTO_OPEN=true AIIMAGE_ZINIAO_OPEN_STORE_AUTO_OPEN=true
@@ -15,6 +15,11 @@ spring:
url: ${AIIMAGE_DB_URL:jdbc:mysql://127.0.0.1:3306/aiimage?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false} url: ${AIIMAGE_DB_URL:jdbc:mysql://127.0.0.1:3306/aiimage?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false}
username: ${AIIMAGE_DB_USERNAME:root} username: ${AIIMAGE_DB_USERNAME:root}
password: ${AIIMAGE_DB_PASSWORD:change-me} password: ${AIIMAGE_DB_PASSWORD:change-me}
hikari:
maximum-pool-size: ${AIIMAGE_DB_POOL_MAX_SIZE:30}
minimum-idle: ${AIIMAGE_DB_POOL_MIN_IDLE:5}
connection-timeout: ${AIIMAGE_DB_POOL_CONNECTION_TIMEOUT_MS:30000}
leak-detection-threshold: ${AIIMAGE_DB_POOL_LEAK_DETECT_MS:0}
data: data:
redis: redis:
host: ${AIIMAGE_REDIS_HOST:127.0.0.1} host: ${AIIMAGE_REDIS_HOST:127.0.0.1}
@@ -72,6 +77,10 @@ aiimage:
failed-ttl-hours: ${AIIMAGE_BRAND_PROGRESS_FAILED_TTL_HOURS:2} failed-ttl-hours: ${AIIMAGE_BRAND_PROGRESS_FAILED_TTL_HOURS:2}
heartbeat-timeout-minutes: ${AIIMAGE_BRAND_PROGRESS_HEARTBEAT_TIMEOUT_MINUTES:15} heartbeat-timeout-minutes: ${AIIMAGE_BRAND_PROGRESS_HEARTBEAT_TIMEOUT_MINUTES:15}
stale-check-cron: ${AIIMAGE_BRAND_PROGRESS_STALE_CHECK_CRON:0 */2 * * * *} stale-check-cron: ${AIIMAGE_BRAND_PROGRESS_STALE_CHECK_CRON:0 */2 * * * *}
delete-brand-progress:
heartbeat-timeout-minutes: ${AIIMAGE_DELETE_BRAND_HEARTBEAT_TIMEOUT_MINUTES:15}
stale-check-cron: ${AIIMAGE_DELETE_BRAND_STALE_CHECK_CRON:0 */2 * * * *}
finalize-check-cron: ${AIIMAGE_DELETE_BRAND_FINALIZE_CHECK_CRON:30 */2 * * * *}
module-cleanup: module-cleanup:
enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true} enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true}
cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *} cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *}
@@ -99,3 +108,9 @@ aiimage:
shops-cache-minutes: ${AIIMAGE_ZINIAO_SHOPS_CACHE_MINUTES:30} shops-cache-minutes: ${AIIMAGE_ZINIAO_SHOPS_CACHE_MINUTES:30}
connect-timeout-seconds: ${AIIMAGE_ZINIAO_CONNECT_TIMEOUT_SECONDS:5} connect-timeout-seconds: ${AIIMAGE_ZINIAO_CONNECT_TIMEOUT_SECONDS:5}
read-timeout-seconds: ${AIIMAGE_ZINIAO_READ_TIMEOUT_SECONDS:15} read-timeout-seconds: ${AIIMAGE_ZINIAO_READ_TIMEOUT_SECONDS:15}
key-scan-max-keys: ${AIIMAGE_ZINIAO_KEY_SCAN_MAX_KEYS:100}
key-scan-max-seconds: ${AIIMAGE_ZINIAO_KEY_SCAN_MAX_SECONDS:30}
shop-index-refresh-cron: ${AIIMAGE_ZINIAO_SHOP_INDEX_REFRESH_CRON:0 */10 * * * *}
shop-index-fresh-minutes: ${AIIMAGE_ZINIAO_SHOP_INDEX_FRESH_MINUTES:20}
shop-index-entry-ttl-hours: ${AIIMAGE_ZINIAO_SHOP_INDEX_ENTRY_TTL_HOURS:12}
shop-index-refresh-batch-size: ${AIIMAGE_ZINIAO_SHOP_INDEX_REFRESH_BATCH_SIZE:100}
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS biz_shop_key (
id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键',
ziniao_account_name VARCHAR(128) NOT NULL COMMENT '紫鸟账号名称',
ziniao_token VARCHAR(512) NOT NULL COMMENT '紫鸟令牌',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
KEY idx_created_at (created_at)
) COMMENT='店铺密钥管理表';
@@ -0,0 +1,27 @@
SET @drop_shop_key_machine_no_index_sql := (
SELECT CASE
WHEN COUNT(*) > 0 THEN 'ALTER TABLE biz_shop_key DROP INDEX uk_machine_no'
ELSE 'SELECT 1'
END
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_shop_key'
AND INDEX_NAME = 'uk_machine_no'
);
PREPARE stmt FROM @drop_shop_key_machine_no_index_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @drop_shop_key_machine_no_column_sql := (
SELECT CASE
WHEN COUNT(*) > 0 THEN 'ALTER TABLE biz_shop_key DROP COLUMN machine_no'
ELSE 'SELECT 1'
END
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_shop_key'
AND COLUMN_NAME = 'machine_no'
);
PREPARE stmt FROM @drop_shop_key_machine_no_column_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS biz_ziniao_memory_store (
id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键',
cache_type VARCHAR(64) NOT NULL COMMENT '缓存类型',
cache_key VARCHAR(255) NOT NULL COMMENT '缓存key',
payload_json LONGTEXT NOT NULL COMMENT '缓存JSON',
expires_at DATETIME NOT NULL COMMENT '过期时间',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
UNIQUE KEY uk_type_key (cache_type, cache_key),
KEY idx_expires_at (expires_at)
) COMMENT='紫鸟记忆存储(跨会话SQL缓存)';
Binary file not shown.
+107
View File
@@ -617,6 +617,113 @@ def upload_version():
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
# ---------- 店铺密钥管理 ----------
@admin_api.route('/shop-keys')
@admin_required
def list_shop_keys():
page = max(1, int(request.args.get('page', 1)))
page_size = min(100, max(1, int(request.args.get('page_size', 15))))
result, error_response, status = _proxy_backend_java(
'GET',
'/api/admin/shop-keys',
params={'page': page, 'pageSize': page_size},
)
if error_response is not None:
return error_response, status
payload = result.get('data') or {}
items = [
{
'id': item.get('id'),
'ziniao_account_name': item.get('ziniaoAccountName') or '',
'ziniao_token': item.get('ziniaoToken') or '',
'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16],
'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16],
}
for item in (payload.get('items') or [])
]
return jsonify({
'success': True,
'items': items,
'total': payload.get('total') or 0,
'page': payload.get('page') or page,
'page_size': payload.get('pageSize') or page_size,
})
@admin_api.route('/shop-key', methods=['POST'])
@admin_required
def create_shop_key():
data = request.get_json() or {}
payload = {
'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(),
'ziniaoToken': (data.get('ziniao_token') or '').strip(),
}
result, error_response, status = _proxy_backend_java(
'POST',
'/api/admin/shop-keys',
json_data=payload,
)
if error_response is not None:
return error_response, status
item = result.get('data') or {}
return jsonify({
'success': True,
'msg': result.get('message') or '创建成功',
'item': {
'id': item.get('id'),
'ziniao_account_name': item.get('ziniaoAccountName') or '',
'ziniao_token': item.get('ziniaoToken') or '',
'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16],
'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16],
},
})
@admin_api.route('/shop-key/<int:item_id>', methods=['PUT'])
@admin_required
def update_shop_key(item_id):
data = request.get_json() or {}
payload = {
'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(),
'ziniaoToken': (data.get('ziniao_token') or '').strip(),
}
result, error_response, status = _proxy_backend_java(
'PUT',
f'/api/admin/shop-keys/{item_id}',
json_data=payload,
)
if error_response is not None:
return error_response, status
item = result.get('data') or {}
return jsonify({
'success': True,
'msg': result.get('message') or '更新成功',
'item': {
'id': item.get('id'),
'ziniao_account_name': item.get('ziniaoAccountName') or '',
'ziniao_token': item.get('ziniaoToken') or '',
'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16],
'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16],
},
})
@admin_api.route('/shop-key/<int:item_id>', methods=['DELETE'])
@admin_required
def delete_shop_key(item_id):
result, error_response, status = _proxy_backend_java(
'DELETE',
f'/api/admin/shop-keys/{item_id}',
)
if error_response is not None:
return error_response, status
return jsonify({
'success': True,
'msg': result.get('message') or '删除成功',
})
# ---------- 数据去重总数据 ---------- # ---------- 数据去重总数据 ----------
@admin_api.route('/dedupe-total-data') @admin_api.route('/dedupe-total-data')
+196
View File
@@ -112,6 +112,7 @@
<div class="tab active" data-tab="users">用户管理</div> <div class="tab active" data-tab="users">用户管理</div>
<div class="tab" data-tab="columns">栏目权限配置</div> <div class="tab" data-tab="columns">栏目权限配置</div>
<div class="tab" data-tab="dedupe-total-data">数据去重总数据</div> <div class="tab" data-tab="dedupe-total-data">数据去重总数据</div>
<div class="tab" data-tab="shop-keys">店铺密钥管理</div>
<div class="tab" data-tab="history">查看生成记录</div> <div class="tab" data-tab="history">查看生成记录</div>
<div class="tab" data-tab="version">版本管理</div> <div class="tab" data-tab="version">版本管理</div>
</div> </div>
@@ -308,6 +309,42 @@
</div> </div>
</div> </div>
<!-- 店铺密钥管理 -->
<div id="panel-shop-keys" class="tab-panel">
<div class="form-box">
<h3 style="margin-bottom:16px;font-size:15px;">新增店铺密钥</h3>
<div class="form-row">
<div class="form-group" style="min-width:220px;">
<label>紫鸟账号名称</label>
<input type="text" id="shopKeyZiniaoAccountName" placeholder="请输入紫鸟账号名称">
</div>
<div class="form-group" style="min-width:260px;">
<label>紫鸟令牌</label>
<input type="text" id="shopKeyZiniaoToken" placeholder="请输入紫鸟令牌">
</div>
<button class="btn" id="btnCreateShopKey">新增店铺密钥</button>
</div>
<p class="msg" id="msgShopKey"></p>
</div>
<div class="panel-box">
<h3 style="margin-bottom:16px;font-size:15px;">店铺密钥列表</h3>
<table>
<thead>
<tr>
<th>序号</th>
<th>紫鸟账号名称</th>
<th>紫鸟令牌</th>
<th>创建时间</th>
<th>修改时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="shopKeyListBody"></tbody>
</table>
<div class="pagination" id="shopKeyPagination"></div>
</div>
</div>
<!-- 查看生成记录 --> <!-- 查看生成记录 -->
<div id="panel-history" class="tab-panel"> <div id="panel-history" class="tab-panel">
<div class="form-box"> <div class="form-box">
@@ -423,6 +460,27 @@
</div> </div>
</div> </div>
<!-- 编辑店铺密钥弹窗 -->
<div class="modal-mask" id="editShopKeyModal">
<div class="modal">
<h3>编辑店铺密钥</h3>
<input type="hidden" id="editShopKeyId">
<div class="form-group">
<label>紫鸟账号名称</label>
<input type="text" id="editShopKeyZiniaoAccountName" placeholder="紫鸟账号名称">
</div>
<div class="form-group">
<label>紫鸟令牌</label>
<input type="text" id="editShopKeyZiniaoToken" placeholder="紫鸟令牌">
</div>
<p class="msg" id="msgEditShopKey"></p>
<div style="margin-top:16px;display:flex;gap:8px;">
<button class="btn" id="btnSaveShopKey">保存</button>
<button class="btn btn-secondary" id="btnCloseEditShopKey">取消</button>
</div>
</div>
</div>
<script> <script>
(function() { (function() {
// Tab 切换 // Tab 切换
@@ -436,6 +494,7 @@
if (t.dataset.tab === 'users') { loadUsers(1); loadColumnsForPermission(); } if (t.dataset.tab === 'users') { loadUsers(1); loadColumnsForPermission(); }
else if (t.dataset.tab === 'columns') loadColumns(); else if (t.dataset.tab === 'columns') loadColumns();
else if (t.dataset.tab === 'dedupe-total-data') loadDedupeTotalData(1); else if (t.dataset.tab === 'dedupe-total-data') loadDedupeTotalData(1);
else if (t.dataset.tab === 'shop-keys') loadShopKeys(1);
else if (t.dataset.tab === 'history') loadHistory(1); else if (t.dataset.tab === 'history') loadHistory(1);
else if (t.dataset.tab === 'version') loadVersions(); else if (t.dataset.tab === 'version') loadVersions();
}; };
@@ -1134,6 +1193,142 @@
document.getElementById('editDedupeTotalDataModal').classList.remove('show'); document.getElementById('editDedupeTotalDataModal').classList.remove('show');
}; };
// ========== 店铺密钥管理 ==========
var shopKeyPage = 1, shopKeyPageSize = 15;
function buildShopKeyQuery(page) {
return 'page=' + (page || 1) + '&page_size=' + shopKeyPageSize;
}
function loadShopKeys(page) {
shopKeyPage = page || 1;
fetch('/api/admin/shop-keys?' + buildShopKeyQuery(shopKeyPage))
.then(function(r) { return r.json(); })
.then(function(res) {
var tbody = document.getElementById('shopKeyListBody');
if (!res.success) {
tbody.innerHTML = '<tr><td colspan="6" class="empty-tip">加载失败: ' + (res.error || '') + '</td></tr>';
return;
}
var items = res.items || [];
if (items.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="empty-tip">暂无店铺密钥</td></tr>';
} else {
tbody.innerHTML = items.map(function(item, index) {
var rowNo = (shopKeyPage - 1) * shopKeyPageSize + index + 1;
return '<tr><td>' + rowNo + '</td><td>' + (item.ziniao_account_name || '') + '</td><td>' + (item.ziniao_token || '') + '</td><td>' + (item.created_at || '') + '</td><td>' + (item.updated_at || '') + '</td><td>' +
'<button class="btn btn-sm" data-shop-key-edit="' + item.id + '" data-shop-key="' + (JSON.stringify(item).replace(/"/g, '&quot;')) + '">编辑</button> ' +
'<button class="btn btn-sm btn-danger" data-shop-key-delete="' + item.id + '" data-ziniao-account-name="' + (item.ziniao_account_name || '').replace(/"/g, '&quot;') + '">删除</button>' +
'</td></tr>';
}).join('');
}
renderPagination('shopKeyPagination', res.total, res.page, res.page_size, loadShopKeys);
bindShopKeyActions();
})
.catch(function() {
document.getElementById('shopKeyListBody').innerHTML = '<tr><td colspan="6" class="empty-tip">请求失败</td></tr>';
});
}
function bindShopKeyActions() {
document.querySelectorAll('[data-shop-key-edit]').forEach(function(btn) {
btn.onclick = function() {
var item = {};
try { item = JSON.parse((btn.dataset.shopKey || '').replace(/&quot;/g, '"')); } catch (e) { item = {}; }
document.getElementById('editShopKeyId').value = item.id || '';
document.getElementById('editShopKeyZiniaoAccountName').value = item.ziniao_account_name || '';
document.getElementById('editShopKeyZiniaoToken').value = item.ziniao_token || '';
document.getElementById('msgEditShopKey').textContent = '';
document.getElementById('msgEditShopKey').className = 'msg';
document.getElementById('editShopKeyModal').classList.add('show');
};
});
document.querySelectorAll('[data-shop-key-delete]').forEach(function(btn) {
btn.onclick = function() {
var name = (btn.dataset.ziniaoAccountName || '').replace(/&quot;/g, '"');
if (!confirm('确定删除店铺密钥「' + name + '」吗?')) return;
fetch('/api/admin/shop-key/' + btn.dataset.shopKeyDelete, { method: 'DELETE' })
.then(function(r) { return r.json(); })
.then(function(res) {
if (res.success) { loadShopKeys(shopKeyPage); }
else { alert(res.error || '删除失败'); }
});
};
});
}
document.getElementById('btnCreateShopKey').onclick = function() {
var ziniaoAccountName = (document.getElementById('shopKeyZiniaoAccountName').value || '').trim();
var ziniaoToken = (document.getElementById('shopKeyZiniaoToken').value || '').trim();
var msgEl = document.getElementById('msgShopKey');
msgEl.textContent = '';
msgEl.className = 'msg';
if (!ziniaoAccountName || !ziniaoToken) {
msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌';
msgEl.classList.add('err');
return;
}
fetch('/api/admin/shop-key', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ziniao_account_name: ziniaoAccountName,
ziniao_token: ziniaoToken
})
})
.then(function(r) { return r.json(); })
.then(function(res) {
if (res.success) {
document.getElementById('shopKeyZiniaoAccountName').value = '';
document.getElementById('shopKeyZiniaoToken').value = '';
msgEl.textContent = res.msg || '创建成功';
msgEl.className = 'msg ok';
loadShopKeys(1);
} else {
msgEl.textContent = res.error || '创建失败';
msgEl.className = 'msg err';
}
})
.catch(function() {
msgEl.textContent = '请求失败';
msgEl.className = 'msg err';
});
};
document.getElementById('btnSaveShopKey').onclick = function() {
var itemId = document.getElementById('editShopKeyId').value;
var ziniaoAccountName = (document.getElementById('editShopKeyZiniaoAccountName').value || '').trim();
var ziniaoToken = (document.getElementById('editShopKeyZiniaoToken').value || '').trim();
var msgEl = document.getElementById('msgEditShopKey');
msgEl.textContent = '';
msgEl.className = 'msg';
if (!ziniaoAccountName || !ziniaoToken) {
msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌';
msgEl.classList.add('err');
return;
}
fetch('/api/admin/shop-key/' + itemId, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ziniao_account_name: ziniaoAccountName,
ziniao_token: ziniaoToken
})
})
.then(function(r) { return r.json(); })
.then(function(res) {
if (res.success) {
document.getElementById('editShopKeyModal').classList.remove('show');
loadShopKeys(shopKeyPage);
} else {
msgEl.textContent = res.error || '保存失败';
msgEl.classList.add('err');
}
})
.catch(function() {
msgEl.textContent = '请求失败';
msgEl.classList.add('err');
});
};
document.getElementById('btnCloseEditShopKey').onclick = function() {
document.getElementById('editShopKeyModal').classList.remove('show');
};
// ========== 版本管理 ========== // ========== 版本管理 ==========
function loadVersions() { function loadVersions() {
fetch('/api/admin/versions') fetch('/api/admin/versions')
@@ -1334,6 +1529,7 @@
loadUserOptions(); loadUserOptions();
loadColumnsForPermission(); loadColumnsForPermission();
loadDedupeTotalData(1); loadDedupeTotalData(1);
loadShopKeys(1);
})(); })();
</script> </script>
</body> </body>
File diff suppressed because it is too large Load Diff
@@ -6,12 +6,30 @@
</div> </div>
<nav class="nav-tabs"> <nav class="nav-tabs">
<span class="nav-tab-group"> <div class="nav-tab-group">
<a v-for="item in navItems" :key="item.key" :href="item.href" class="nav-tab" <div
:class="{ active: active === item.key }"> v-for="group in navGroups"
:key="group.label"
class="nav-dropdown"
:class="{ active: group.items.some(item => item.key === active) }"
>
<button type="button" class="nav-dropdown-trigger">
<span>{{ group.label }}</span>
<span class="nav-dropdown-arrow">▾</span>
</button>
<div class="nav-dropdown-menu">
<a
v-for="item in group.items"
:key="item.key"
:href="item.href"
class="nav-dropdown-item"
:class="{ active: active === item.key }"
>
{{ item.label }} {{ item.label }}
</a> </a>
</span> </div>
</div>
</div>
</nav> </nav>
<div class="top-right"></div> <div class="top-right"></div>
@@ -25,12 +43,22 @@ const props = defineProps<{
const active = props.active const active = props.active
const navItems = [ const navGroups = [
{
label: '前端工具',
items: [
{ key: 'brand', label: '品牌检测', href: '/brand' }, { key: 'brand', label: '品牌检测', href: '/brand' },
{ key: 'dedupe', label: '数据去重', href: '/new_web_source/dedupe.html' }, { key: 'dedupe', label: '数据去重', href: '/new_web_source/dedupe.html' },
{ key: 'split', label: '数据拆分', href: '/new_web_source/split.html' }, { key: 'split', label: '数据拆分', href: '/new_web_source/split.html' },
{ key: 'convert', label: '格式转换', href: '/new_web_source/convert.html' }, { key: 'convert', label: '格式转换', href: '/new_web_source/convert.html' },
{ key: 'delete-brand', label: '删除品牌', href: '/new_web_source/delete-brand.html' }, ],
},
{
label: '运营工具',
items: [
{ key: 'delete-brand', label: '删除指定ASIN和品牌', href: '/new_web_source/delete-brand.html' },
],
},
] as const ] as const
</script> </script>
@@ -86,11 +114,16 @@ const navItems = [
justify-content: center; justify-content: center;
} }
.nav-tab { .nav-dropdown {
position: relative;
}
.nav-dropdown-trigger {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
min-width: 92px; gap: 8px;
min-width: 112px;
height: 38px; height: 38px;
padding: 0 16px; padding: 0 16px;
border-radius: 10px; border-radius: 10px;
@@ -99,21 +132,70 @@ const navItems = [
background: transparent; background: transparent;
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
text-decoration: none; cursor: pointer;
transition: all 0.2s ease; transition: all 0.2s ease;
} }
.nav-tab:hover { .nav-dropdown:hover .nav-dropdown-trigger,
.nav-dropdown.active .nav-dropdown-trigger {
color: #b9d6ff; color: #b9d6ff;
background: rgba(77, 126, 189, 0.14); background: rgba(77, 126, 189, 0.14);
} }
.nav-tab.active { .nav-dropdown.active .nav-dropdown-trigger {
background: rgba(77, 126, 189, 0.24); background: rgba(77, 126, 189, 0.24);
border-color: rgba(91, 148, 219, 0.35); border-color: rgba(91, 148, 219, 0.35);
color: #6caeff; color: #6caeff;
} }
.nav-dropdown-arrow {
font-size: 11px;
line-height: 1;
}
.nav-dropdown-menu {
position: absolute;
top: 100%;
left: 0;
min-width: 220px;
padding: 8px;
border: 1px solid #2a2a2a;
border-radius: 12px;
background: #171717;
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
display: none;
z-index: 20;
}
.nav-dropdown:hover .nav-dropdown-menu {
display: flex;
flex-direction: column;
gap: 4px;
}
.nav-dropdown-item {
display: flex;
align-items: center;
min-height: 38px;
padding: 0 12px;
border-radius: 8px;
color: #b8b8b8;
font-size: 13px;
font-weight: 600;
text-decoration: none;
transition: all 0.2s ease;
}
.nav-dropdown-item:hover {
color: #e8f2ff;
background: rgba(77, 126, 189, 0.14);
}
.nav-dropdown-item.active {
color: #6caeff;
background: rgba(77, 126, 189, 0.24);
}
.top-right { .top-right {
width: 120px; width: 120px;
flex-shrink: 0; flex-shrink: 0;
@@ -132,6 +214,16 @@ const navItems = [
justify-content: flex-start; justify-content: flex-start;
} }
.nav-tab-group {
width: 100%;
justify-content: flex-start;
}
.nav-dropdown-menu {
left: 0;
right: auto;
}
.top-right { .top-right {
display: none; display: none;
} }

Some files were not shown because too many files have changed in this diff Show More