diff --git a/app/.env b/app/.env
index c9e68e145..123ec5197 100644
--- a/app/.env
+++ b/app/.env
@@ -12,8 +12,8 @@ zn_username=%E8%87%AA%E5%8A%A8%E5%8C%96_Robot
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:18081
-java_api_base=http://8.136.19.173:18080
+# java_api_base=http://8.136.19.173:18080
diff --git a/app/__pycache__/main.cpython-312.pyc b/app/__pycache__/main.cpython-312.pyc
index 38a623b77..2e240fb21 100644
Binary files a/app/__pycache__/main.cpython-312.pyc and b/app/__pycache__/main.cpython-312.pyc differ
diff --git a/app/amazon/__pycache__/main.cpython-312.pyc b/app/amazon/__pycache__/main.cpython-312.pyc
index c2a436a71..73334f83e 100644
Binary files a/app/amazon/__pycache__/main.cpython-312.pyc and b/app/amazon/__pycache__/main.cpython-312.pyc differ
diff --git a/app/assets/convert.js b/app/assets/convert.js
index b211d5b35..6cf91a34a 100644
--- a/app/assets/convert.js
+++ b/app/assets/convert.js
@@ -1 +1 @@
-import{d as A,o as H,a as n,c as o,b as z,B as K,e as s,F as w,r as F,t as r,f as _,n as E,w as M,s as j,u as q,g as u,h as T,x as J,i as k,E as i,y as L,z as O,A as G,_ as Q,p as W,q as X}from"./pywebview-V_UIajJm.js";import{e as Y}from"./brand-1nUVsWrm.js";const Z={class:"page-shell module-page"},ee={class:"main-content"},se={class:"left-panel"},te={class:"upload-zone"},ae={class:"selected-files clean-placeholder"},le={key:0,class:"more-line"},ne={key:1},oe={class:"option-group"},ie=["value"],re={class:"template-item-content"},ce={class:"label"},ue={key:0,class:"template-tag"},de={key:1,class:"template-tag muted"},ve={key:2,class:"template-tag custom"},pe={class:"desc"},_e={key:0,class:"empty-option"},fe={class:"option-group"},me={class:"radio-item active"},he={class:"desc"},ye={class:"run-row"},ge=["disabled"],be={class:"loading-msg"},we={class:"right-panel"},ke={class:"task-list-wrap"},Ce={class:"clean-result-summary"},xe={class:"summary-card"},Fe={class:"summary-card"},Pe={class:"summary-card"},Ee={class:"result-list-wrap"},Te={key:0,class:"empty-tasks"},Ie={key:1,class:"task-list clean-result-list"},Be={class:"left"},Ne=["title"],$e={key:0,class:"files"},De={key:1,class:"files"},Re={class:"task-right"},Se=["onClick"],Ue=["onClick"],Ve=A({__name:"BrandConvertTab",setup(He){const v=u([]),g=u(""),f=u([]),m=u(!1),b=u([]),h=u({total:0,successCount:0,failedCount:0,items:[]}),d=u([]),c=u(""),C=T(()=>v.value.slice(0,8)),I=T(()=>d.value.find(a=>a.id===c.value)||null);async function P(a){const e=k();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const l of a){const p=typeof l=="string"?l:l.absolutePath,V=typeof l=="string"?void 0:l.relativePath,y=await e.upload_file_to_java(p,V);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${p}`);t.push(y.data)}return t}async function B(a){const e=await J();d.value=e||[];const t=d.value.find(p=>p.id===c.value);if(t){c.value=t.id;return}const l=d.value.find(p=>p.isDefault);if(l){c.value=l.id;return}c.value=d.value[0]?.id||""}async function N(a,e){v.value=a,g.value="",f.value=await P(a),i.success(e)}async function $(){const a=k();if(!a?.select_brand_xlsx_files){i.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await a.select_brand_xlsx_files();if(!e?.length)return;await N(e,`已选择 ${e.length} 个待转换文件`)}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function D(){const a=k();if(!a?.select_brand_folder){i.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await a.select_brand_folder();if(!e)return;g.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await Y(e);if(t.success&&t.items?.length){v.value=t.items.map(l=>l.relativePath),f.value=await P(t.items),i.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}i.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function R(){if(!f.value.length){i.warning("请先选择待转换 Excel 文件或文件夹");return}if(!c.value){i.warning("请先选择模板");return}try{m.value=!0;const a=await L({files:f.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),templateId:c.value,archiveName:f.value.some(e=>!!e.relativePath)&&g.value?g.value:void 0});h.value=a,b.value=a.items||[],await x(),i.success("格式转换完成")}catch(a){i.error(a instanceof Error?a.message:"格式转换失败")}finally{m.value=!1}}async function x(){try{const a=await O();b.value=a.items||[],h.value={total:a.items?.length||0,successCount:a.items?.filter(e=>e.success).length||0,failedCount:a.items?.filter(e=>!e.success).length||0,items:a.items||[]}}catch{}}async function S(a){try{await G(a),await x(),i.success("已删除")}catch(e){i.error(e instanceof Error?e.message:"删除失败")}}async function U(a){const e=k();if(!a.downloadUrl){i.warning("当前结果没有下载地址");return}const t=a.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.txt`;if(e?.save_file_from_url_new){const l=await e.save_file_from_url_new(a.downloadUrl,t);l.success?i.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&i.error(l.error);return}}return H(()=>{B().catch(()=>{}),x().catch(()=>{})}),(a,e)=>(n(),o("div",Z,[z(K,{active:"convert"}),s("div",ee,[s("aside",se,[e[5]||(e[5]=s("div",{class:"section-title"},"选择文件",-1)),s("div",te,[e[1]||(e[1]=s("div",{class:"hint"},"选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:$},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:D},"选择文件夹")]),s("div",ae,[v.value.length?(n(),o(w,{key:0},[(n(!0),o(w,null,F(C.value,t=>(n(),o("span",{key:t},r(t),1))),128)),v.value.length>C.value.length?(n(),o("span",le," 还有 "+r(v.value.length-C.value.length)+" 个文件未展开显示 ",1)):_("",!0)],64)):(n(),o("span",ne,"暂未选择待转换文件"))])]),e[6]||(e[6]=s("div",{class:"section-title"},"模板选择",-1)),s("div",oe,[(n(!0),o(w,null,F(d.value,t=>(n(),o("label",{key:t.id,class:E(["radio-item",{active:c.value===t.id}])},[M(s("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>c.value=l),type:"radio",value:t.id,name:"convert-template"},null,8,ie),[[j,c.value]]),s("div",re,[s("div",null,[s("span",ce,[q(r(t.templateName)+" ",1),t.isDefault?(n(),o("span",ue,"默认")):t.builtIn?(n(),o("span",de,"内置")):(n(),o("span",ve,"自定义"))]),s("div",pe,"输出文件:"+r(t.outputFilename),1)])])],2))),128)),d.value.length?_("",!0):(n(),o("div",_e,"暂无可用模板"))]),e[7]||(e[7]=s("div",{class:"section-title"},"转换说明",-1)),s("div",fe,[s("label",me,[e[3]||(e[3]=s("input",{type:"checkbox",checked:"",disabled:""},null,-1)),s("div",null,[e[2]||(e[2]=s("span",{class:"label"},"按当前模板输出",-1)),s("div",he,"当前模板:"+r(I.value?.templateName||"未加载模板"),1)])]),e[4]||(e[4]=s("label",{class:"radio-item active"},[s("input",{type:"checkbox",checked:"",disabled:""}),s("div",null,[s("span",{class:"label"},"SKU 使用雪花ID-序号"),s("div",{class:"desc"},"例如 1773816146796-1")])],-1))]),s("div",ye,[s("button",{type:"button",class:"btn-run",disabled:m.value,onClick:R},r(m.value?"转换中...":"开始转换"),9,ge),s("span",be,r(m.value?"正在生成并上传结果,请稍候…":"选择文件后即可执行格式转换,结果会显示在右侧供下载"),1)])]),s("section",we,[e[12]||(e[12]=s("div",{class:"panel-header"},"转换结果",-1)),s("div",ke,[s("div",Ce,[s("div",xe,[e[8]||(e[8]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,r(h.value.total),1)]),s("div",Fe,[e[9]||(e[9]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,r(h.value.successCount),1)]),s("div",Pe,[e[10]||(e[10]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,r(h.value.failedCount),1)])]),s("div",Ee,[e[11]||(e[11]=s("div",{class:"result-list-header"},[s("span",null,"生成的结果压缩包列表")],-1)),b.value.length===0?(n(),o("div",Te," 暂无转换结果,完成格式转换后会在这里展示结果压缩包 ")):(n(),o("ul",Ie,[(n(!0),o(w,null,F(b.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Be,[s("span",{class:"id",title:t.sourceFilename},r(t.sourceFilename||"-"),9,Ne),t.outputFilename?(n(),o("div",$e,"压缩包文件:"+r(t.outputFilename),1)):_("",!0),t.error?(n(),o("div",De,"错误信息:"+r(t.error),1)):_("",!0)]),s("div",Re,[s("span",{class:E(["status",t.success?"success":"failed"])},r(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:l=>U(t)}," 下载压缩包 ",8,Se)):_("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:l=>S(t.resultId)}," 删除 ",8,Ue)):_("",!0)])]))),128))]))])])])])]))}}),Ae=Q(Ve,[["__scopeId","data-v-7c280b44"]]);W(Ae).use(X).mount("#app");
+import{d as A,o as H,a as n,c as o,b as z,B as K,e as s,F as w,r as F,t as r,f as _,n as E,w as M,s as j,u as q,g as u,h as T,x as J,i as k,E as i,y as L,z as O,A as G,_ as Q,p as W,q as X}from"./pywebview-Cq_E2BnJ.js";import{e as Y}from"./brand-DZ5_PGnw.js";const Z={class:"page-shell module-page"},ee={class:"main-content"},se={class:"left-panel"},te={class:"upload-zone"},ae={class:"selected-files clean-placeholder"},le={key:0,class:"more-line"},ne={key:1},oe={class:"option-group"},ie=["value"],re={class:"template-item-content"},ce={class:"label"},ue={key:0,class:"template-tag"},de={key:1,class:"template-tag muted"},ve={key:2,class:"template-tag custom"},pe={class:"desc"},_e={key:0,class:"empty-option"},fe={class:"option-group"},me={class:"radio-item active"},he={class:"desc"},ye={class:"run-row"},ge=["disabled"],be={class:"loading-msg"},we={class:"right-panel"},ke={class:"task-list-wrap"},Ce={class:"clean-result-summary"},xe={class:"summary-card"},Fe={class:"summary-card"},Pe={class:"summary-card"},Ee={class:"result-list-wrap"},Te={key:0,class:"empty-tasks"},Ie={key:1,class:"task-list clean-result-list"},Be={class:"left"},Ne=["title"],$e={key:0,class:"files"},De={key:1,class:"files"},Re={class:"task-right"},Se=["onClick"],Ue=["onClick"],Ve=A({__name:"BrandConvertTab",setup(He){const v=u([]),g=u(""),f=u([]),m=u(!1),b=u([]),h=u({total:0,successCount:0,failedCount:0,items:[]}),d=u([]),c=u(""),C=T(()=>v.value.slice(0,8)),I=T(()=>d.value.find(a=>a.id===c.value)||null);async function P(a){const e=k();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const l of a){const p=typeof l=="string"?l:l.absolutePath,V=typeof l=="string"?void 0:l.relativePath,y=await e.upload_file_to_java(p,V);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${p}`);t.push(y.data)}return t}async function B(a){const e=await J();d.value=e||[];const t=d.value.find(p=>p.id===c.value);if(t){c.value=t.id;return}const l=d.value.find(p=>p.isDefault);if(l){c.value=l.id;return}c.value=d.value[0]?.id||""}async function N(a,e){v.value=a,g.value="",f.value=await P(a),i.success(e)}async function $(){const a=k();if(!a?.select_brand_xlsx_files){i.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await a.select_brand_xlsx_files();if(!e?.length)return;await N(e,`已选择 ${e.length} 个待转换文件`)}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function D(){const a=k();if(!a?.select_brand_folder){i.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await a.select_brand_folder();if(!e)return;g.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await Y(e);if(t.success&&t.items?.length){v.value=t.items.map(l=>l.relativePath),f.value=await P(t.items),i.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}i.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function R(){if(!f.value.length){i.warning("请先选择待转换 Excel 文件或文件夹");return}if(!c.value){i.warning("请先选择模板");return}try{m.value=!0;const a=await L({files:f.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),templateId:c.value,archiveName:f.value.some(e=>!!e.relativePath)&&g.value?g.value:void 0});h.value=a,b.value=a.items||[],await x(),i.success("格式转换完成")}catch(a){i.error(a instanceof Error?a.message:"格式转换失败")}finally{m.value=!1}}async function x(){try{const a=await O();b.value=a.items||[],h.value={total:a.items?.length||0,successCount:a.items?.filter(e=>e.success).length||0,failedCount:a.items?.filter(e=>!e.success).length||0,items:a.items||[]}}catch{}}async function S(a){try{await G(a),await x(),i.success("已删除")}catch(e){i.error(e instanceof Error?e.message:"删除失败")}}async function U(a){const e=k();if(!a.downloadUrl){i.warning("当前结果没有下载地址");return}const t=a.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.txt`;if(e?.save_file_from_url_new){const l=await e.save_file_from_url_new(a.downloadUrl,t);l.success?i.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&i.error(l.error);return}}return H(()=>{B().catch(()=>{}),x().catch(()=>{})}),(a,e)=>(n(),o("div",Z,[z(K,{active:"convert"}),s("div",ee,[s("aside",se,[e[5]||(e[5]=s("div",{class:"section-title"},"选择文件",-1)),s("div",te,[e[1]||(e[1]=s("div",{class:"hint"},"选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:$},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:D},"选择文件夹")]),s("div",ae,[v.value.length?(n(),o(w,{key:0},[(n(!0),o(w,null,F(C.value,t=>(n(),o("span",{key:t},r(t),1))),128)),v.value.length>C.value.length?(n(),o("span",le," 还有 "+r(v.value.length-C.value.length)+" 个文件未展开显示 ",1)):_("",!0)],64)):(n(),o("span",ne,"暂未选择待转换文件"))])]),e[6]||(e[6]=s("div",{class:"section-title"},"模板选择",-1)),s("div",oe,[(n(!0),o(w,null,F(d.value,t=>(n(),o("label",{key:t.id,class:E(["radio-item",{active:c.value===t.id}])},[M(s("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>c.value=l),type:"radio",value:t.id,name:"convert-template"},null,8,ie),[[j,c.value]]),s("div",re,[s("div",null,[s("span",ce,[q(r(t.templateName)+" ",1),t.isDefault?(n(),o("span",ue,"默认")):t.builtIn?(n(),o("span",de,"内置")):(n(),o("span",ve,"自定义"))]),s("div",pe,"输出文件:"+r(t.outputFilename),1)])])],2))),128)),d.value.length?_("",!0):(n(),o("div",_e,"暂无可用模板"))]),e[7]||(e[7]=s("div",{class:"section-title"},"转换说明",-1)),s("div",fe,[s("label",me,[e[3]||(e[3]=s("input",{type:"checkbox",checked:"",disabled:""},null,-1)),s("div",null,[e[2]||(e[2]=s("span",{class:"label"},"按当前模板输出",-1)),s("div",he,"当前模板:"+r(I.value?.templateName||"未加载模板"),1)])]),e[4]||(e[4]=s("label",{class:"radio-item active"},[s("input",{type:"checkbox",checked:"",disabled:""}),s("div",null,[s("span",{class:"label"},"SKU 使用雪花ID-序号"),s("div",{class:"desc"},"例如 1773816146796-1")])],-1))]),s("div",ye,[s("button",{type:"button",class:"btn-run",disabled:m.value,onClick:R},r(m.value?"转换中...":"开始转换"),9,ge),s("span",be,r(m.value?"正在生成并上传结果,请稍候…":"选择文件后即可执行格式转换,结果会显示在右侧供下载"),1)])]),s("section",we,[e[12]||(e[12]=s("div",{class:"panel-header"},"转换结果",-1)),s("div",ke,[s("div",Ce,[s("div",xe,[e[8]||(e[8]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,r(h.value.total),1)]),s("div",Fe,[e[9]||(e[9]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,r(h.value.successCount),1)]),s("div",Pe,[e[10]||(e[10]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,r(h.value.failedCount),1)])]),s("div",Ee,[e[11]||(e[11]=s("div",{class:"result-list-header"},[s("span",null,"生成的结果压缩包列表")],-1)),b.value.length===0?(n(),o("div",Te," 暂无转换结果,完成格式转换后会在这里展示结果压缩包 ")):(n(),o("ul",Ie,[(n(!0),o(w,null,F(b.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Be,[s("span",{class:"id",title:t.sourceFilename},r(t.sourceFilename||"-"),9,Ne),t.outputFilename?(n(),o("div",$e,"压缩包文件:"+r(t.outputFilename),1)):_("",!0),t.error?(n(),o("div",De,"错误信息:"+r(t.error),1)):_("",!0)]),s("div",Re,[s("span",{class:E(["status",t.success?"success":"failed"])},r(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:l=>U(t)}," 下载压缩包 ",8,Se)):_("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:l=>S(t.resultId)}," 删除 ",8,Ue)):_("",!0)])]))),128))]))])])])])]))}}),Ae=Q(Ve,[["__scopeId","data-v-7c280b44"]]);W(Ae).use(X).mount("#app");
diff --git a/app/assets/dedupe.js b/app/assets/dedupe.js
index 1b6f30d4c..3002d313f 100644
--- a/app/assets/dedupe.js
+++ b/app/assets/dedupe.js
@@ -1 +1 @@
-import{d as z,o as W,a as n,c as o,b as q,B as J,e as s,F as C,r as F,t as i,f as b,n as I,w as P,v as B,g as u,h as L,i as x,E as r,j as O,k as G,l as Q,m as X,_ as Y,p as Z,q as ee}from"./pywebview-V_UIajJm.js";import{e as se}from"./brand-1nUVsWrm.js";const te={class:"page-shell module-page"},le={class:"main-content"},ae={class:"left-panel"},ne={class:"upload-zone"},oe={class:"selected-files clean-placeholder"},re={key:0,class:"more-line"},ie={key:1},ue={class:"option-group column-option-group"},ce={class:"column-toolbar"},de={class:"column-count"},ve={key:0,class:"column-grid"},pe=["value"],fe={key:1,class:"empty-column-state"},_e={class:"option-group"},me={class:"run-row"},he=["disabled"],ge={class:"loading-msg"},ye={class:"right-panel"},be={class:"task-list-wrap"},we={class:"clean-result-summary"},ke={class:"summary-card"},Ce={class:"summary-card"},Ie={class:"summary-card"},xe={class:"result-list-wrap"},Ee={key:0,class:"empty-tasks"},De={key:1,class:"task-list clean-result-list"},Fe={class:"left"},Pe=["title"],Be={key:0,class:"files"},Se={key:1,class:"files"},Ue={class:"task-right"},Ne=["onClick"],$e=["onClick"],Ae=z({__name:"BrandDedupeTab",setup(Ke){const p=u([]),c=u([]),f=u([]),w=u(""),d=u([]),S=u(!1),_=u(!0),m=u(!0),h=u(!1),k=u([]),g=u({total:0,successCount:0,failedCount:0,items:[]}),E=L(()=>f.value.slice(0,8));function $(){c.value=[...p.value]}function A(){c.value=[]}async function U(l){const e=x();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of l){const v=typeof a=="string"?a:a.absolutePath,j=typeof a=="string"?void 0:a.relativePath,y=await e.upload_file_to_java(v,j);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${v}`);t.push(y.data)}return t}async function N(l){const e=await X(l);if(!e.headers?.length){r.error("读取 Excel 表头失败"),p.value=[],c.value=[];return}const t=["id","ASIN","国家","价格","卖家名称"],a=[...t.filter(v=>e.headers?.includes(v)),...(e.headers||[]).filter(v=>!t.includes(v))];p.value=a,c.value=t.filter(v=>a.includes(v))}async function H(l,e){f.value=l,w.value="",d.value=await U(l),d.value.length>0&&await N(d.value[0].fileKey),r.success(e)}async function K(){const l=x();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await l.select_brand_xlsx_files();if(!e?.length)return;await H(e,`已选择 ${e.length} 个待清洗文件`)}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function R(){const l=x();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await l.select_brand_folder();if(!e)return;w.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await se(e);if(t.success&&t.items?.length){f.value=t.items.map(a=>a.relativePath),d.value=await U(t.items),d.value.length>0&&await N(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function V(){if(!d.value.length){r.warning("请先选择待清洗 Excel 文件或文件夹");return}if(!c.value.length){r.warning("请至少选择一列保留列");return}if(!S.value&&!_.value&&!m.value){r.warning("请至少选择一种 ID 保留规则");return}try{h.value=!0;const l=await O({files:d.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),selectedColumns:c.value,keepIntegerIds:S.value,keepUnderscoreIds:_.value,keepIntegerMainIdsWhenNoSubIds:m.value,archiveName:d.value.some(e=>!!e.relativePath)&&w.value?w.value:void 0});g.value=l,k.value=l.items||[],await D(),r.success("数据去重完成")}catch(l){r.error(l instanceof Error?l.message:"去重失败")}finally{h.value=!1}}async function D(){try{const l=await G();k.value=l.items||[],g.value={total:l.items?.length||0,successCount:l.items?.filter(e=>e.success).length||0,failedCount:l.items?.filter(e=>!e.success).length||0,items:l.items||[]}}catch{}}async function M(l){try{await Q(l),await D(),r.success("已删除")}catch(e){r.error(e instanceof Error?e.message:"删除失败")}}async function T(l){const e=x();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}_cleaned.xlsx`;if(e?.save_file_from_url_new){const a=await e.save_file_from_url_new(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}}return W(()=>{D().catch(()=>{})}),(l,e)=>(n(),o("div",te,[q(J,{active:"dedupe"}),s("div",le,[s("aside",ae,[e[7]||(e[7]=s("div",{class:"section-title"},"选择文件",-1)),s("div",ne,[e[3]||(e[3]=s("div",{class:"hint"},"选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:K},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:R},"选择文件夹")]),s("div",oe,[f.value.length?(n(),o(C,{key:0},[(n(!0),o(C,null,F(E.value,t=>(n(),o("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(n(),o("span",re," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):b("",!0)],64)):(n(),o("span",ie,"暂未选择待清洗文件"))])]),e[8]||(e[8]=s("div",{class:"section-title"},"保留列设置",-1)),s("div",ue,[s("div",ce,[s("span",de,"已选择 "+i(c.value.length)+" / "+i(p.value.length)+" 列",1),s("div",{class:"column-actions"},[s("button",{type:"button",class:"opt-btn small",onClick:$},"全选"),s("button",{type:"button",class:"opt-btn small",onClick:A},"清空")])]),p.value.length?(n(),o("div",ve,[(n(!0),o(C,null,F(p.value,t=>(n(),o("label",{key:t,class:I(["column-item",{active:c.value.includes(t)}])},[P(s("input",{"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),type:"checkbox",value:t},null,8,pe),[[B,c.value]]),s("span",null,i(t),1)],2))),128))])):(n(),o("div",fe,"请选择 Excel 文件后读取表头并填充可保留列")),e[4]||(e[4]=s("div",{class:"desc"},"读取首个 Excel 文件的第一行作为表头,用于动态选择需要保留的列。",-1))]),e[9]||(e[9]=s("div",{class:"section-title"},"ID 保留规则",-1)),s("div",_e,[s("label",{class:I(["radio-item",{active:_.value}])},[P(s("input",{"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),type:"checkbox"},null,512),[[B,_.value]]),e[5]||(e[5]=s("div",null,[s("span",{class:"label"},"保留子链接"),s("div",{class:"desc"},"例如 1_1、2_3 这种带下划线的子项 ID")],-1))],2),s("label",{class:I(["radio-item",{active:m.value}])},[P(s("input",{"onUpdate:modelValue":e[2]||(e[2]=t=>m.value=t),type:"checkbox"},null,512),[[B,m.value]]),e[6]||(e[6]=s("div",null,[s("span",{class:"label"},"仅剩主链接无子链接"),s("div",{class:"desc"},"当某个主链接只有 13 这类主 ID、没有 13_1 这类对应子 ID 时,自动保留该主 ID")],-1))],2)]),s("div",me,[s("button",{type:"button",class:"btn-run",disabled:h.value,onClick:V},i(h.value?"清洗中...":"开始清洗"),9,he),s("span",ge,i(h.value?"正在处理文件并上传结果,请稍候…":"选择文件、列和 ID 规则后即可执行清洗,结果会显示在右侧供下载"),1)])]),s("section",ye,[e[14]||(e[14]=s("div",{class:"panel-header"},"去重结果",-1)),s("div",be,[s("div",we,[s("div",ke,[e[10]||(e[10]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,i(g.value.total),1)]),s("div",Ce,[e[11]||(e[11]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,i(g.value.successCount),1)]),s("div",Ie,[e[12]||(e[12]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,i(g.value.failedCount),1)])]),s("div",xe,[e[13]||(e[13]=s("div",{class:"result-list-header"},[s("span",null,"处理后的 Excel 列表")],-1)),k.value.length===0?(n(),o("div",Ee," 暂无去重结果,完成数据去重后会在这里展示输出文件 ")):(n(),o("ul",De,[(n(!0),o(C,null,F(k.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Fe,[s("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Pe),t.outputFilename?(n(),o("div",Be,"输出文件:"+i(t.outputFilename),1)):b("",!0),t.error?(n(),o("div",Se,"错误信息:"+i(t.error),1)):b("",!0)]),s("div",Ue,[s("span",{class:I(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:a=>T(t)}," 下载文件 ",8,Ne)):b("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:a=>M(t.resultId)}," 删除 ",8,$e)):b("",!0)])]))),128))]))])])])])]))}}),He=Y(Ae,[["__scopeId","data-v-bdaefe1c"]]);Z(He).use(ee).mount("#app");
+import{d as z,o as W,a as n,c as o,b as q,B as J,e as s,F as C,r as F,t as i,f as b,n as I,w as P,v as B,g as u,h as L,i as x,E as r,j as O,k as G,l as Q,m as X,_ as Y,p as Z,q as ee}from"./pywebview-Cq_E2BnJ.js";import{e as se}from"./brand-DZ5_PGnw.js";const te={class:"page-shell module-page"},le={class:"main-content"},ae={class:"left-panel"},ne={class:"upload-zone"},oe={class:"selected-files clean-placeholder"},re={key:0,class:"more-line"},ie={key:1},ue={class:"option-group column-option-group"},ce={class:"column-toolbar"},de={class:"column-count"},ve={key:0,class:"column-grid"},pe=["value"],fe={key:1,class:"empty-column-state"},_e={class:"option-group"},me={class:"run-row"},he=["disabled"],ge={class:"loading-msg"},ye={class:"right-panel"},be={class:"task-list-wrap"},we={class:"clean-result-summary"},ke={class:"summary-card"},Ce={class:"summary-card"},Ie={class:"summary-card"},xe={class:"result-list-wrap"},Ee={key:0,class:"empty-tasks"},De={key:1,class:"task-list clean-result-list"},Fe={class:"left"},Pe=["title"],Be={key:0,class:"files"},Se={key:1,class:"files"},Ue={class:"task-right"},Ne=["onClick"],$e=["onClick"],Ae=z({__name:"BrandDedupeTab",setup(Ke){const p=u([]),c=u([]),f=u([]),w=u(""),d=u([]),S=u(!1),_=u(!0),m=u(!0),h=u(!1),k=u([]),g=u({total:0,successCount:0,failedCount:0,items:[]}),E=L(()=>f.value.slice(0,8));function $(){c.value=[...p.value]}function A(){c.value=[]}async function U(l){const e=x();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of l){const v=typeof a=="string"?a:a.absolutePath,j=typeof a=="string"?void 0:a.relativePath,y=await e.upload_file_to_java(v,j);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${v}`);t.push(y.data)}return t}async function N(l){const e=await X(l);if(!e.headers?.length){r.error("读取 Excel 表头失败"),p.value=[],c.value=[];return}const t=["id","ASIN","国家","价格","卖家名称"],a=[...t.filter(v=>e.headers?.includes(v)),...(e.headers||[]).filter(v=>!t.includes(v))];p.value=a,c.value=t.filter(v=>a.includes(v))}async function H(l,e){f.value=l,w.value="",d.value=await U(l),d.value.length>0&&await N(d.value[0].fileKey),r.success(e)}async function K(){const l=x();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await l.select_brand_xlsx_files();if(!e?.length)return;await H(e,`已选择 ${e.length} 个待清洗文件`)}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function R(){const l=x();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await l.select_brand_folder();if(!e)return;w.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await se(e);if(t.success&&t.items?.length){f.value=t.items.map(a=>a.relativePath),d.value=await U(t.items),d.value.length>0&&await N(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function V(){if(!d.value.length){r.warning("请先选择待清洗 Excel 文件或文件夹");return}if(!c.value.length){r.warning("请至少选择一列保留列");return}if(!S.value&&!_.value&&!m.value){r.warning("请至少选择一种 ID 保留规则");return}try{h.value=!0;const l=await O({files:d.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),selectedColumns:c.value,keepIntegerIds:S.value,keepUnderscoreIds:_.value,keepIntegerMainIdsWhenNoSubIds:m.value,archiveName:d.value.some(e=>!!e.relativePath)&&w.value?w.value:void 0});g.value=l,k.value=l.items||[],await D(),r.success("数据去重完成")}catch(l){r.error(l instanceof Error?l.message:"去重失败")}finally{h.value=!1}}async function D(){try{const l=await G();k.value=l.items||[],g.value={total:l.items?.length||0,successCount:l.items?.filter(e=>e.success).length||0,failedCount:l.items?.filter(e=>!e.success).length||0,items:l.items||[]}}catch{}}async function M(l){try{await Q(l),await D(),r.success("已删除")}catch(e){r.error(e instanceof Error?e.message:"删除失败")}}async function T(l){const e=x();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}_cleaned.xlsx`;if(e?.save_file_from_url_new){const a=await e.save_file_from_url_new(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}}return W(()=>{D().catch(()=>{})}),(l,e)=>(n(),o("div",te,[q(J,{active:"dedupe"}),s("div",le,[s("aside",ae,[e[7]||(e[7]=s("div",{class:"section-title"},"选择文件",-1)),s("div",ne,[e[3]||(e[3]=s("div",{class:"hint"},"选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:K},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:R},"选择文件夹")]),s("div",oe,[f.value.length?(n(),o(C,{key:0},[(n(!0),o(C,null,F(E.value,t=>(n(),o("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(n(),o("span",re," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):b("",!0)],64)):(n(),o("span",ie,"暂未选择待清洗文件"))])]),e[8]||(e[8]=s("div",{class:"section-title"},"保留列设置",-1)),s("div",ue,[s("div",ce,[s("span",de,"已选择 "+i(c.value.length)+" / "+i(p.value.length)+" 列",1),s("div",{class:"column-actions"},[s("button",{type:"button",class:"opt-btn small",onClick:$},"全选"),s("button",{type:"button",class:"opt-btn small",onClick:A},"清空")])]),p.value.length?(n(),o("div",ve,[(n(!0),o(C,null,F(p.value,t=>(n(),o("label",{key:t,class:I(["column-item",{active:c.value.includes(t)}])},[P(s("input",{"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),type:"checkbox",value:t},null,8,pe),[[B,c.value]]),s("span",null,i(t),1)],2))),128))])):(n(),o("div",fe,"请选择 Excel 文件后读取表头并填充可保留列")),e[4]||(e[4]=s("div",{class:"desc"},"读取首个 Excel 文件的第一行作为表头,用于动态选择需要保留的列。",-1))]),e[9]||(e[9]=s("div",{class:"section-title"},"ID 保留规则",-1)),s("div",_e,[s("label",{class:I(["radio-item",{active:_.value}])},[P(s("input",{"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),type:"checkbox"},null,512),[[B,_.value]]),e[5]||(e[5]=s("div",null,[s("span",{class:"label"},"保留子链接"),s("div",{class:"desc"},"例如 1_1、2_3 这种带下划线的子项 ID")],-1))],2),s("label",{class:I(["radio-item",{active:m.value}])},[P(s("input",{"onUpdate:modelValue":e[2]||(e[2]=t=>m.value=t),type:"checkbox"},null,512),[[B,m.value]]),e[6]||(e[6]=s("div",null,[s("span",{class:"label"},"仅剩主链接无子链接"),s("div",{class:"desc"},"当某个主链接只有 13 这类主 ID、没有 13_1 这类对应子 ID 时,自动保留该主 ID")],-1))],2)]),s("div",me,[s("button",{type:"button",class:"btn-run",disabled:h.value,onClick:V},i(h.value?"清洗中...":"开始清洗"),9,he),s("span",ge,i(h.value?"正在处理文件并上传结果,请稍候…":"选择文件、列和 ID 规则后即可执行清洗,结果会显示在右侧供下载"),1)])]),s("section",ye,[e[14]||(e[14]=s("div",{class:"panel-header"},"去重结果",-1)),s("div",be,[s("div",we,[s("div",ke,[e[10]||(e[10]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,i(g.value.total),1)]),s("div",Ce,[e[11]||(e[11]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,i(g.value.successCount),1)]),s("div",Ie,[e[12]||(e[12]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,i(g.value.failedCount),1)])]),s("div",xe,[e[13]||(e[13]=s("div",{class:"result-list-header"},[s("span",null,"处理后的 Excel 列表")],-1)),k.value.length===0?(n(),o("div",Ee," 暂无去重结果,完成数据去重后会在这里展示输出文件 ")):(n(),o("ul",De,[(n(!0),o(C,null,F(k.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Fe,[s("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Pe),t.outputFilename?(n(),o("div",Be,"输出文件:"+i(t.outputFilename),1)):b("",!0),t.error?(n(),o("div",Se,"错误信息:"+i(t.error),1)):b("",!0)]),s("div",Ue,[s("span",{class:I(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:a=>T(t)}," 下载文件 ",8,Ne)):b("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:a=>M(t.resultId)}," 删除 ",8,$e)):b("",!0)])]))),128))]))])])])])]))}}),He=Y(Ae,[["__scopeId","data-v-bdaefe1c"]]);Z(He).use(ee).mount("#app");
diff --git a/app/assets/delete-brand.js b/app/assets/delete-brand.js
index e8b6a2463..ccccdd15e 100644
--- a/app/assets/delete-brand.js
+++ b/app/assets/delete-brand.js
@@ -1 +1 @@
-import{d as Oe,o as He,I as Je,a as u,c,b as Ge,B as je,e as r,F as K,r as re,t as f,f as p,J as Ve,K as Fe,n as Ne,g as m,h as W,L as ze,i as O,E as h,M as Qe,N as Xe,O as We,P as Ye,_ as Ze,p as es,q as ss}from"./pywebview-V_UIajJm.js";import{e as ts}from"./brand-1nUVsWrm.js";const as={class:"page-shell module-page"},ns={class:"main-content"},ls={class:"left-panel"},rs={class:"upload-zone"},os={class:"selected-files clean-placeholder split-selected-files"},is={key:0,class:"more-line"},us={key:1},cs={class:"run-row"},ds=["disabled"],fs={class:"loading-msg"},vs={key:0,class:"queue-debug-card"},ps={key:0,class:"queue-debug-line"},hs={key:1,class:"queue-debug-payload"},_s={class:"right-panel"},gs={class:"task-list-wrap"},ys={class:"clean-result-summary"},ks={class:"summary-card"},ms={class:"summary-card"},ws={class:"summary-card"},Is={class:"result-list-wrap"},Ss={key:0,class:"empty-tasks"},bs={key:0,class:"result-subsection"},Cs={class:"task-list clean-result-list"},Ts={class:"left split-result-main"},Fs=["title"],Ns={class:"files"},Es={class:"files"},Rs={key:0,class:"files"},xs={key:1,class:"files"},$s={key:2,class:"files"},Ps={key:3,class:"time"},As={key:4,class:"delete-brand-progress-block"},Ds={class:"delete-brand-progress-header"},Ms={class:"delete-brand-progress-bar"},Bs={class:"files delete-brand-progress"},Us={key:5,class:"files split-entry-list delete-brand-preview"},qs={key:6,class:"files"},Ls={class:"task-right split-result-actions"},Ks=["onClick"],Os=["onClick"],Hs=["onClick"],Js={key:1,class:"result-subsection"},Gs={class:"task-list clean-result-list"},js={class:"left split-result-main"},Vs=["title"],zs={class:"files"},Qs={class:"files"},Xs={key:0,class:"files"},Ws={key:1,class:"files"},Ys={key:2,class:"time"},Zs={key:3,class:"delete-brand-progress-block"},et={class:"delete-brand-progress-header"},st={class:"delete-brand-progress-bar"},tt={class:"files delete-brand-progress"},at={key:4,class:"files split-entry-list delete-brand-preview"},nt={key:5,class:"files"},lt={class:"task-right split-result-actions"},rt=["onClick"],ot=["onClick"],it=Oe({__name:"BrandDeleteBrandTab",setup(ct){function M(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const $=m([]),H=m([]),B=m(!1),oe=m([]),v=m([]),J=m([]),G=m({total:0,successCount:0,failedCount:0,items:[]}),T=m(""),C=m(""),g=m({}),S=m(null),Y=m(!1),P=m(!1),A=m(""),j=m(!1),Z=W(()=>$.value.slice(0,10)),F=W(()=>{const e=[];return v.value.forEach(s=>{e.push(...s.items)}),e});function Ee(){try{const e=typeof window<"u"?window.localStorage.getItem(M()):null;if(e){if(v.value=JSON.parse(e),v.value.length>0){const s=v.value[v.value.length-1];T.value=s.queuePushResult||"",C.value=s.queuePayloadText||""}}else v.value=[]}catch{v.value=[]}}function ie(e,s,t,a){if(!s?.length)return;const n=v.value.findIndex(d=>d.taskId===e),o=n>=0?v.value[n]:null,l=s.map(d=>{const _=o?.items.find(Ke=>D(Ke,d)),k=Array.isArray(d.countries)?d.countries:void 0,y=Array.isArray(_?.countries)?_?.countries:void 0,w=k&&k.length>0?k:y&&y.length>0?y:k??y,I=Array.isArray(d.previewRows)?d.previewRows:void 0,b=Array.isArray(_?.previewRows)?_?.previewRows:void 0,le=I&&I.length>0?I:b&&b.length>0?b:I??b;return{...d,countries:w,previewRows:le,_pushed:_?._pushed??d._pushed??!1,_completed:_?._completed??d._completed??!1}}),i={taskId:e,items:l,createdAt:o?.createdAt||Date.now(),queuePushResult:t??o?.queuePushResult,queuePayloadText:a??o?.queuePayloadText};n>=0?v.value[n]=i:v.value.push(i),typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}function ue(e){const s=v.value.length;v.value=v.value.filter(t=>t.taskId!==e),v.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}const V=W(()=>J.value.filter(e=>!F.value.some(s=>D(s,e)))),Re=W(()=>F.value.length>0||V.value.length>0);function ce(){typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}function N(e){return e?(v.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function ee(e){return e&&v.value.find(s=>s.taskId===e)||null}function D(e,s){return!e||!s?!1:e.resultId!=null&&s.resultId!=null?e.resultId===s.resultId:e.fileKey&&s.fileKey?e.fileKey===s.fileKey:e.sourceFilename===s.sourceFilename}function E(e,s){const t=ee(e);return t&&t.items.find(a=>D(a,s))||null}function de(e){if(!e)return!1;const s=ee(e);if(!s)return!1;let t=!1;const a=g.value[e]?.line_progress?.info,n=N(e);if(a?.file_name&&a.current_line!=null&&a.total_lines!=null&&a.total_lines>0&&a.current_line>=a.total_lines){const o=s.items.find(l=>l.sourceFilename===a.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!n){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const l=s.items[0];l&&!l._completed&&(l._completed=!0,t=!0)}}return t&&ce(),t}function fe(e){return e&&g.value[e]?.task?.status||""}function z(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&g.value[s]?.task?.errorMessage||""}function ve(e){const s=e.taskId;if(!s)return!1;const t=g.value[s]?.line_progress,a=fe(s),n=N(s),o=x(e);if(n){const l=E(s,e),i=L(e)===A.value,d=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return!!(i||d||l?._pushed||(a==="RUNNING"||a==="PENDING"||!a)&&l?._completed)}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function pe(e){return e.map(s=>s.matchStatus==="MATCHED"?{...s,_pushed:!1,_completed:!1}:{...s,matched:!1,openStoreUrl:void 0,error:s.error||void 0,_pushed:!1,_completed:!1})}function he(e){return e.matchStatus==="MATCHED"?`已匹配 ${e.shopId||""}`.trim():e.matchMessage?e.matchMessage:e.matchStatus==="CONFLICT"?"存在多个同名店铺,请人工确认":e.matchStatus==="PENDING"||e.matchStatus==="INDEX_STALE"?"店铺索引暂未就绪":e.matchStatus?e.matchStatus:e.matched?`已匹配 ${e.shopId||""}`.trim():"待匹配"}function xe(){oe.value=[...F.value,...V.value]}function R(){xe(),$e(oe.value)}function $e(e){G.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function se(e){const s=e.taskId;return s&&(g.value[s]?.fileProgress||[]).find(n=>n.fileKey&&e.fileKey?n.fileKey===e.fileKey:n.sourceFilename&&e.sourceFilename?n.sourceFilename===e.sourceFilename:!1)||null}function _e(e){const s=e.taskId;if(!s)return"";const t=g.value[s],a=t?.line_progress?.info,n=se(e);if(N(s)){const i=E(s,e),d=t?.task?.status,_=!!(a?.file_name&&a.file_name===e.sourceFilename);let k=i?._completed?"COMPLETED":(i?._pushed,"PENDING"),y=0,w=Math.max(0,e.totalRows??n?.totalRows??0);d==="SUCCESS"||d==="FAILED"&&i?._completed?(k="COMPLETED",y=w):_?(k="RUNNING",y=Math.max(0,Math.min(w||Number.MAX_SAFE_INTEGER,a?.current_line??0)),!w&&a?.total_lines&&a.total_lines>0&&(w=a.total_lines)):i?._completed?(k="COMPLETED",y=w):i?._pushed&&(k="PENDING",y=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${y}/${w}`),a?.finished_files!=null){const b=a.file_total&&a.file_total>0?`/${a.file_total}`:"";I.push(`已完成文件:${a.finished_files}${b}`)}return a?.phase&&I.push(`阶段:${a.phase}`),I.join("|")}if(n){const i=[],d=n.processedRows??0,_=n.totalRows??0;if(n.status&&i.push(`文件状态:${n.status}`),i.push(`文件进度:${d}/${_}`),a?.finished_files!=null){const k=a.file_total&&a.file_total>0?`/${a.file_total}`:"";i.push(`已完成文件:${a.finished_files}${k}`)}return a?.phase&&i.push(`阶段:${a.phase}`),i.join("|")}if(!t?.line_progress?.has_progress||!a){const i=t?.task?.status;return i?`任务状态:${i}`:""}const l=[];if(a.phase&&l.push(`阶段:${a.phase}`),a.file_index&&a.file_total&&l.push(`文件:${a.file_index}/${a.file_total}`),a.file_name&&l.push(`当前文件:${a.file_name}`),a.current_line!=null&&a.total_lines!=null&&l.push(`${N(s)?"当前文件进度":"进度"}:${a.current_line}/${a.total_lines}`),a.current_country&&l.push(`国家:${a.current_country}`),a.current_asin&&l.push(`ASIN:${a.current_asin}`),a.finished_files!=null){const i=a.file_total&&a.file_total>0?`/${a.file_total}`:"";l.push(`已完成文件:${a.finished_files}${i}`)}return l.join("|")}function Q(e){const s=e.taskId;if(!s)return 0;const t=g.value[s]?.line_progress?.info;if(N(s)){const l=E(s,e);if(g.value[s]?.task?.status==="SUCCESS"||l?._completed)return 100;const d=Math.max(0,e.totalRows??se(e)?.totalRows??0);if(!!(t?.file_name&&t.file_name===e.sourceFilename)){if(t?.current_line!=null&&t?.total_lines&&t.total_lines>0)return Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100)));if(t?.current_line!=null&&d>0)return Math.max(0,Math.min(100,Math.round(t.current_line/d*100)))}return 0}const n=se(e);return n?Math.max(0,Math.min(100,n.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function ge(e){const s=g.value[e]?.task?.status;return s==="SUCCESS"||s==="FAILED"}function U(){const e=new Set;return v.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function x(e){const s=e.taskId;if(!s||!ee(s))return"";const a=E(s,e),n=fe(s),o=g.value[s]?.line_progress,l=N(s);if(!l&&(n==="SUCCESS"||n==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(a?._completed)return"本文件解析完毕";if(n==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(l&&!a?._pushed&&!a?._completed)return"未入队";if(l&&n==="SUCCESS")return"本文件解析完毕";if(!l){const i=g.value[s];if(i?.items&&i.items.find(_=>D(_,e))&&n==="SUCCESS")return"本文件解析完毕"}return a?._pushed?"已入队":"未入队"}function ye(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?g.value[s]?.task?.status==="SUCCESS":!1}function Pe(e){const s=e?.task?.id;if(!s)return!1;const t=v.value.find(l=>l.taskId===s);if(!t)return!1;const a=e?.items||[];let n=!1;const o=t.items.map(l=>{const i=a.find(le=>D(le,l));if(!i)return l;const d=Array.isArray(i.countries)?i.countries:void 0,_=Array.isArray(l.countries)?l.countries:void 0,k=d&&d.length>0?d:_&&_.length>0?_:d??_,y=Array.isArray(i.previewRows)?i.previewRows:void 0,w=Array.isArray(l.previewRows)?l.previewRows:void 0,I=y&&y.length>0?y:w&&w.length>0?w:y??w,b={...l,...i,countries:k,previewRows:I,_pushed:l._pushed,_completed:l._completed};return JSON.stringify(b)!==JSON.stringify(l)&&(n=!0),b});for(const l of a)o.some(i=>D(i,l))||(o.push({...l,_pushed:!1,_completed:!1}),n=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,n=!0),n&&ce(),n}async function te(e){const s=e||U();if(s.length)try{const t=await ze(s);let a=!1;for(const n of t.items||[]){const o=n?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=n,Pe(n)&&(a=!0),de(o)&&(a=!0))}a&&R()}catch{}}function Ae(){return document.visibilityState==="visible"?4500:1e4}function ae(e=!1){if(S.value){if(!e)return;clearTimeout(S.value),S.value=null}const s=async()=>{if(S.value=null,Y.value){ae();return}const t=U();if(!t.length)return;Y.value=!0;let a=!1,n=!1;try{await te(t),await qe();for(const o of t)ge(o)&&(ue(o),a=!0,n=!0)}finally{Y.value=!1}n?await q():a&&R(),U().length>0&&ae()};e?s():S.value=window.setTimeout(s,Ae())}function ne(e=!1){S.value&&!e||ae(e)}function X(e){const s=e.taskId?g.value[e.taskId]?.task?.status:null;return s==="SUCCESS"?{className:"success",text:"已完成"}:s==="FAILED"?{className:"failed",text:"失败"}:s==="RUNNING"?{className:"running",text:"执行中"}:e.taskStatus==="SUCCESS"?{className:"success",text:"已完成"}:e.taskStatus==="FAILED"?{className:"failed",text:"失败"}:e.taskStatus==="RUNNING"?{className:"running",text:"执行中"}:e.success?{className:"success",text:"已完成"}:{className:"failed",text:"失败"}}function ke(){S.value&&(window.clearTimeout(S.value),S.value=null)}async function me(e){const s=O();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of e){const n=typeof a=="string"?a:a.absolutePath,o=typeof a=="string"?void 0:a.relativePath,l=await s.upload_file_to_java(n,o);if(!l?.success||!l.data)throw new Error(l?.error||l?.message||`上传失败:${n}`);t.push(l.data)}return t}async function De(){const e=O();if(!e?.select_brand_xlsx_files){h.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;$.value=s,H.value=await me(s),h.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Me(){const e=O();if(!e?.select_brand_folder){h.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await ts(s);if(!t.success||!t.items?.length){h.warning(t.error||"该文件夹下没有 xlsx 文件");return}$.value=t.items.map(a=>a.relativePath||a.absolutePath),H.value=await me(t.items),h.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Be(){if(!H.value.length){h.warning("请先选择待处理文件");return}try{B.value=!0;const e=await Qe({files:H.value.map(n=>({fileKey:n.fileKey,originalFilename:n.originalFilename,relativePath:n.relativePath}))}),s=pe(e.items||[]),t=s.some(n=>n.matchStatus==="MATCHED"),a=s.some(n=>n.matchStatus&&n.matchStatus!=="MATCHED");T.value="解析完成,等待手动点击打开紫鸟进行单任务处理",C.value="",s.length&&s[0].taskId&&ie(s[0].taskId,s,T.value,C.value),R(),a?h.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?h.success("删除品牌解析完成,请手动推送"):h.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await q()}catch(e){h.error(e instanceof Error?e.message:"执行失败")}finally{B.value=!1}}async function we(e){const s=e.taskId;if(!s){h.warning("未找到任务ID");return}const t=O(),a=Xe(s),n=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(a,n);o.success?h.success(`已保存:${o.path||n}`):o.error&&o.error!=="用户取消"&&h.error(o.error);return}}async function q(){try{const e=await We();J.value=pe(e.items||[]),R(),await te(),ne(!0)}catch(e){console.error("loadHistory error:",e)}}function Ie(e){v.value.forEach(t=>{t.items=t.items.filter(a=>a.resultId!==e)});const s=v.value.length;v.value=v.value.filter(t=>t.items.length>0),v.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value)),J.value=J.value.filter(t=>t.resultId!==e),R(),U().length===0&&ke()}async function Se(e){try{await Ye(e),Ie(e),await q(),h.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){Ie(e),h.success("已删除");return}h.error(t)}}function be(e){const s=e.slice(0,5).map(a=>`${a.country}:${a.asin}${a.status?`(${a.status})`:""}`);return e.length-s.length>0?`${s.join("、")} 等 ${e.length} 条`:s.join("、")}function dt(e,s){}function Ce(){for(const e of v.value)for(const s of e.items){const t=x(s);if(t==="已入队"||t==="处理中")return!0}return!1}function L(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Ue(){return F.value.find(e=>!e.openStoreUrl||L(e)===A.value||E(e.taskId,e)?._completed?!1:x(e)==="未入队")}async function Te(e,s){if(s?.auto&&Ce())return e.taskId,e.sourceFilename,!1;const t=O(),a=e.taskId;if(!a)return!1;const n=v.value.find(d=>d.taskId===a);if(!n)return!1;if(!t?.enqueue_json)return h.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),!1;const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:a,items:[e]}};C.value=JSON.stringify(o,null,2);const l=await t.enqueue_json(o);let i="";if(l?.success){i=`已推送文件 ${e.sourceFilename},当前队列长度:${l.queue_size??"-"}`;const d=E(a,e);d&&(d._pushed=!0,d._completed=!1),A.value=L(e),ie(a,n.items,i,C.value),ne(!0)}else i=`推送到 Python 队列失败:${l?.error||"未知错误"}`;return T.value=i,!!l?.success}async function qe(){if(!P.value||j.value){P.value,j.value;return}if(Ce())return;const e=A.value;if(e){const t=F.value.find(a=>L(a)===e);if(t){const a=t.taskId,n=N(a);n&&(de(a),x(t),void 0);const o=x(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(n){const l=E(a,t);if(l&&!l._completed){t.sourceFilename,l._pushed,l._completed;return}}}}const s=Ue();if(!s){A.value="",P.value=!1;return}j.value=!0;try{s.taskId,s.sourceFilename,L(s),await Te(s,{auto:!0})||(s.taskId,s.sourceFilename,P.value=!1)}finally{j.value=!1}}async function Le(e){P.value=!0,await Te(e)||(P.value=!1,A.value="")}return He(()=>{Ee();const e=U();e.length>0?te(e).then(async()=>{let s=!1,t=!1;for(const a of e)ge(a)&&(ue(a),s=!0,t=!0);t?await q():s&&R(),ne(!0)}):R(),q().catch(()=>{})}),Je(()=>{ke()}),(e,s)=>(u(),c("div",as,[Ge(je,{active:"delete-brand"}),r("div",ns,[r("aside",ls,[s[2]||(s[2]=r("div",{class:"section-title"},"选择文件",-1)),r("div",rs,[s[0]||(s[0]=r("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),r("div",{class:"btns"},[r("button",{type:"button",class:"opt-btn",onClick:De},"选择 Excel 文件"),r("button",{type:"button",class:"opt-btn",onClick:Me},"选择文件夹")]),r("div",os,[$.value.length?(u(),c(K,{key:0},[(u(!0),c(K,null,re(Z.value,t=>(u(),c("span",{key:t},f(t),1))),128)),$.value.length>Z.value.length?(u(),c("span",is," 还有 "+f($.value.length-Z.value.length)+" 个文件未展开显示 ",1)):p("",!0)],64)):(u(),c("span",us,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=Ve('
执行说明
',2)),r("div",cs,[r("button",{type:"button",class:"btn-run",disabled:B.value,onClick:Be},f(B.value?"解析中...":"开始解析"),9,ds),r("span",fs,f(B.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),T.value||C.value?(u(),c("div",vs,[s[1]||(s[1]=r("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),T.value?(u(),c("div",ps,f(T.value),1)):p("",!0),C.value?(u(),c("pre",hs,f(C.value),1)):p("",!0)])):p("",!0)]),r("section",_s,[s[12]||(s[12]=r("div",{class:"panel-header"},"删除品牌结果",-1)),r("div",gs,[r("div",ys,[r("div",ks,[s[4]||(s[4]=r("span",{class:"summary-label"},"已处理文件",-1)),r("strong",null,f(G.value.total),1)]),r("div",ms,[s[5]||(s[5]=r("span",{class:"summary-label"},"成功结果",-1)),r("strong",null,f(G.value.successCount),1)]),r("div",ws,[s[6]||(s[6]=r("span",{class:"summary-label"},"失败文件",-1)),r("strong",null,f(G.value.failedCount),1)])]),r("div",Is,[s[11]||(s[11]=r("div",{class:"result-list-header"},[r("span",null,"删除品牌结果列表")],-1)),Re.value?(u(),c(K,{key:1},[F.value.length?(u(),c("div",bs,[s[8]||(s[8]=r("div",{class:"result-subsection-title"},"当前任务",-1)),r("ul",Cs,[(u(!0),c(K,null,re(F.value,t=>(u(),c("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",Ts,[r("span",{class:"id",title:t.sourceFilename},f(t.sourceFilename||"-"),9,Fs),r("div",Ns,"店铺名:"+f(t.shopName||"-"),1),r("div",Es,"匹配结果:"+f(he(t)),1),t.platform?(u(),c("div",Rs,"平台:"+f(t.platform),1)):p("",!0),x(t)?(u(),c("div",xs,"队列状态:"+f(x(t)),1)):p("",!0),t.countryCount!==void 0&&t.matched?(u(),c("div",$s,"国家数:"+f(t.countryCount),1)):p("",!0),t.totalRows!==void 0&&t.matched?(u(),c("div",Ps,"去重后 "+f(t.totalRows)+" 条 ",1)):p("",!0),ve(t)?(u(),c("div",As,[r("div",Ds,[s[7]||(s[7]=r("span",null,"任务进度",-1)),r("span",null,f(Q(t))+"%",1)]),r("div",Ms,[r("div",{class:"delete-brand-progress-bar-fill",style:Fe({width:`${Q(t)}%`})},null,4)]),r("div",Bs,f(_e(t)),1)])):p("",!0),t.previewRows?.length?(u(),c("div",Us,f(be(t.previewRows)),1)):p("",!0),z(t)?(u(),c("div",qs,"错误信息:"+f(z(t)),1)):p("",!0)]),r("div",Ls,[r("span",{class:Ne(["status",X(t).className])},f(X(t).text),3),t.openStoreUrl?(u(),c("button",{key:0,type:"button",class:"download",onClick:a=>Le(t)}," 打开紫鸟 ",8,Ks)):p("",!0),ye(t)?(u(),c("button",{key:1,type:"button",class:"download",onClick:a=>we(t)}," 下载 ",8,Os)):p("",!0),t.resultId?(u(),c("button",{key:2,type:"button",class:"btn-delete",onClick:a=>Se(t.resultId)}," 删除 ",8,Hs)):p("",!0)])]))),128))])])):p("",!0),V.value.length?(u(),c("div",Js,[s[10]||(s[10]=r("div",{class:"result-subsection-title"},"历史记录",-1)),r("ul",Gs,[(u(!0),c(K,null,re(V.value,t=>(u(),c("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",js,[r("span",{class:"id",title:t.sourceFilename},f(t.sourceFilename||"-"),9,Vs),r("div",zs,"店铺名:"+f(t.shopName||"-"),1),r("div",Qs,"匹配结果:"+f(he(t)),1),t.platform?(u(),c("div",Xs,"平台:"+f(t.platform),1)):p("",!0),t.countryCount!==void 0&&t.matched?(u(),c("div",Ws,"国家数:"+f(t.countryCount),1)):p("",!0),t.totalRows!==void 0&&t.matched?(u(),c("div",Ys,"去重后 "+f(t.totalRows)+" 条 ",1)):p("",!0),ve(t)?(u(),c("div",Zs,[r("div",et,[s[9]||(s[9]=r("span",null,"任务进度",-1)),r("span",null,f(Q(t))+"%",1)]),r("div",st,[r("div",{class:"delete-brand-progress-bar-fill",style:Fe({width:`${Q(t)}%`})},null,4)]),r("div",tt,f(_e(t)),1)])):p("",!0),t.previewRows?.length?(u(),c("div",at,f(be(t.previewRows)),1)):p("",!0),z(t)?(u(),c("div",nt,"错误信息:"+f(z(t)),1)):p("",!0)]),r("div",lt,[r("span",{class:Ne(["status",X(t).className])},f(X(t).text),3),ye(t)?(u(),c("button",{key:0,type:"button",class:"download",onClick:a=>we(t)}," 下载 ",8,rt)):p("",!0),t.resultId?(u(),c("button",{key:1,type:"button",class:"btn-delete",onClick:a=>Se(t.resultId)}," 删除 ",8,ot)):p("",!0)])]))),128))])])):p("",!0)],64)):(u(),c("div",Ss," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),ut=Ze(it,[["__scopeId","data-v-468f2aa7"]]);es(ut).use(ss).mount("#app");
+import{d as Oe,o as He,I as Je,a as u,c,b as Ge,B as je,e as r,F as K,r as re,t as f,f as p,J as Ve,K as Fe,n as Ne,g as m,h as W,L as ze,i as O,E as h,M as Qe,N as Xe,O as We,P as Ye,_ as Ze,p as es,q as ss}from"./pywebview-Cq_E2BnJ.js";import{e as ts}from"./brand-DZ5_PGnw.js";const as={class:"page-shell module-page"},ns={class:"main-content"},ls={class:"left-panel"},rs={class:"upload-zone"},os={class:"selected-files clean-placeholder split-selected-files"},is={key:0,class:"more-line"},us={key:1},cs={class:"run-row"},ds=["disabled"],fs={class:"loading-msg"},vs={key:0,class:"queue-debug-card"},ps={key:0,class:"queue-debug-line"},hs={key:1,class:"queue-debug-payload"},_s={class:"right-panel"},gs={class:"task-list-wrap"},ys={class:"clean-result-summary"},ks={class:"summary-card"},ms={class:"summary-card"},ws={class:"summary-card"},Is={class:"result-list-wrap"},Ss={key:0,class:"empty-tasks"},bs={key:0,class:"result-subsection"},Cs={class:"task-list clean-result-list"},Ts={class:"left split-result-main"},Fs=["title"],Ns={class:"files"},Es={class:"files"},Rs={key:0,class:"files"},xs={key:1,class:"files"},$s={key:2,class:"files"},Ps={key:3,class:"time"},As={key:4,class:"delete-brand-progress-block"},Ds={class:"delete-brand-progress-header"},Ms={class:"delete-brand-progress-bar"},Bs={class:"files delete-brand-progress"},Us={key:5,class:"files split-entry-list delete-brand-preview"},qs={key:6,class:"files"},Ls={class:"task-right split-result-actions"},Ks=["onClick"],Os=["onClick"],Hs=["onClick"],Js={key:1,class:"result-subsection"},Gs={class:"task-list clean-result-list"},js={class:"left split-result-main"},Vs=["title"],zs={class:"files"},Qs={class:"files"},Xs={key:0,class:"files"},Ws={key:1,class:"files"},Ys={key:2,class:"time"},Zs={key:3,class:"delete-brand-progress-block"},et={class:"delete-brand-progress-header"},st={class:"delete-brand-progress-bar"},tt={class:"files delete-brand-progress"},at={key:4,class:"files split-entry-list delete-brand-preview"},nt={key:5,class:"files"},lt={class:"task-right split-result-actions"},rt=["onClick"],ot=["onClick"],it=Oe({__name:"BrandDeleteBrandTab",setup(ct){function M(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const $=m([]),H=m([]),B=m(!1),oe=m([]),v=m([]),J=m([]),G=m({total:0,successCount:0,failedCount:0,items:[]}),T=m(""),C=m(""),g=m({}),S=m(null),Y=m(!1),P=m(!1),A=m(""),j=m(!1),Z=W(()=>$.value.slice(0,10)),F=W(()=>{const e=[];return v.value.forEach(s=>{e.push(...s.items)}),e});function Ee(){try{const e=typeof window<"u"?window.localStorage.getItem(M()):null;if(e){if(v.value=JSON.parse(e),v.value.length>0){const s=v.value[v.value.length-1];T.value=s.queuePushResult||"",C.value=s.queuePayloadText||""}}else v.value=[]}catch{v.value=[]}}function ie(e,s,t,a){if(!s?.length)return;const n=v.value.findIndex(d=>d.taskId===e),o=n>=0?v.value[n]:null,l=s.map(d=>{const _=o?.items.find(Ke=>D(Ke,d)),k=Array.isArray(d.countries)?d.countries:void 0,y=Array.isArray(_?.countries)?_?.countries:void 0,w=k&&k.length>0?k:y&&y.length>0?y:k??y,I=Array.isArray(d.previewRows)?d.previewRows:void 0,b=Array.isArray(_?.previewRows)?_?.previewRows:void 0,le=I&&I.length>0?I:b&&b.length>0?b:I??b;return{...d,countries:w,previewRows:le,_pushed:_?._pushed??d._pushed??!1,_completed:_?._completed??d._completed??!1}}),i={taskId:e,items:l,createdAt:o?.createdAt||Date.now(),queuePushResult:t??o?.queuePushResult,queuePayloadText:a??o?.queuePayloadText};n>=0?v.value[n]=i:v.value.push(i),typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}function ue(e){const s=v.value.length;v.value=v.value.filter(t=>t.taskId!==e),v.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}const V=W(()=>J.value.filter(e=>!F.value.some(s=>D(s,e)))),Re=W(()=>F.value.length>0||V.value.length>0);function ce(){typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value))}function N(e){return e?(v.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function ee(e){return e&&v.value.find(s=>s.taskId===e)||null}function D(e,s){return!e||!s?!1:e.resultId!=null&&s.resultId!=null?e.resultId===s.resultId:e.fileKey&&s.fileKey?e.fileKey===s.fileKey:e.sourceFilename===s.sourceFilename}function E(e,s){const t=ee(e);return t&&t.items.find(a=>D(a,s))||null}function de(e){if(!e)return!1;const s=ee(e);if(!s)return!1;let t=!1;const a=g.value[e]?.line_progress?.info,n=N(e);if(a?.file_name&&a.current_line!=null&&a.total_lines!=null&&a.total_lines>0&&a.current_line>=a.total_lines){const o=s.items.find(l=>l.sourceFilename===a.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!n){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const l=s.items[0];l&&!l._completed&&(l._completed=!0,t=!0)}}return t&&ce(),t}function fe(e){return e&&g.value[e]?.task?.status||""}function z(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&g.value[s]?.task?.errorMessage||""}function ve(e){const s=e.taskId;if(!s)return!1;const t=g.value[s]?.line_progress,a=fe(s),n=N(s),o=x(e);if(n){const l=E(s,e),i=L(e)===A.value,d=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return!!(i||d||l?._pushed||(a==="RUNNING"||a==="PENDING"||!a)&&l?._completed)}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function pe(e){return e.map(s=>s.matchStatus==="MATCHED"?{...s,_pushed:!1,_completed:!1}:{...s,matched:!1,openStoreUrl:void 0,error:s.error||void 0,_pushed:!1,_completed:!1})}function he(e){return e.matchStatus==="MATCHED"?`已匹配 ${e.shopId||""}`.trim():e.matchMessage?e.matchMessage:e.matchStatus==="CONFLICT"?"存在多个同名店铺,请人工确认":e.matchStatus==="PENDING"||e.matchStatus==="INDEX_STALE"?"店铺索引暂未就绪":e.matchStatus?e.matchStatus:e.matched?`已匹配 ${e.shopId||""}`.trim():"待匹配"}function xe(){oe.value=[...F.value,...V.value]}function R(){xe(),$e(oe.value)}function $e(e){G.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function se(e){const s=e.taskId;return s&&(g.value[s]?.fileProgress||[]).find(n=>n.fileKey&&e.fileKey?n.fileKey===e.fileKey:n.sourceFilename&&e.sourceFilename?n.sourceFilename===e.sourceFilename:!1)||null}function _e(e){const s=e.taskId;if(!s)return"";const t=g.value[s],a=t?.line_progress?.info,n=se(e);if(N(s)){const i=E(s,e),d=t?.task?.status,_=!!(a?.file_name&&a.file_name===e.sourceFilename);let k=i?._completed?"COMPLETED":(i?._pushed,"PENDING"),y=0,w=Math.max(0,e.totalRows??n?.totalRows??0);d==="SUCCESS"||d==="FAILED"&&i?._completed?(k="COMPLETED",y=w):_?(k="RUNNING",y=Math.max(0,Math.min(w||Number.MAX_SAFE_INTEGER,a?.current_line??0)),!w&&a?.total_lines&&a.total_lines>0&&(w=a.total_lines)):i?._completed?(k="COMPLETED",y=w):i?._pushed&&(k="PENDING",y=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${y}/${w}`),a?.finished_files!=null){const b=a.file_total&&a.file_total>0?`/${a.file_total}`:"";I.push(`已完成文件:${a.finished_files}${b}`)}return a?.phase&&I.push(`阶段:${a.phase}`),I.join("|")}if(n){const i=[],d=n.processedRows??0,_=n.totalRows??0;if(n.status&&i.push(`文件状态:${n.status}`),i.push(`文件进度:${d}/${_}`),a?.finished_files!=null){const k=a.file_total&&a.file_total>0?`/${a.file_total}`:"";i.push(`已完成文件:${a.finished_files}${k}`)}return a?.phase&&i.push(`阶段:${a.phase}`),i.join("|")}if(!t?.line_progress?.has_progress||!a){const i=t?.task?.status;return i?`任务状态:${i}`:""}const l=[];if(a.phase&&l.push(`阶段:${a.phase}`),a.file_index&&a.file_total&&l.push(`文件:${a.file_index}/${a.file_total}`),a.file_name&&l.push(`当前文件:${a.file_name}`),a.current_line!=null&&a.total_lines!=null&&l.push(`${N(s)?"当前文件进度":"进度"}:${a.current_line}/${a.total_lines}`),a.current_country&&l.push(`国家:${a.current_country}`),a.current_asin&&l.push(`ASIN:${a.current_asin}`),a.finished_files!=null){const i=a.file_total&&a.file_total>0?`/${a.file_total}`:"";l.push(`已完成文件:${a.finished_files}${i}`)}return l.join("|")}function Q(e){const s=e.taskId;if(!s)return 0;const t=g.value[s]?.line_progress?.info;if(N(s)){const l=E(s,e);if(g.value[s]?.task?.status==="SUCCESS"||l?._completed)return 100;const d=Math.max(0,e.totalRows??se(e)?.totalRows??0);if(!!(t?.file_name&&t.file_name===e.sourceFilename)){if(t?.current_line!=null&&t?.total_lines&&t.total_lines>0)return Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100)));if(t?.current_line!=null&&d>0)return Math.max(0,Math.min(100,Math.round(t.current_line/d*100)))}return 0}const n=se(e);return n?Math.max(0,Math.min(100,n.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function ge(e){const s=g.value[e]?.task?.status;return s==="SUCCESS"||s==="FAILED"}function U(){const e=new Set;return v.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function x(e){const s=e.taskId;if(!s||!ee(s))return"";const a=E(s,e),n=fe(s),o=g.value[s]?.line_progress,l=N(s);if(!l&&(n==="SUCCESS"||n==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(a?._completed)return"本文件解析完毕";if(n==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(l&&!a?._pushed&&!a?._completed)return"未入队";if(l&&n==="SUCCESS")return"本文件解析完毕";if(!l){const i=g.value[s];if(i?.items&&i.items.find(_=>D(_,e))&&n==="SUCCESS")return"本文件解析完毕"}return a?._pushed?"已入队":"未入队"}function ye(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?g.value[s]?.task?.status==="SUCCESS":!1}function Pe(e){const s=e?.task?.id;if(!s)return!1;const t=v.value.find(l=>l.taskId===s);if(!t)return!1;const a=e?.items||[];let n=!1;const o=t.items.map(l=>{const i=a.find(le=>D(le,l));if(!i)return l;const d=Array.isArray(i.countries)?i.countries:void 0,_=Array.isArray(l.countries)?l.countries:void 0,k=d&&d.length>0?d:_&&_.length>0?_:d??_,y=Array.isArray(i.previewRows)?i.previewRows:void 0,w=Array.isArray(l.previewRows)?l.previewRows:void 0,I=y&&y.length>0?y:w&&w.length>0?w:y??w,b={...l,...i,countries:k,previewRows:I,_pushed:l._pushed,_completed:l._completed};return JSON.stringify(b)!==JSON.stringify(l)&&(n=!0),b});for(const l of a)o.some(i=>D(i,l))||(o.push({...l,_pushed:!1,_completed:!1}),n=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,n=!0),n&&ce(),n}async function te(e){const s=e||U();if(s.length)try{const t=await ze(s);let a=!1;for(const n of t.items||[]){const o=n?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=n,Pe(n)&&(a=!0),de(o)&&(a=!0))}a&&R()}catch{}}function Ae(){return document.visibilityState==="visible"?4500:1e4}function ae(e=!1){if(S.value){if(!e)return;clearTimeout(S.value),S.value=null}const s=async()=>{if(S.value=null,Y.value){ae();return}const t=U();if(!t.length)return;Y.value=!0;let a=!1,n=!1;try{await te(t),await qe();for(const o of t)ge(o)&&(ue(o),a=!0,n=!0)}finally{Y.value=!1}n?await q():a&&R(),U().length>0&&ae()};e?s():S.value=window.setTimeout(s,Ae())}function ne(e=!1){S.value&&!e||ae(e)}function X(e){const s=e.taskId?g.value[e.taskId]?.task?.status:null;return s==="SUCCESS"?{className:"success",text:"已完成"}:s==="FAILED"?{className:"failed",text:"失败"}:s==="RUNNING"?{className:"running",text:"执行中"}:e.taskStatus==="SUCCESS"?{className:"success",text:"已完成"}:e.taskStatus==="FAILED"?{className:"failed",text:"失败"}:e.taskStatus==="RUNNING"?{className:"running",text:"执行中"}:e.success?{className:"success",text:"已完成"}:{className:"failed",text:"失败"}}function ke(){S.value&&(window.clearTimeout(S.value),S.value=null)}async function me(e){const s=O();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of e){const n=typeof a=="string"?a:a.absolutePath,o=typeof a=="string"?void 0:a.relativePath,l=await s.upload_file_to_java(n,o);if(!l?.success||!l.data)throw new Error(l?.error||l?.message||`上传失败:${n}`);t.push(l.data)}return t}async function De(){const e=O();if(!e?.select_brand_xlsx_files){h.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;$.value=s,H.value=await me(s),h.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Me(){const e=O();if(!e?.select_brand_folder){h.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await ts(s);if(!t.success||!t.items?.length){h.warning(t.error||"该文件夹下没有 xlsx 文件");return}$.value=t.items.map(a=>a.relativePath||a.absolutePath),H.value=await me(t.items),h.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Be(){if(!H.value.length){h.warning("请先选择待处理文件");return}try{B.value=!0;const e=await Qe({files:H.value.map(n=>({fileKey:n.fileKey,originalFilename:n.originalFilename,relativePath:n.relativePath}))}),s=pe(e.items||[]),t=s.some(n=>n.matchStatus==="MATCHED"),a=s.some(n=>n.matchStatus&&n.matchStatus!=="MATCHED");T.value="解析完成,等待手动点击打开紫鸟进行单任务处理",C.value="",s.length&&s[0].taskId&&ie(s[0].taskId,s,T.value,C.value),R(),a?h.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?h.success("删除品牌解析完成,请手动推送"):h.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await q()}catch(e){h.error(e instanceof Error?e.message:"执行失败")}finally{B.value=!1}}async function we(e){const s=e.taskId;if(!s){h.warning("未找到任务ID");return}const t=O(),a=Xe(s),n=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(a,n);o.success?h.success(`已保存:${o.path||n}`):o.error&&o.error!=="用户取消"&&h.error(o.error);return}}async function q(){try{const e=await We();J.value=pe(e.items||[]),R(),await te(),ne(!0)}catch(e){console.error("loadHistory error:",e)}}function Ie(e){v.value.forEach(t=>{t.items=t.items.filter(a=>a.resultId!==e)});const s=v.value.length;v.value=v.value.filter(t=>t.items.length>0),v.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(M(),JSON.stringify(v.value)),J.value=J.value.filter(t=>t.resultId!==e),R(),U().length===0&&ke()}async function Se(e){try{await Ye(e),Ie(e),await q(),h.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){Ie(e),h.success("已删除");return}h.error(t)}}function be(e){const s=e.slice(0,5).map(a=>`${a.country}:${a.asin}${a.status?`(${a.status})`:""}`);return e.length-s.length>0?`${s.join("、")} 等 ${e.length} 条`:s.join("、")}function dt(e,s){}function Ce(){for(const e of v.value)for(const s of e.items){const t=x(s);if(t==="已入队"||t==="处理中")return!0}return!1}function L(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Ue(){return F.value.find(e=>!e.openStoreUrl||L(e)===A.value||E(e.taskId,e)?._completed?!1:x(e)==="未入队")}async function Te(e,s){if(s?.auto&&Ce())return e.taskId,e.sourceFilename,!1;const t=O(),a=e.taskId;if(!a)return!1;const n=v.value.find(d=>d.taskId===a);if(!n)return!1;if(!t?.enqueue_json)return h.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),!1;const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:a,items:[e]}};C.value=JSON.stringify(o,null,2);const l=await t.enqueue_json(o);let i="";if(l?.success){i=`已推送文件 ${e.sourceFilename},当前队列长度:${l.queue_size??"-"}`;const d=E(a,e);d&&(d._pushed=!0,d._completed=!1),A.value=L(e),ie(a,n.items,i,C.value),ne(!0)}else i=`推送到 Python 队列失败:${l?.error||"未知错误"}`;return T.value=i,!!l?.success}async function qe(){if(!P.value||j.value){P.value,j.value;return}if(Ce())return;const e=A.value;if(e){const t=F.value.find(a=>L(a)===e);if(t){const a=t.taskId,n=N(a);n&&(de(a),x(t),void 0);const o=x(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(n){const l=E(a,t);if(l&&!l._completed){t.sourceFilename,l._pushed,l._completed;return}}}}const s=Ue();if(!s){A.value="",P.value=!1;return}j.value=!0;try{s.taskId,s.sourceFilename,L(s),await Te(s,{auto:!0})||(s.taskId,s.sourceFilename,P.value=!1)}finally{j.value=!1}}async function Le(e){P.value=!0,await Te(e)||(P.value=!1,A.value="")}return He(()=>{Ee();const e=U();e.length>0?te(e).then(async()=>{let s=!1,t=!1;for(const a of e)ge(a)&&(ue(a),s=!0,t=!0);t?await q():s&&R(),ne(!0)}):R(),q().catch(()=>{})}),Je(()=>{ke()}),(e,s)=>(u(),c("div",as,[Ge(je,{active:"delete-brand"}),r("div",ns,[r("aside",ls,[s[2]||(s[2]=r("div",{class:"section-title"},"选择文件",-1)),r("div",rs,[s[0]||(s[0]=r("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),r("div",{class:"btns"},[r("button",{type:"button",class:"opt-btn",onClick:De},"选择 Excel 文件"),r("button",{type:"button",class:"opt-btn",onClick:Me},"选择文件夹")]),r("div",os,[$.value.length?(u(),c(K,{key:0},[(u(!0),c(K,null,re(Z.value,t=>(u(),c("span",{key:t},f(t),1))),128)),$.value.length>Z.value.length?(u(),c("span",is," 还有 "+f($.value.length-Z.value.length)+" 个文件未展开显示 ",1)):p("",!0)],64)):(u(),c("span",us,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=Ve('执行说明
',2)),r("div",cs,[r("button",{type:"button",class:"btn-run",disabled:B.value,onClick:Be},f(B.value?"解析中...":"开始解析"),9,ds),r("span",fs,f(B.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),T.value||C.value?(u(),c("div",vs,[s[1]||(s[1]=r("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),T.value?(u(),c("div",ps,f(T.value),1)):p("",!0),C.value?(u(),c("pre",hs,f(C.value),1)):p("",!0)])):p("",!0)]),r("section",_s,[s[12]||(s[12]=r("div",{class:"panel-header"},"删除品牌结果",-1)),r("div",gs,[r("div",ys,[r("div",ks,[s[4]||(s[4]=r("span",{class:"summary-label"},"已处理文件",-1)),r("strong",null,f(G.value.total),1)]),r("div",ms,[s[5]||(s[5]=r("span",{class:"summary-label"},"成功结果",-1)),r("strong",null,f(G.value.successCount),1)]),r("div",ws,[s[6]||(s[6]=r("span",{class:"summary-label"},"失败文件",-1)),r("strong",null,f(G.value.failedCount),1)])]),r("div",Is,[s[11]||(s[11]=r("div",{class:"result-list-header"},[r("span",null,"删除品牌结果列表")],-1)),Re.value?(u(),c(K,{key:1},[F.value.length?(u(),c("div",bs,[s[8]||(s[8]=r("div",{class:"result-subsection-title"},"当前任务",-1)),r("ul",Cs,[(u(!0),c(K,null,re(F.value,t=>(u(),c("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",Ts,[r("span",{class:"id",title:t.sourceFilename},f(t.sourceFilename||"-"),9,Fs),r("div",Ns,"店铺名:"+f(t.shopName||"-"),1),r("div",Es,"匹配结果:"+f(he(t)),1),t.platform?(u(),c("div",Rs,"平台:"+f(t.platform),1)):p("",!0),x(t)?(u(),c("div",xs,"队列状态:"+f(x(t)),1)):p("",!0),t.countryCount!==void 0&&t.matched?(u(),c("div",$s,"国家数:"+f(t.countryCount),1)):p("",!0),t.totalRows!==void 0&&t.matched?(u(),c("div",Ps,"去重后 "+f(t.totalRows)+" 条 ",1)):p("",!0),ve(t)?(u(),c("div",As,[r("div",Ds,[s[7]||(s[7]=r("span",null,"任务进度",-1)),r("span",null,f(Q(t))+"%",1)]),r("div",Ms,[r("div",{class:"delete-brand-progress-bar-fill",style:Fe({width:`${Q(t)}%`})},null,4)]),r("div",Bs,f(_e(t)),1)])):p("",!0),t.previewRows?.length?(u(),c("div",Us,f(be(t.previewRows)),1)):p("",!0),z(t)?(u(),c("div",qs,"错误信息:"+f(z(t)),1)):p("",!0)]),r("div",Ls,[r("span",{class:Ne(["status",X(t).className])},f(X(t).text),3),t.openStoreUrl?(u(),c("button",{key:0,type:"button",class:"download",onClick:a=>Le(t)}," 打开紫鸟 ",8,Ks)):p("",!0),ye(t)?(u(),c("button",{key:1,type:"button",class:"download",onClick:a=>we(t)}," 下载 ",8,Os)):p("",!0),t.resultId?(u(),c("button",{key:2,type:"button",class:"btn-delete",onClick:a=>Se(t.resultId)}," 删除 ",8,Hs)):p("",!0)])]))),128))])])):p("",!0),V.value.length?(u(),c("div",Js,[s[10]||(s[10]=r("div",{class:"result-subsection-title"},"历史记录",-1)),r("ul",Gs,[(u(!0),c(K,null,re(V.value,t=>(u(),c("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",js,[r("span",{class:"id",title:t.sourceFilename},f(t.sourceFilename||"-"),9,Vs),r("div",zs,"店铺名:"+f(t.shopName||"-"),1),r("div",Qs,"匹配结果:"+f(he(t)),1),t.platform?(u(),c("div",Xs,"平台:"+f(t.platform),1)):p("",!0),t.countryCount!==void 0&&t.matched?(u(),c("div",Ws,"国家数:"+f(t.countryCount),1)):p("",!0),t.totalRows!==void 0&&t.matched?(u(),c("div",Ys,"去重后 "+f(t.totalRows)+" 条 ",1)):p("",!0),ve(t)?(u(),c("div",Zs,[r("div",et,[s[9]||(s[9]=r("span",null,"任务进度",-1)),r("span",null,f(Q(t))+"%",1)]),r("div",st,[r("div",{class:"delete-brand-progress-bar-fill",style:Fe({width:`${Q(t)}%`})},null,4)]),r("div",tt,f(_e(t)),1)])):p("",!0),t.previewRows?.length?(u(),c("div",at,f(be(t.previewRows)),1)):p("",!0),z(t)?(u(),c("div",nt,"错误信息:"+f(z(t)),1)):p("",!0)]),r("div",lt,[r("span",{class:Ne(["status",X(t).className])},f(X(t).text),3),ye(t)?(u(),c("button",{key:0,type:"button",class:"download",onClick:a=>we(t)}," 下载 ",8,rt)):p("",!0),t.resultId?(u(),c("button",{key:1,type:"button",class:"btn-delete",onClick:a=>Se(t.resultId)}," 删除 ",8,ot)):p("",!0)])]))),128))])])):p("",!0)],64)):(u(),c("div",Ss," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),ut=Ze(it,[["__scopeId","data-v-468f2aa7"]]);es(ut).use(ss).mount("#app");
diff --git a/app/assets/split.js b/app/assets/split.js
index 6755b9c82..97d282c11 100644
--- a/app/assets/split.js
+++ b/app/assets/split.js
@@ -1 +1 @@
-import{d as G,o as J,a,c as n,b as L,B as O,e,F as S,r as $,t as i,f as v,n as x,w as k,s as V,C as M,g as c,h as Q,i as F,E as r,D as W,G as X,m as Y,v as Z,H as ss,_ as es,p as ts,q as ls}from"./pywebview-V_UIajJm.js";import{e as as}from"./brand-1nUVsWrm.js";const ns={class:"page-shell module-page"},os={class:"main-content"},is={class:"left-panel"},rs={class:"upload-zone"},us={class:"selected-files clean-placeholder split-selected-files"},cs={key:0,class:"more-line"},ds={key:1},ps={class:"option-group column-option-group"},vs={class:"column-toolbar"},fs={class:"column-count"},_s={class:"column-actions"},ms={key:0,class:"column-grid"},ys=["value"],gs={key:1,class:"empty-column-state"},hs={class:"option-group"},bs={class:"radio-item active"},ws={class:"desc"},ks={class:"option-group"},Cs={class:"option-group"},Ss={key:0,class:"split-input-card"},xs={key:1,class:"split-input-card"},Fs={class:"run-row"},Es=["disabled"],Ps={class:"loading-msg"},$s={class:"right-panel"},Bs={class:"task-list-wrap"},Rs={class:"clean-result-summary"},Is={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},Ds={key:1,class:"task-list clean-result-list"},Hs={class:"left split-result-main"},Ns=["title"],js={key:0,class:"files"},As={key:1,class:"time"},Ks={key:2,class:"files"},zs={key:3,class:"files split-entry-list"},qs={key:4,class:"files"},Gs={class:"task-right split-result-actions"},Js=["onClick"],Ls=["onClick"],Os=G({__name:"BrandSplitTab",setup(Ws){const f=c([]),C=c(""),d=c([]),_=c([]),p=c([]),B=c(0),u=c("rows_per_file"),m=c(2e3),y=c(5),g=c(!1),h=c([]),b=c({total:0,successCount:0,failedCount:0,items:[]}),E=Q(()=>f.value.slice(0,8));function T(l){b.value={total:l.length,successCount:l.filter(s=>s.success).length,failedCount:l.filter(s=>!s.success).length,items:l}}async function R(l){const s=F();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const o of l){const U=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(U,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${U}`);t.push(w.data)}return t}async function I(l){const s=await Y(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function D(l,s){f.value=l,C.value="",d.value=await R(l),d.value.length>0&&await I(d.value[0].fileKey),r.success(s)}async function H(){const l=F();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await l.select_brand_xlsx_files();if(!s?.length)return;await D(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function N(){const l=F();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await l.select_brand_folder();if(!s)return;C.value=s.split(/[/\\]/).filter(Boolean).pop()||"";const t=await as(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),d.value=await R(t.items),d.value.length>0&&await I(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function j(){if(!d.value.length){r.warning("请先选择待拆分 Excel 文件或文件夹");return}if(!p.value.length){r.warning("请至少选择一列保留列");return}if(u.value==="rows_per_file"&&(!m.value||m.value<=0)){r.warning("请输入有效的每份条数");return}if(u.value==="parts"&&(!y.value||y.value<=0)){r.warning("请输入有效的拆分份数");return}try{g.value=!0;const l=await W({files:d.value.map(s=>({fileKey:s.fileKey,originalFilename:s.originalFilename,relativePath:s.relativePath})),selectedColumns:p.value,splitMode:u.value,rowsPerFile:u.value==="rows_per_file"&&m.value||void 0,parts:u.value==="parts"&&y.value||void 0,archiveName:d.value.some(s=>!!s.relativePath)&&C.value?C.value:void 0});b.value=l,h.value=l.items||[],await P(),r.success("数据拆分完成")}catch(l){r.error(l instanceof Error?l.message:"数据拆分失败")}finally{g.value=!1}}async function P(){try{const l=await X();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await ss(l),await P(),r.success("已删除")}catch(s){r.error(s instanceof Error?s.message:"删除失败")}}function K(l){const s=l.slice(0,4).map(o=>o.rowCount!==void 0?`${o.filename}(${o.rowCount}条)`:o.filename);return l.length-s.length>0?`${s.join("、")} 等 ${l.length} 个文件`:s.join("、")}async function z(l){const s=F();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.zip`;if(s?.save_file_from_url_new){const o=await s.save_file_from_url_new(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}}return J(()=>{P().catch(()=>{})}),(l,s)=>(a(),n("div",ns,[L(O,{active:"split"}),e("div",os,[e("aside",is,[s[14]||(s[14]=e("div",{class:"section-title"},"选择文件",-1)),e("div",rs,[s[7]||(s[7]=e("div",{class:"hint"},"选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。",-1)),e("div",{class:"btns"},[e("button",{type:"button",class:"opt-btn",onClick:H},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:N},"选择文件夹")]),e("div",us,[f.value.length?(a(),n(S,{key:0},[(a(!0),n(S,null,$(E.value,t=>(a(),n("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(a(),n("span",cs," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",ds,"暂未选择待拆分文件"))])]),s[15]||(s[15]=e("div",{class:"section-title"},"保留列设置",-1)),e("div",ps,[e("div",vs,[e("span",fs,"已选择 "+i(p.value.length)+" / "+i(_.value.length)+" 列",1),e("div",_s,[e("button",{type:"button",class:"opt-btn small",onClick:s[0]||(s[0]=t=>p.value=[..._.value])},"全选"),e("button",{type:"button",class:"opt-btn small",onClick:s[1]||(s[1]=t=>p.value=[])},"清空")])]),_.value.length?(a(),n("div",ms,[(a(!0),n(S,null,$(_.value,t=>(a(),n("label",{key:t,class:x(["column-item",{active:p.value.includes(t)}])},[k(e("input",{"onUpdate:modelValue":s[2]||(s[2]=o=>p.value=o),type:"checkbox",value:t},null,8,ys),[[Z,p.value]]),e("span",null,i(t),1)],2))),128))])):(a(),n("div",gs,"请选择 Excel 文件后读取表头并填充可保留列"))]),s[16]||(s[16]=e("div",{class:"section-title"},"总条数",-1)),e("div",hs,[e("label",bs,[s[9]||(s[9]=e("input",{type:"checkbox",checked:"",disabled:""},null,-1)),e("div",null,[s[8]||(s[8]=e("span",{class:"label"},"当前数据总条数",-1)),e("div",ws,i(B.value)+" 条(不含表头)",1)])])]),s[17]||(s[17]=e("div",{class:"section-title"},"拆分模式",-1)),e("div",ks,[e("label",{class:x(["radio-item",{active:u.value==="rows_per_file"}])},[k(e("input",{"onUpdate:modelValue":s[3]||(s[3]=t=>u.value=t),type:"radio",value:"rows_per_file",name:"split-mode"},null,512),[[V,u.value]]),s[10]||(s[10]=e("div",null,[e("span",{class:"label"},"按每份条数"),e("div",{class:"desc"},"例如每份 2000 条,最后一份放剩余数据")],-1))],2),e("label",{class:x(["radio-item",{active:u.value==="parts"}])},[k(e("input",{"onUpdate:modelValue":s[4]||(s[4]=t=>u.value=t),type:"radio",value:"parts",name:"split-mode"},null,512),[[V,u.value]]),s[11]||(s[11]=e("div",null,[e("span",{class:"label"},"按份数平均拆分"),e("div",{class:"desc"},"例如拆 5 份,按总条数尽量平均分配")],-1))],2)]),s[18]||(s[18]=e("div",{class:"section-title"},"拆分参数",-1)),e("div",Cs,[u.value==="rows_per_file"?(a(),n("label",Ss,[s[12]||(s[12]=e("span",{class:"label"},"每份条数",-1)),k(e("input",{"onUpdate:modelValue":s[5]||(s[5]=t=>m.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 2000"},null,512),[[M,m.value,void 0,{number:!0}]])])):(a(),n("label",xs,[s[13]||(s[13]=e("span",{class:"label"},"拆分份数",-1)),k(e("input",{"onUpdate:modelValue":s[6]||(s[6]=t=>y.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 5"},null,512),[[M,y.value,void 0,{number:!0}]])]))]),e("div",Fs,[e("button",{type:"button",class:"btn-run",disabled:g.value,onClick:j},i(g.value?"拆分中...":"开始拆分"),9,Es),e("span",Ps,i(g.value?"正在拆分并上传结果,请稍候…":"选择文件、保留列和拆分规则后即可执行拆分,结果会显示在右侧供下载"),1)])]),e("section",$s,[s[23]||(s[23]=e("div",{class:"panel-header"},"拆分结果",-1)),e("div",Bs,[e("div",Rs,[e("div",Is,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Us,[s[20]||(s[20]=e("span",{class:"summary-label"},"成功结果",-1)),e("strong",null,i(b.value.successCount),1)]),e("div",Vs,[s[21]||(s[21]=e("span",{class:"summary-label"},"失败文件",-1)),e("strong",null,i(b.value.failedCount),1)])]),e("div",Ms,[s[22]||(s[22]=e("div",{class:"result-list-header"},[e("span",null,"拆分结果压缩包列表")],-1)),h.value.length===0?(a(),n("div",Ts," 暂无拆分结果,完成数据拆分后会在这里展示压缩包文件 ")):(a(),n("ul",Ds,[(a(!0),n(S,null,$(h.value,t=>(a(),n("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}-${t.rowCount||0}`,class:"task-item split-result-item"},[e("div",Hs,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Ns),t.outputFilename?(a(),n("div",js,"压缩包文件:"+i(t.outputFilename),1)):v("",!0),t.rowCount!==void 0?(a(),n("div",As,"压缩包共包含 "+i(t.rowCount)+" 条数据",1)):v("",!0),t.entryCount&&t.entryCount>0?(a(),n("div",Ks,"压缩包内共 "+i(t.entryCount)+" 个拆分文件 ",1)):v("",!0),t.entries&&t.entries.length?(a(),n("div",zs," 压缩包内容:"+i(K(t.entries)),1)):v("",!0),t.error?(a(),n("div",qs,"错误信息:"+i(t.error),1)):v("",!0)]),e("div",Gs,[e("span",{class:x(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(a(),n("button",{key:0,type:"button",class:"download",onClick:o=>z(t)}," 下载压缩包 ",8,Js)):v("",!0),t.resultId?(a(),n("button",{key:1,type:"button",class:"btn-delete",onClick:o=>A(t.resultId)}," 删除 ",8,Ls)):v("",!0)])]))),128))]))])])])])]))}}),Qs=es(Os,[["__scopeId","data-v-c5a98d6b"]]);ts(Qs).use(ls).mount("#app");
+import{d as G,o as J,a,c as n,b as L,B as O,e,F as S,r as $,t as i,f as v,n as x,w as k,s as V,C as M,g as c,h as Q,i as F,E as r,D as W,G as X,m as Y,v as Z,H as ss,_ as es,p as ts,q as ls}from"./pywebview-Cq_E2BnJ.js";import{e as as}from"./brand-DZ5_PGnw.js";const ns={class:"page-shell module-page"},os={class:"main-content"},is={class:"left-panel"},rs={class:"upload-zone"},us={class:"selected-files clean-placeholder split-selected-files"},cs={key:0,class:"more-line"},ds={key:1},ps={class:"option-group column-option-group"},vs={class:"column-toolbar"},fs={class:"column-count"},_s={class:"column-actions"},ms={key:0,class:"column-grid"},ys=["value"],gs={key:1,class:"empty-column-state"},hs={class:"option-group"},bs={class:"radio-item active"},ws={class:"desc"},ks={class:"option-group"},Cs={class:"option-group"},Ss={key:0,class:"split-input-card"},xs={key:1,class:"split-input-card"},Fs={class:"run-row"},Es=["disabled"],Ps={class:"loading-msg"},$s={class:"right-panel"},Bs={class:"task-list-wrap"},Rs={class:"clean-result-summary"},Is={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},Ds={key:1,class:"task-list clean-result-list"},Hs={class:"left split-result-main"},Ns=["title"],js={key:0,class:"files"},As={key:1,class:"time"},Ks={key:2,class:"files"},zs={key:3,class:"files split-entry-list"},qs={key:4,class:"files"},Gs={class:"task-right split-result-actions"},Js=["onClick"],Ls=["onClick"],Os=G({__name:"BrandSplitTab",setup(Ws){const f=c([]),C=c(""),d=c([]),_=c([]),p=c([]),B=c(0),u=c("rows_per_file"),m=c(2e3),y=c(5),g=c(!1),h=c([]),b=c({total:0,successCount:0,failedCount:0,items:[]}),E=Q(()=>f.value.slice(0,8));function T(l){b.value={total:l.length,successCount:l.filter(s=>s.success).length,failedCount:l.filter(s=>!s.success).length,items:l}}async function R(l){const s=F();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const o of l){const U=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(U,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${U}`);t.push(w.data)}return t}async function I(l){const s=await Y(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function D(l,s){f.value=l,C.value="",d.value=await R(l),d.value.length>0&&await I(d.value[0].fileKey),r.success(s)}async function H(){const l=F();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await l.select_brand_xlsx_files();if(!s?.length)return;await D(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function N(){const l=F();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await l.select_brand_folder();if(!s)return;C.value=s.split(/[/\\]/).filter(Boolean).pop()||"";const t=await as(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),d.value=await R(t.items),d.value.length>0&&await I(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function j(){if(!d.value.length){r.warning("请先选择待拆分 Excel 文件或文件夹");return}if(!p.value.length){r.warning("请至少选择一列保留列");return}if(u.value==="rows_per_file"&&(!m.value||m.value<=0)){r.warning("请输入有效的每份条数");return}if(u.value==="parts"&&(!y.value||y.value<=0)){r.warning("请输入有效的拆分份数");return}try{g.value=!0;const l=await W({files:d.value.map(s=>({fileKey:s.fileKey,originalFilename:s.originalFilename,relativePath:s.relativePath})),selectedColumns:p.value,splitMode:u.value,rowsPerFile:u.value==="rows_per_file"&&m.value||void 0,parts:u.value==="parts"&&y.value||void 0,archiveName:d.value.some(s=>!!s.relativePath)&&C.value?C.value:void 0});b.value=l,h.value=l.items||[],await P(),r.success("数据拆分完成")}catch(l){r.error(l instanceof Error?l.message:"数据拆分失败")}finally{g.value=!1}}async function P(){try{const l=await X();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await ss(l),await P(),r.success("已删除")}catch(s){r.error(s instanceof Error?s.message:"删除失败")}}function K(l){const s=l.slice(0,4).map(o=>o.rowCount!==void 0?`${o.filename}(${o.rowCount}条)`:o.filename);return l.length-s.length>0?`${s.join("、")} 等 ${l.length} 个文件`:s.join("、")}async function z(l){const s=F();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.zip`;if(s?.save_file_from_url_new){const o=await s.save_file_from_url_new(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}}return J(()=>{P().catch(()=>{})}),(l,s)=>(a(),n("div",ns,[L(O,{active:"split"}),e("div",os,[e("aside",is,[s[14]||(s[14]=e("div",{class:"section-title"},"选择文件",-1)),e("div",rs,[s[7]||(s[7]=e("div",{class:"hint"},"选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。",-1)),e("div",{class:"btns"},[e("button",{type:"button",class:"opt-btn",onClick:H},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:N},"选择文件夹")]),e("div",us,[f.value.length?(a(),n(S,{key:0},[(a(!0),n(S,null,$(E.value,t=>(a(),n("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(a(),n("span",cs," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",ds,"暂未选择待拆分文件"))])]),s[15]||(s[15]=e("div",{class:"section-title"},"保留列设置",-1)),e("div",ps,[e("div",vs,[e("span",fs,"已选择 "+i(p.value.length)+" / "+i(_.value.length)+" 列",1),e("div",_s,[e("button",{type:"button",class:"opt-btn small",onClick:s[0]||(s[0]=t=>p.value=[..._.value])},"全选"),e("button",{type:"button",class:"opt-btn small",onClick:s[1]||(s[1]=t=>p.value=[])},"清空")])]),_.value.length?(a(),n("div",ms,[(a(!0),n(S,null,$(_.value,t=>(a(),n("label",{key:t,class:x(["column-item",{active:p.value.includes(t)}])},[k(e("input",{"onUpdate:modelValue":s[2]||(s[2]=o=>p.value=o),type:"checkbox",value:t},null,8,ys),[[Z,p.value]]),e("span",null,i(t),1)],2))),128))])):(a(),n("div",gs,"请选择 Excel 文件后读取表头并填充可保留列"))]),s[16]||(s[16]=e("div",{class:"section-title"},"总条数",-1)),e("div",hs,[e("label",bs,[s[9]||(s[9]=e("input",{type:"checkbox",checked:"",disabled:""},null,-1)),e("div",null,[s[8]||(s[8]=e("span",{class:"label"},"当前数据总条数",-1)),e("div",ws,i(B.value)+" 条(不含表头)",1)])])]),s[17]||(s[17]=e("div",{class:"section-title"},"拆分模式",-1)),e("div",ks,[e("label",{class:x(["radio-item",{active:u.value==="rows_per_file"}])},[k(e("input",{"onUpdate:modelValue":s[3]||(s[3]=t=>u.value=t),type:"radio",value:"rows_per_file",name:"split-mode"},null,512),[[V,u.value]]),s[10]||(s[10]=e("div",null,[e("span",{class:"label"},"按每份条数"),e("div",{class:"desc"},"例如每份 2000 条,最后一份放剩余数据")],-1))],2),e("label",{class:x(["radio-item",{active:u.value==="parts"}])},[k(e("input",{"onUpdate:modelValue":s[4]||(s[4]=t=>u.value=t),type:"radio",value:"parts",name:"split-mode"},null,512),[[V,u.value]]),s[11]||(s[11]=e("div",null,[e("span",{class:"label"},"按份数平均拆分"),e("div",{class:"desc"},"例如拆 5 份,按总条数尽量平均分配")],-1))],2)]),s[18]||(s[18]=e("div",{class:"section-title"},"拆分参数",-1)),e("div",Cs,[u.value==="rows_per_file"?(a(),n("label",Ss,[s[12]||(s[12]=e("span",{class:"label"},"每份条数",-1)),k(e("input",{"onUpdate:modelValue":s[5]||(s[5]=t=>m.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 2000"},null,512),[[M,m.value,void 0,{number:!0}]])])):(a(),n("label",xs,[s[13]||(s[13]=e("span",{class:"label"},"拆分份数",-1)),k(e("input",{"onUpdate:modelValue":s[6]||(s[6]=t=>y.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 5"},null,512),[[M,y.value,void 0,{number:!0}]])]))]),e("div",Fs,[e("button",{type:"button",class:"btn-run",disabled:g.value,onClick:j},i(g.value?"拆分中...":"开始拆分"),9,Es),e("span",Ps,i(g.value?"正在拆分并上传结果,请稍候…":"选择文件、保留列和拆分规则后即可执行拆分,结果会显示在右侧供下载"),1)])]),e("section",$s,[s[23]||(s[23]=e("div",{class:"panel-header"},"拆分结果",-1)),e("div",Bs,[e("div",Rs,[e("div",Is,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Us,[s[20]||(s[20]=e("span",{class:"summary-label"},"成功结果",-1)),e("strong",null,i(b.value.successCount),1)]),e("div",Vs,[s[21]||(s[21]=e("span",{class:"summary-label"},"失败文件",-1)),e("strong",null,i(b.value.failedCount),1)])]),e("div",Ms,[s[22]||(s[22]=e("div",{class:"result-list-header"},[e("span",null,"拆分结果压缩包列表")],-1)),h.value.length===0?(a(),n("div",Ts," 暂无拆分结果,完成数据拆分后会在这里展示压缩包文件 ")):(a(),n("ul",Ds,[(a(!0),n(S,null,$(h.value,t=>(a(),n("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}-${t.rowCount||0}`,class:"task-item split-result-item"},[e("div",Hs,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Ns),t.outputFilename?(a(),n("div",js,"压缩包文件:"+i(t.outputFilename),1)):v("",!0),t.rowCount!==void 0?(a(),n("div",As,"压缩包共包含 "+i(t.rowCount)+" 条数据",1)):v("",!0),t.entryCount&&t.entryCount>0?(a(),n("div",Ks,"压缩包内共 "+i(t.entryCount)+" 个拆分文件 ",1)):v("",!0),t.entries&&t.entries.length?(a(),n("div",zs," 压缩包内容:"+i(K(t.entries)),1)):v("",!0),t.error?(a(),n("div",qs,"错误信息:"+i(t.error),1)):v("",!0)]),e("div",Gs,[e("span",{class:x(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(a(),n("button",{key:0,type:"button",class:"download",onClick:o=>z(t)}," 下载压缩包 ",8,Js)):v("",!0),t.resultId?(a(),n("button",{key:1,type:"button",class:"btn-delete",onClick:o=>A(t.resultId)}," 删除 ",8,Ls)):v("",!0)])]))),128))]))])])])])]))}}),Qs=es(Os,[["__scopeId","data-v-c5a98d6b"]]);ts(Qs).use(ls).mount("#app");
diff --git a/app/blueprints/__pycache__/main.cpython-312.pyc b/app/blueprints/__pycache__/main.cpython-312.pyc
index 81ddaad31..995b8b2b9 100644
Binary files a/app/blueprints/__pycache__/main.cpython-312.pyc and b/app/blueprints/__pycache__/main.cpython-312.pyc differ
diff --git a/app/main.py b/app/main.py
index 7a76502ee..90847a605 100644
--- a/app/main.py
+++ b/app/main.py
@@ -19,6 +19,7 @@ import threading
import time
import requests
import subprocess
+import atexit
from amazon.del_brand import kill_process
@@ -39,6 +40,21 @@ print(f"""
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
APP_URL = "http://127.0.0.1:5123"
PORT = 5123
+_shutdown_started = False
+
+
+def cleanup_before_exit():
+ global _shutdown_started
+ if _shutdown_started:
+ return
+ _shutdown_started = True
+ try:
+ kill_process('v6')
+ except Exception as e:
+ print(f"【退出前】关闭紫鸟浏览器进程异常: {str(e)}")
+
+
+atexit.register(cleanup_before_exit)
def generate_images(params):
@@ -57,6 +73,11 @@ class WindowAPI:
window.events.restored += lambda _: setattr(self, '_is_maximized', False)
def close(self):
+ try:
+ self._window.destroy()
+ except:
+ pass
+ return
try:
kill_process('v6')
except Exception as e:
@@ -369,6 +390,7 @@ def start_task_monitor():
def on_window_closing():
+ return
"""窗口关闭事件处理器,执行与 close() 方法相同的清理逻辑"""
# 先关闭窗口,避免看起来卡着
try:
@@ -419,7 +441,7 @@ def main():
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.open_external_url,api.enqueue_json,api.get_detail_del,api.save_file_from_url_new)
webview.start(
- debug=False,
+ debug=True,
storage_path=cache_path,
private_mode=False
)
diff --git a/app/new_web_source/convert.html b/app/new_web_source/convert.html
index 243e08988..ebf8bf8e2 100644
--- a/app/new_web_source/convert.html
+++ b/app/new_web_source/convert.html
@@ -5,9 +5,9 @@
格式转换 - 数富AI
-
-
-
+
+
+
diff --git a/app/new_web_source/dedupe.html b/app/new_web_source/dedupe.html
index 90cb2c482..14c18c011 100644
--- a/app/new_web_source/dedupe.html
+++ b/app/new_web_source/dedupe.html
@@ -5,9 +5,9 @@
数据去重 - 数富AI
-
-
-
+
+
+
diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html
index 5d907e3f4..5827e0631 100644
--- a/app/new_web_source/delete-brand.html
+++ b/app/new_web_source/delete-brand.html
@@ -5,9 +5,9 @@
删除品牌 - 数富AI
-
-
-
+
+
+
diff --git a/app/new_web_source/split.html b/app/new_web_source/split.html
index ee85e1cf7..79158d2e1 100644
--- a/app/new_web_source/split.html
+++ b/app/new_web_source/split.html
@@ -5,9 +5,9 @@
数据拆分 - 数富AI
-
-
-
+
+
+
diff --git a/backend-java/aiimage-backend.log.2026-04-06.0.gz b/backend-java/aiimage-backend.log.2026-04-06.0.gz
deleted file mode 100644
index 60d55d320..000000000
Binary files a/backend-java/aiimage-backend.log.2026-04-06.0.gz and /dev/null differ
diff --git a/backend-java/aiimage-backend.log.2026-04-07.0.gz b/backend-java/aiimage-backend.log.2026-04-07.0.gz
deleted file mode 100644
index 76f171ac7..000000000
Binary files a/backend-java/aiimage-backend.log.2026-04-07.0.gz and /dev/null differ
diff --git a/backend-java/brand_chunk_load_test.py b/backend-java/brand_chunk_load_test.py
deleted file mode 100644
index da8ccd350..000000000
--- a/backend-java/brand_chunk_load_test.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python3
-import json
-import sys
-import time
-from urllib import request, error
-
-
-def build_chunk(file_url: str, chunk_index: int, chunk_total: int, total_lines: int):
- return {
- "fileUrl": file_url,
- "originalFilename": "demo.xlsx",
- "relativePath": None,
- "mainSheetName": "Sheet1",
- "chunkIndex": chunk_index,
- "chunkTotal": chunk_total,
- "totalLines": total_lines,
- "keptRows": [f"brand-{chunk_index}"],
- "invalidBrands": [],
- "queryFailedBrands": []
- }
-
-
-def post_json(url: str, payload: dict):
- data = json.dumps(payload).encode("utf-8")
- req = request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST")
- with request.urlopen(req, timeout=60) as resp:
- return resp.status, resp.read().decode("utf-8", errors="ignore")
-
-
-def main():
- if len(sys.argv) < 4:
- print("usage: python brand_chunk_load_test.py [file_url]")
- sys.exit(1)
- base_url = sys.argv[1].rstrip("/")
- task_id = int(sys.argv[2])
- chunk_total = int(sys.argv[3])
- file_url = sys.argv[4] if len(sys.argv) > 4 else "https://example.com/demo.xlsx"
-
- submit_url = f"{base_url}/api/brand/tasks/{task_id}/result"
- started = time.time()
- for i in range(1, chunk_total + 1):
- payload = {
- "strategy": "Terms",
- "files": [build_chunk(file_url, i, chunk_total, chunk_total)]
- }
- status, body = post_json(submit_url, payload)
- if i == 1 or i == chunk_total or i % 100 == 0:
- print(f"chunk {i}/{chunk_total} status={status} elapsed={time.time() - started:.2f}s")
- if status < 200 or status >= 300:
- print(body)
- sys.exit(2)
- print(f"done {chunk_total} chunks in {time.time() - started:.2f}s")
-
-
-if __name__ == "__main__":
- main()
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java
index 349374e63..24351495d 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java
@@ -19,4 +19,5 @@ public class DeleteBrandProgressProperties {
* 与删除品牌共用同一定时调度。
*/
private long productRiskStaleTimeoutMinutes = 10;
+ private long productRiskInitialTimeoutMinutes = 10;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/InstanceMetadata.java b/backend-java/src/main/java/com/nanri/aiimage/config/InstanceMetadata.java
new file mode 100644
index 000000000..2ffa0f5eb
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/InstanceMetadata.java
@@ -0,0 +1,37 @@
+package com.nanri.aiimage.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.net.InetAddress;
+
+@Component
+public class InstanceMetadata {
+
+ private final String instanceId;
+ private final String hostname;
+
+ public InstanceMetadata(@Value("${aiimage.instance-id:}") String configuredInstanceId) {
+ this.hostname = resolveHostname();
+ this.instanceId = configuredInstanceId == null || configuredInstanceId.isBlank()
+ ? this.hostname
+ : configuredInstanceId.trim();
+ }
+
+ public String getInstanceId() {
+ return instanceId;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ private static String resolveHostname() {
+ try {
+ return InetAddress.getLocalHost().getHostName();
+ } catch (Exception ignored) {
+ String envHostname = System.getenv("HOSTNAME");
+ return (envHostname == null || envHostname.isBlank()) ? "unknown-host" : envHostname;
+ }
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/RequestTraceFilter.java b/backend-java/src/main/java/com/nanri/aiimage/config/RequestTraceFilter.java
new file mode 100644
index 000000000..05bf06098
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/RequestTraceFilter.java
@@ -0,0 +1,81 @@
+package com.nanri.aiimage.config;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import java.io.IOException;
+import java.util.Optional;
+
+@Component
+public class RequestTraceFilter extends OncePerRequestFilter {
+
+ private static final Logger log = LoggerFactory.getLogger(RequestTraceFilter.class);
+
+ private final InstanceMetadata instanceMetadata;
+
+ public RequestTraceFilter(InstanceMetadata instanceMetadata) {
+ this.instanceMetadata = instanceMetadata;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+ long start = System.currentTimeMillis();
+ String remoteAddr = firstNonBlank(
+ request.getHeader("X-Forwarded-For"),
+ request.getHeader("X-Real-IP"),
+ request.getRemoteAddr()
+ );
+ String forwardedProto = request.getHeader("X-Forwarded-Proto");
+ String forwardedHost = firstNonBlank(request.getHeader("X-Forwarded-Host"), request.getHeader("Host"));
+ String forwardedPort = request.getHeader("X-Forwarded-Port");
+ String requestId = firstNonBlank(
+ request.getHeader("X-Request-Id"),
+ request.getHeader("X-Amzn-Trace-Id"),
+ request.getHeader("Traceparent")
+ );
+
+ response.setHeader("X-AIIMAGE-Instance", instanceMetadata.getInstanceId());
+ response.setHeader("X-AIIMAGE-Host", instanceMetadata.getHostname());
+
+ try {
+ filterChain.doFilter(request, response);
+ } finally {
+ long costMs = System.currentTimeMillis() - start;
+ log.info(
+ "request-trace instance={} host={} method={} uri={} status={} remote={} forwardedHost={} forwardedProto={} forwardedPort={} requestId={} userAgent={} costMs={}",
+ instanceMetadata.getInstanceId(),
+ instanceMetadata.getHostname(),
+ request.getMethod(),
+ request.getRequestURI(),
+ response.getStatus(),
+ remoteAddr,
+ blankToDash(forwardedHost),
+ blankToDash(forwardedProto),
+ blankToDash(forwardedPort),
+ blankToDash(requestId),
+ blankToDash(request.getHeader("User-Agent")),
+ costMs
+ );
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ for (String value : values) {
+ if (value != null && !value.isBlank()) {
+ return value;
+ }
+ }
+ return null;
+ }
+
+ private static String blankToDash(String value) {
+ return Optional.ofNullable(value).filter(v -> !v.isBlank()).orElse("-");
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/debug/controller/DebugRequestInfoController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/debug/controller/DebugRequestInfoController.java
new file mode 100644
index 000000000..ee4dc72f6
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/debug/controller/DebugRequestInfoController.java
@@ -0,0 +1,53 @@
+package com.nanri.aiimage.modules.debug.controller;
+
+import com.nanri.aiimage.config.InstanceMetadata;
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/debug")
+public class DebugRequestInfoController {
+
+ private final InstanceMetadata instanceMetadata;
+
+ public DebugRequestInfoController(InstanceMetadata instanceMetadata) {
+ this.instanceMetadata = instanceMetadata;
+ }
+
+ @GetMapping("/request-info")
+ public Map requestInfo(
+ HttpServletRequest request,
+ @RequestHeader(value = "X-Forwarded-For", required = false) String forwardedFor,
+ @RequestHeader(value = "X-Real-IP", required = false) String realIp,
+ @RequestHeader(value = "X-Forwarded-Proto", required = false) String forwardedProto,
+ @RequestHeader(value = "X-Forwarded-Host", required = false) String forwardedHost,
+ @RequestHeader(value = "X-Forwarded-Port", required = false) String forwardedPort,
+ @RequestHeader(value = "X-Request-Id", required = false) String requestId,
+ @RequestHeader(value = "X-Amzn-Trace-Id", required = false) String amazonTraceId,
+ @RequestHeader(value = "Traceparent", required = false) String traceparent
+ ) {
+ Map result = new LinkedHashMap<>();
+ result.put("instanceId", instanceMetadata.getInstanceId());
+ result.put("hostname", instanceMetadata.getHostname());
+ result.put("serverName", request.getServerName());
+ result.put("serverPort", request.getServerPort());
+ result.put("method", request.getMethod());
+ result.put("uri", request.getRequestURI());
+ result.put("remoteAddr", request.getRemoteAddr());
+ result.put("xForwardedFor", forwardedFor);
+ result.put("xRealIp", realIp);
+ result.put("xForwardedProto", forwardedProto);
+ result.put("xForwardedHost", forwardedHost);
+ result.put("xForwardedPort", forwardedPort);
+ result.put("xRequestId", requestId);
+ result.put("xAmznTraceId", amazonTraceId);
+ result.put("traceparent", traceparent);
+ return result;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java
index c9fa8e8c8..4e4ebf016 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.deletebrand.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.config.DeleteBrandProgressProperties;
+import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskCacheService;
import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
@@ -31,6 +32,7 @@ public class DeleteBrandStaleTaskService {
private final DeleteBrandTaskCacheService deleteBrandTaskCacheService;
private final DeleteBrandRunService deleteBrandRunService;
private final ProductRiskTaskService productRiskTaskService;
+ private final ProductRiskTaskCacheService productRiskTaskCacheService;
private final DeleteBrandProgressProperties deleteBrandProgressProperties;
@Scheduled(cron = "${aiimage.delete-brand-progress.stale-check-cron:0 */2 * * * *}")
@@ -115,7 +117,10 @@ public class DeleteBrandStaleTaskService {
private ProductRiskStaleCheckStats failStaleProductRiskResolveTasks() {
ProductRiskStaleCheckStats stats = new ProductRiskStaleCheckStats();
long minutes = Math.max(1L, deleteBrandProgressProperties.getProductRiskStaleTimeoutMinutes());
- LocalDateTime threshold = LocalDateTime.now().minusMinutes(minutes);
+ long initialMinutes = Math.max(minutes, deleteBrandProgressProperties.getProductRiskInitialTimeoutMinutes());
+ LocalDateTime now = LocalDateTime.now();
+ LocalDateTime threshold = now.minusMinutes(minutes);
+ LocalDateTime initialThreshold = now.minusMinutes(initialMinutes);
java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper()
.eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRODUCT_RISK)
.eq(FileTaskEntity::getStatus, "RUNNING")
@@ -125,9 +130,19 @@ public class DeleteBrandStaleTaskService {
if (runningTasks.isEmpty()) {
return stats;
}
- log.info("[stale-check] product-risk candidates={} threshold={} timeoutMinutes={}",
- runningTasks.size(), threshold, minutes);
+ log.info("[stale-check] product-risk candidates={} threshold={} timeoutMinutes={} initialThreshold={} initialTimeoutMinutes={}",
+ runningTasks.size(), threshold, minutes, initialThreshold, initialMinutes);
for (FileTaskEntity task : runningTasks) {
+ boolean hasUploadedPayload = productRiskTaskCacheService.hasAnyShopMergedPayload(task.getId());
+ boolean hasFinishedRows = (task.getSuccessFileCount() != null && task.getSuccessFileCount() > 0)
+ || (task.getFailedFileCount() != null && task.getFailedFileCount() > 0);
+ boolean hasStartedProgress = hasUploadedPayload || hasFinishedRows;
+ if (!hasStartedProgress && task.getCreatedAt() != null && task.getCreatedAt().isAfter(initialThreshold)) {
+ stats.skippedTaskCount++;
+ log.info("[stale-check] product-risk skip initial-grace taskId={} createdAt={} initialThreshold={}",
+ task.getId(), task.getCreatedAt(), initialThreshold);
+ continue;
+ }
try {
if (productRiskTaskService.tryFinalizeTask(task.getId(), true)) {
stats.finalizedTaskCount++;
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java
index e287cc787..587ebe318 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java
@@ -8,6 +8,7 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
+import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@@ -27,4 +28,8 @@ public class ProductRiskCreateTaskRequest {
+ "店名会去重;每店生成一条 biz_file_result(含 resultId)。",
requiredMode = Schema.RequiredMode.REQUIRED)
private List items = new ArrayList<>();
+
+ @JsonProperty("schedule_time")
+ @Schema(description = "可选,定时执行时间,必须晚于当前时间", example = "2026-04-09T18:30:00")
+ private LocalDateTime scheduleTime;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java
index 01cebecf9..41a60969c 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java
@@ -57,4 +57,8 @@ public class ProductRiskResultItemVo {
@JsonProperty("downloadUrl")
@Schema(description = "预签名下载 URL(列表里可能带;直链下载也可用 GET /results/{resultId}/download)")
private String downloadUrl;
+
+ @JsonProperty("scheduledAt")
+ @Schema(description = "定时执行时间,未设置时为空")
+ private String scheduledAt;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java
index b313a185e..971ce126b 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java
@@ -33,4 +33,8 @@ public class ProductRiskTaskItemVo {
@JsonProperty("finishedAt")
@Schema(description = "结束时间;RUNNING 时通常为空")
private String finishedAt;
+
+ @JsonProperty("scheduledAt")
+ @Schema(description = "定时执行时间,未设置时为空")
+ private String scheduledAt;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskCacheService.java
index 69f25f199..2a48521ed 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskCacheService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskCacheService.java
@@ -73,6 +73,14 @@ public class ProductRiskTaskCacheService {
}
}
+ public boolean hasAnyShopMergedPayload(Long taskId) {
+ if (taskId == null || taskId <= 0) {
+ return false;
+ }
+ Long size = stringRedisTemplate.opsForHash().size(buildShopPayloadKey(taskId));
+ return size != null && size > 0;
+ }
+
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java
new file mode 100644
index 000000000..63952d34c
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java
@@ -0,0 +1,150 @@
+package com.nanri.aiimage.modules.shopmatch.controller;
+
+import com.nanri.aiimage.common.api.ApiResponse;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCreateTaskRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskTaskBatchRequest;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCreateTaskVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo;
+import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchSubmitResultRequest;
+import com.nanri.aiimage.modules.shopmatch.service.ShopMatchResolveService;
+import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskService;
+import jakarta.validation.Valid;
+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.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;
+import org.springframework.web.server.ResponseStatusException;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/shop-match")
+public class ShopMatchController {
+
+ private final ShopMatchResolveService shopMatchResolveService;
+ private final ShopMatchTaskService shopMatchTaskService;
+
+ @GetMapping("/candidates")
+ public ApiResponse> listCandidates(@RequestParam("user_id") Long userId) {
+ return ApiResponse.success(shopMatchResolveService.listCandidates(userId));
+ }
+
+ @PostMapping("/candidates")
+ public ApiResponse addCandidate(@Valid @RequestBody ProductRiskCandidateAddRequest request) {
+ return ApiResponse.success(shopMatchResolveService.addCandidate(request));
+ }
+
+ @DeleteMapping("/candidates/{id}")
+ public ApiResponse deleteCandidate(@PathVariable Long id, @RequestParam("user_id") Long userId) {
+ shopMatchResolveService.deleteCandidate(userId, id);
+ return ApiResponse.success(null);
+ }
+
+ @GetMapping("/country-preference")
+ public ApiResponse getCountryPreference(@RequestParam("user_id") Long userId) {
+ return ApiResponse.success(shopMatchResolveService.getCountryPreference(userId));
+ }
+
+ @PutMapping("/country-preference")
+ public ApiResponse saveCountryPreference(@Valid @RequestBody ProductRiskCountryPreferenceSaveRequest request) {
+ return ApiResponse.success(shopMatchResolveService.saveCountryPreference(request));
+ }
+
+ @PostMapping("/match-shops")
+ public ApiResponse matchShops(@Valid @RequestBody ProductRiskMatchShopsRequest request) {
+ return ApiResponse.success(shopMatchResolveService.matchShops(request));
+ }
+
+ @GetMapping("/dashboard")
+ public ApiResponse dashboard(@RequestParam("user_id") Long userId) {
+ return ApiResponse.success(shopMatchTaskService.dashboard(userId));
+ }
+
+ @GetMapping("/history")
+ public ApiResponse history(@RequestParam("user_id") Long userId) {
+ return ApiResponse.success(shopMatchTaskService.listHistory(userId));
+ }
+
+ @DeleteMapping("/history/{resultId}")
+ public ApiResponse deleteHistory(@PathVariable Long resultId, @RequestParam("user_id") Long userId) {
+ shopMatchTaskService.deleteHistory(resultId, userId);
+ return ApiResponse.success(null);
+ }
+
+ @PostMapping("/tasks")
+ public ApiResponse createTask(@Valid @RequestBody ProductRiskCreateTaskRequest request) {
+ return ApiResponse.success(shopMatchTaskService.createTask(request));
+ }
+
+ @DeleteMapping("/tasks/{taskId}")
+ public ApiResponse deleteTask(@PathVariable Long taskId, @RequestParam("user_id") Long userId) {
+ shopMatchTaskService.deleteTask(taskId, userId);
+ return ApiResponse.success(null);
+ }
+
+ @PostMapping("/tasks/{taskId}/activate")
+ public ApiResponse activateTask(@PathVariable Long taskId, @RequestParam("user_id") Long userId) {
+ shopMatchTaskService.activateTask(taskId, userId);
+ return ApiResponse.success(null);
+ }
+
+ @PostMapping("/tasks/batch")
+ public ApiResponse tasksBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) {
+ return ApiResponse.success(shopMatchTaskService.getTaskDetailsBatch(request.getTaskIds()));
+ }
+
+ @PostMapping("/tasks/{taskId}/result")
+ public ApiResponse submitResult(@PathVariable Long taskId, @Valid @RequestBody ShopMatchSubmitResultRequest request) {
+ shopMatchTaskService.submitResult(taskId, request);
+ return ApiResponse.success(null);
+ }
+
+ @GetMapping("/results/{resultId}/download")
+ public void downloadResult(
+ @PathVariable Long resultId,
+ @RequestParam("user_id") Long userId,
+ jakarta.servlet.http.HttpServletResponse response) {
+ String url = shopMatchTaskService.resolveResultDownloadUrl(resultId, userId);
+ String filename = shopMatchTaskService.resolveResultDownloadFilename(resultId, userId);
+ if (url == null || url.isBlank()) {
+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, "暂无可下载结果");
+ }
+ 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, "下载失败");
+ }
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchCountryPrefMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchCountryPrefMapper.java
new file mode 100644
index 000000000..c34f32ffa
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchCountryPrefMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.shopmatch.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.shopmatch.model.entity.ShopMatchCountryPrefEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ShopMatchCountryPrefMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchShopCandidateMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchShopCandidateMapper.java
new file mode 100644
index 000000000..c5cdb0e50
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/mapper/ShopMatchShopCandidateMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.shopmatch.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.shopmatch.model.entity.ShopMatchShopCandidateEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ShopMatchShopCandidateMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchRowDto.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchRowDto.java
new file mode 100644
index 000000000..222cc170b
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchRowDto.java
@@ -0,0 +1,20 @@
+package com.nanri.aiimage.modules.shopmatch.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+@Data
+@Schema(description = "匹配店铺单行结果")
+public class ShopMatchRowDto {
+
+ @Schema(description = "ASIN")
+ private String asin;
+
+ @Schema(description = "状态")
+ private String status;
+
+ @JsonProperty("done")
+ @Schema(description = "该店铺是否已完成回传")
+ private Boolean done;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchShopPayloadDto.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchShopPayloadDto.java
new file mode 100644
index 000000000..9100f22fa
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchShopPayloadDto.java
@@ -0,0 +1,25 @@
+package com.nanri.aiimage.modules.shopmatch.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Data
+@Schema(description = "Python 回传的单店铺结果")
+public class ShopMatchShopPayloadDto {
+
+ @JsonProperty("shopName")
+ @Schema(description = "店铺名称")
+ private String shopName;
+
+ @Schema(description = "失败时的错误信息")
+ private String error;
+
+ @Schema(description = "按国家分组的 ASIN/状态 列表")
+ private Map> countries = new LinkedHashMap<>();
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchSubmitResultRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchSubmitResultRequest.java
new file mode 100644
index 000000000..d1719ad82
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/dto/ShopMatchSubmitResultRequest.java
@@ -0,0 +1,18 @@
+package com.nanri.aiimage.modules.shopmatch.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 ShopMatchSubmitResultRequest {
+
+ @NotEmpty(message = "shops 不能为空")
+ @Valid
+ private List shops = new ArrayList<>();
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchCountryPrefEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchCountryPrefEntity.java
new file mode 100644
index 000000000..c7cf6dc9d
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchCountryPrefEntity.java
@@ -0,0 +1,18 @@
+package com.nanri.aiimage.modules.shopmatch.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_match_country_pref")
+public class ShopMatchCountryPrefEntity {
+
+ @TableId(type = IdType.INPUT)
+ private Long userId;
+ private String countryCodesJson;
+ private LocalDateTime updatedAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchShopCandidateEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchShopCandidateEntity.java
new file mode 100644
index 000000000..4eaf49268
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/model/entity/ShopMatchShopCandidateEntity.java
@@ -0,0 +1,19 @@
+package com.nanri.aiimage.modules.shopmatch.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_match_shop_candidate")
+public class ShopMatchShopCandidateEntity {
+
+ @TableId(type = IdType.AUTO)
+ private Long id;
+ private Long userId;
+ private String shopName;
+ private LocalDateTime createdAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchExcelAssemblyService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchExcelAssemblyService.java
new file mode 100644
index 000000000..e58159eb6
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchExcelAssemblyService.java
@@ -0,0 +1,79 @@
+package com.nanri.aiimage.modules.shopmatch.service;
+
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
+import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchRowDto;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+@Slf4j
+public class ShopMatchExcelAssemblyService {
+
+ private static final String[] HEADER = {"ASIN", "状态"};
+
+ public void writeWorkbook(File outputXlsx, Map> countries) {
+ Map> safe = countries == null ? Map.of() : countries;
+ try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream fos = new FileOutputStream(outputXlsx)) {
+ for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) {
+ String sheetName = code.getSheetName();
+ Sheet sheet = wb.createSheet(sheetName);
+ Row header = sheet.createRow(0);
+ header.createCell(0).setCellValue(HEADER[0]);
+ header.createCell(1).setCellValue(HEADER[1]);
+ List rows = safe.getOrDefault(sheetName, List.of());
+ int rowIndex = 1;
+ for (ShopMatchRowDto item : rows) {
+ if (item == null) {
+ continue;
+ }
+ Row row = sheet.createRow(rowIndex++);
+ row.createCell(0).setCellValue(item.getAsin() == null ? "" : item.getAsin());
+ row.createCell(1).setCellValue(item.getStatus() == null ? "" : item.getStatus());
+ }
+ sheet.autoSizeColumn(0);
+ sheet.autoSizeColumn(1);
+ }
+ wb.write(fos);
+ } catch (Exception ex) {
+ log.warn("[shop-match] write workbook failed: {}", ex.getMessage());
+ throw new BusinessException("生成 Excel 失败: " + ex.getMessage());
+ }
+ }
+
+ public int countRows(Map> countries) {
+ if (countries == null || countries.isEmpty()) {
+ return 0;
+ }
+ int count = 0;
+ for (List rows : countries.values()) {
+ if (rows != null) {
+ count += rows.size();
+ }
+ }
+ return count;
+ }
+
+ public Map> normalizeCountriesMap(Map> raw) {
+ if (raw == null || raw.isEmpty()) {
+ return new LinkedHashMap<>();
+ }
+ Map> out = new LinkedHashMap<>();
+ for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) {
+ List rows = raw.get(code);
+ if (rows != null) {
+ out.put(code.getSheetName(), rows);
+ }
+ }
+ return out;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchResolveService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchResolveService.java
new file mode 100644
index 000000000..0cc801483
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchResolveService.java
@@ -0,0 +1,274 @@
+package com.nanri.aiimage.modules.shopmatch.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
+import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
+import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
+import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
+import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchCountryPrefMapper;
+import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
+import com.nanri.aiimage.modules.shopmatch.model.entity.ShopMatchCountryPrefEntity;
+import com.nanri.aiimage.modules.shopmatch.model.entity.ShopMatchShopCandidateEntity;
+import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
+import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
+import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Objects;
+
+@Service
+@RequiredArgsConstructor
+public class ShopMatchResolveService {
+
+ public static final List DEFAULT_COUNTRY_PREFERENCE_ORDER = List.of("DE", "UK", "FR", "IT", "ES");
+
+ private final ShopMatchShopCandidateMapper candidateMapper;
+ private final ShopMatchCountryPrefMapper countryPrefMapper;
+ private final ObjectMapper objectMapper;
+ private final ZiniaoShopSwitchService ziniaoShopSwitchService;
+
+ public List listCandidates(Long userId) {
+ if (userId == null || userId <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ List rows = candidateMapper.selectList(
+ new LambdaQueryWrapper()
+ .eq(ShopMatchShopCandidateEntity::getUserId, userId)
+ .orderByDesc(ShopMatchShopCandidateEntity::getId));
+ List list = new ArrayList<>();
+ for (ShopMatchShopCandidateEntity row : rows) {
+ ProductRiskCandidateVo vo = new ProductRiskCandidateVo();
+ vo.setId(row.getId());
+ vo.setShopName(row.getShopName());
+ vo.setCreatedAt(row.getCreatedAt());
+ list.add(vo);
+ }
+ return list;
+ }
+
+ @Transactional
+ public ProductRiskCandidateVo addCandidate(ProductRiskCandidateAddRequest request) {
+ if (request.getUserId() == null || request.getUserId() <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ String normalized = ziniaoShopSwitchService.normalizeShopName(request.getShopName());
+ if (normalized.isBlank()) {
+ throw new BusinessException("店铺名不能为空");
+ }
+ ZiniaoShopMatchResultVo indexHit = ziniaoShopSwitchService.findIndexedStoreByName(normalized, false);
+ if (indexHit == null || !indexHit.isMatched()) {
+ String hint = indexHit != null && indexHit.getMatchMessage() != null && !indexHit.getMatchMessage().isBlank()
+ ? indexHit.getMatchMessage()
+ : "店铺索引未命中,无法加入备选";
+ throw new BusinessException(hint);
+ }
+ if (ZiniaoShopIndexService.MATCH_STATUS_CONFLICT.equals(indexHit.getMatchStatus())) {
+ throw new BusinessException(indexHit.getMatchMessage() != null ? indexHit.getMatchMessage() : "存在多个同名店铺,请人工确认");
+ }
+
+ ShopMatchShopCandidateEntity existing = candidateMapper.selectOne(
+ new LambdaQueryWrapper()
+ .eq(ShopMatchShopCandidateEntity::getUserId, request.getUserId())
+ .eq(ShopMatchShopCandidateEntity::getShopName, normalized)
+ .last("limit 1"));
+ if (existing != null) {
+ ProductRiskCandidateVo vo = new ProductRiskCandidateVo();
+ vo.setId(existing.getId());
+ vo.setShopName(existing.getShopName());
+ vo.setCreatedAt(existing.getCreatedAt());
+ return vo;
+ }
+
+ ShopMatchShopCandidateEntity entity = new ShopMatchShopCandidateEntity();
+ entity.setUserId(request.getUserId());
+ entity.setShopName(normalized);
+ entity.setCreatedAt(LocalDateTime.now());
+ candidateMapper.insert(entity);
+
+ ProductRiskCandidateVo vo = new ProductRiskCandidateVo();
+ vo.setId(entity.getId());
+ vo.setShopName(entity.getShopName());
+ vo.setCreatedAt(entity.getCreatedAt());
+ return vo;
+ }
+
+ @Transactional
+ public void deleteCandidate(Long userId, Long id) {
+ if (userId == null || userId <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ if (id == null || id <= 0) {
+ throw new BusinessException("id 不合法");
+ }
+ ShopMatchShopCandidateEntity row = candidateMapper.selectById(id);
+ if (row == null || !userId.equals(row.getUserId())) {
+ throw new BusinessException("记录不存在");
+ }
+ candidateMapper.deleteById(id);
+ }
+
+ public ProductRiskMatchShopsVo matchShops(ProductRiskMatchShopsRequest request) {
+ if (request.getUserId() == null || request.getUserId() <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ LinkedHashSet ordered = new LinkedHashSet<>();
+ for (String raw : request.getShopNames()) {
+ String normalized = ziniaoShopSwitchService.normalizeShopName(raw);
+ if (!normalized.isBlank()) {
+ ordered.add(normalized);
+ }
+ }
+ if (ordered.isEmpty()) {
+ throw new BusinessException("shop_names 无有效店铺名");
+ }
+ ProductRiskMatchShopsVo vo = new ProductRiskMatchShopsVo();
+ for (String shopName : ordered) {
+ vo.getItems().add(matchOneShop(shopName));
+ }
+ return vo;
+ }
+
+ public ProductRiskCountryPreferenceVo getCountryPreference(Long userId) {
+ if (userId == null || userId <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ ShopMatchCountryPrefEntity row = countryPrefMapper.selectById(userId);
+ ProductRiskCountryPreferenceVo vo = new ProductRiskCountryPreferenceVo();
+ if (row == null || row.getCountryCodesJson() == null || row.getCountryCodesJson().isBlank()) {
+ vo.getCountryCodes().addAll(DEFAULT_COUNTRY_PREFERENCE_ORDER);
+ return vo;
+ }
+ try {
+ List parsed = objectMapper.readValue(row.getCountryCodesJson(), new TypeReference>() {});
+ vo.getCountryCodes().addAll(sanitizeStoredCodes(parsed));
+ } catch (Exception ex) {
+ vo.getCountryCodes().addAll(DEFAULT_COUNTRY_PREFERENCE_ORDER);
+ }
+ return vo;
+ }
+
+ @Transactional
+ public ProductRiskCountryPreferenceVo saveCountryPreference(ProductRiskCountryPreferenceSaveRequest request) {
+ if (request.getUserId() == null || request.getUserId() <= 0) {
+ throw new BusinessException("user_id 不合法");
+ }
+ List normalized = validateCountryCodesForSave(request.getCountryCodes());
+ String json;
+ try {
+ json = objectMapper.writeValueAsString(normalized);
+ } catch (Exception ex) {
+ throw new BusinessException("保存偏好失败");
+ }
+
+ ShopMatchCountryPrefEntity row = countryPrefMapper.selectById(request.getUserId());
+ if (row == null) {
+ row = new ShopMatchCountryPrefEntity();
+ row.setUserId(request.getUserId());
+ row.setCountryCodesJson(json);
+ countryPrefMapper.insert(row);
+ } else {
+ row.setCountryCodesJson(json);
+ countryPrefMapper.updateById(row);
+ }
+
+ ProductRiskCountryPreferenceVo vo = new ProductRiskCountryPreferenceVo();
+ vo.getCountryCodes().addAll(normalized);
+ return vo;
+ }
+
+ private ProductRiskShopQueueItemVo matchOneShop(String shopName) {
+ ProductRiskShopQueueItemVo item = new ProductRiskShopQueueItemVo();
+ item.setShopName(shopName);
+ try {
+ ZiniaoShopMatchResultVo matched = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false);
+ if (matched == null) {
+ item.setMatched(false);
+ item.setMatchStatus("PENDING");
+ item.setMatchMessage("匹配结果为空");
+ return item;
+ }
+ item.setMatched(matched.isMatched());
+ item.setShopId(matched.getShopId());
+ item.setPlatform(matched.getPlatform());
+ item.setCompanyName(matched.getCompanyName());
+ item.setMatchedUserId(matched.getMatchedUserId());
+ item.setMatchStatus(matched.getMatchStatus());
+ item.setMatchMessage(matched.getMatchMessage());
+ item.setOpenStoreUrl(matched.getOpenStoreUrl());
+ } catch (BusinessException ex) {
+ item.setMatched(false);
+ item.setMatchStatus("PENDING");
+ item.setMatchMessage(ex.getMessage());
+ } catch (Exception ex) {
+ item.setMatched(false);
+ item.setMatchStatus("PENDING");
+ item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
+ }
+ return item;
+ }
+
+ private static List sanitizeStoredCodes(List raw) {
+ List parsed = parseValidCountryCodes(raw);
+ return parsed.isEmpty() ? new ArrayList<>(DEFAULT_COUNTRY_PREFERENCE_ORDER) : parsed;
+ }
+
+ private static List validateCountryCodesForSave(List raw) {
+ if (raw == null || raw.isEmpty()) {
+ throw new BusinessException("country_codes 至少选择 1 个国家");
+ }
+ LinkedHashSet seen = new LinkedHashSet<>();
+ List out = new ArrayList<>();
+ for (String item : raw) {
+ if (item == null || item.isBlank()) {
+ throw new BusinessException("country_codes 含空值");
+ }
+ String upper = item.trim().toUpperCase();
+ try {
+ ProductRiskCountryCode.valueOf(upper);
+ } catch (IllegalArgumentException ex) {
+ throw new BusinessException("非法国家代码: " + item);
+ }
+ if (!seen.add(upper)) {
+ throw new BusinessException("country_codes 存在重复: " + upper);
+ }
+ out.add(upper);
+ }
+ return out;
+ }
+
+ private static List parseValidCountryCodes(List raw) {
+ if (raw == null || raw.isEmpty()) {
+ return new ArrayList<>();
+ }
+ LinkedHashSet seen = new LinkedHashSet<>();
+ List out = new ArrayList<>();
+ for (String item : raw) {
+ if (item == null || item.isBlank()) {
+ continue;
+ }
+ String upper = item.trim().toUpperCase();
+ try {
+ ProductRiskCountryCode.valueOf(upper);
+ } catch (IllegalArgumentException ex) {
+ continue;
+ }
+ if (seen.add(upper)) {
+ out.add(upper);
+ }
+ }
+ return out;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java
new file mode 100644
index 000000000..79335479c
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java
@@ -0,0 +1,87 @@
+package com.nanri.aiimage.modules.shopmatch.service;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchShopPayloadDto;
+import lombok.RequiredArgsConstructor;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+@Service
+@RequiredArgsConstructor
+public class ShopMatchTaskCacheService {
+
+ private static final long PAYLOAD_TTL_HOURS = 24;
+
+ private final StringRedisTemplate stringRedisTemplate;
+ private final ObjectMapper objectMapper;
+
+ public ShopMatchShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
+ if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) {
+ return null;
+ }
+ Object raw = stringRedisTemplate.opsForHash().get(buildShopPayloadKey(taskId), shopKey);
+ if (!(raw instanceof String json) || json.isBlank()) {
+ return null;
+ }
+ try {
+ return objectMapper.readValue(json, ShopMatchShopPayloadDto.class);
+ } catch (Exception ex) {
+ throw new BusinessException("读取匹配店铺缓存失败");
+ }
+ }
+
+ public void saveShopMergedPayload(Long taskId, String shopKey, ShopMatchShopPayloadDto payload) {
+ if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
+ return;
+ }
+ try {
+ String key = buildShopPayloadKey(taskId);
+ stringRedisTemplate.opsForHash().put(key, shopKey, objectMapper.writeValueAsString(payload));
+ stringRedisTemplate.expire(key, Duration.ofHours(PAYLOAD_TTL_HOURS));
+ } catch (Exception ex) {
+ throw new BusinessException("暂存匹配店铺结果失败");
+ }
+ }
+
+ public void removeShopMergedPayload(Long taskId, String shopKey) {
+ if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) {
+ return;
+ }
+ stringRedisTemplate.opsForHash().delete(buildShopPayloadKey(taskId), shopKey);
+ }
+
+ public Map getAllShopMergedPayload(Long taskId) {
+ try {
+ Map