diff --git a/app/.env b/app/.env
index 4748534..a8104b3 100644
--- a/app/.env
+++ b/app/.env
@@ -14,7 +14,6 @@ client_name=ShuFuAI
# java_api_base=http://47.111.163.154: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
diff --git a/app/__pycache__/app_common.cpython-312.pyc b/app/__pycache__/app_common.cpython-312.pyc
index 92c7675..eac4be7 100644
Binary files a/app/__pycache__/app_common.cpython-312.pyc and b/app/__pycache__/app_common.cpython-312.pyc differ
diff --git a/app/amazon/__pycache__/match_action.cpython-312.pyc b/app/amazon/__pycache__/match_action.cpython-312.pyc
index c770364..4aa5da0 100644
Binary files a/app/amazon/__pycache__/match_action.cpython-312.pyc and b/app/amazon/__pycache__/match_action.cpython-312.pyc differ
diff --git a/app/assets/convert.js b/app/assets/convert.js
index d4284b4..5e77525 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-C_Si_gmj.js";import{e as Y}from"./brand-CyZr-IbT.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-D7_PdvyM.js";import{e as Y}from"./brand-DysFlQbZ.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 57728d1..12f24d7 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-C_Si_gmj.js";import{e as se}from"./brand-CyZr-IbT.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-D7_PdvyM.js";import{e as se}from"./brand-DysFlQbZ.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 e1a175e..8b54b1e 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-C_Si_gmj.js";import{e as ts}from"./brand-CyZr-IbT.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-D7_PdvyM.js";import{e as ts}from"./brand-DysFlQbZ.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 8c34021..b4523fe 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-C_Si_gmj.js";import{e as as}from"./brand-CyZr-IbT.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-D7_PdvyM.js";import{e as as}from"./brand-DysFlQbZ.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__/admin.cpython-312.pyc b/app/blueprints/__pycache__/admin.cpython-312.pyc
index 9d093bb..b65da1d 100644
Binary files a/app/blueprints/__pycache__/admin.cpython-312.pyc and b/app/blueprints/__pycache__/admin.cpython-312.pyc differ
diff --git a/app/new_web_source/convert.html b/app/new_web_source/convert.html
index 194e09e..f682ccb 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 399a780..c64ad66 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 8d2427b..9f4323e 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 88e08d6..3a6d31d 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-11.0.gz b/backend-java/aiimage-backend.log.2026-04-11.0.gz
new file mode 100644
index 0000000..9543d86
Binary files /dev/null and b/backend-java/aiimage-backend.log.2026-04-11.0.gz differ
diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java
index 7b1e109..3512bc8 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java
@@ -32,6 +32,6 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ApiResponse handleException(Exception ex) {
log.error("Unhandled exception", ex);
- return ApiResponse.fail("服务异常:" + ex.getMessage());
+ return ApiResponse.fail("服务异常: " + ex.getMessage());
}
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java
index 54965c6..c080b5d 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java
@@ -127,7 +127,7 @@ public class DeleteBrandRunService {
ZiniaoShopMatchResultVo matchResult = normalizedShopName.isBlank()
? ziniaoShopSwitchService.emptyMatchResult()
: storeMatchByShopName.computeIfAbsent(normalizedShopName,
- ignored -> ziniaoShopSwitchService.findIndexedStoreByName(item.getShopName()));
+ ignored -> ziniaoShopSwitchService.findIndexedStoreByName(item.getShopName(), false));
item.setMatchStatus(matchResult.getMatchStatus());
item.setMatchMessage(matchResult.getMatchMessage());
item.setMatched(matchResult.isMatched());
@@ -714,7 +714,7 @@ public class DeleteBrandRunService {
unmatchedCount++;
continue;
}
- ZiniaoShopMatchResultVo refreshed = ziniaoShopSwitchService.findIndexedStoreByName(item.getShopName());
+ ZiniaoShopMatchResultVo refreshed = ziniaoShopSwitchService.findIndexedStoreByName(item.getShopName(), false);
if (refreshed != null) {
String oldStatus = item.getMatchStatus();
boolean oldMatched = item.isMatched();
@@ -990,6 +990,26 @@ public class DeleteBrandRunService {
Map> mergedByFile = loadMergedChunks(taskId);
int finishedFiles = countCompletedFiles(mergedByFile);
+ if (finishedFiles < expectedFiles) {
+ Map progress = new LinkedHashMap<>();
+ progress.put("finished_files", String.valueOf(finishedFiles));
+ // 定时补偿只负责“再试一次 finalize”,不能把缺片任务重新续命,
+ // 否则 stale-check 永远看不到超时任务。
+ if (!fromCompensation) {
+ progress.put("updated_at", String.valueOf(System.currentTimeMillis()));
+ }
+ deleteBrandTaskCacheService.saveProgress(taskId, progress);
+
+ task.setSuccessFileCount(finishedFiles);
+ if (!fromCompensation) {
+ task.setUpdatedAt(LocalDateTime.now());
+ }
+ fileTaskMapper.updateById(task);
+
+ log.info("[DeleteBrand] tryFinalizeTask skipping -> finishedFiles ({}) < expectedFiles ({})", finishedFiles, expectedFiles);
+ return;
+ }
+
Map progress = new LinkedHashMap<>();
progress.put("finished_files", String.valueOf(finishedFiles));
progress.put("updated_at", String.valueOf(System.currentTimeMillis()));
@@ -1001,11 +1021,6 @@ public class DeleteBrandRunService {
task.setSuccessFileCount(finishedFiles);
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
-
- if (finishedFiles < expectedFiles) {
- log.info("[DeleteBrand] tryFinalizeTask skipping -> finishedFiles ({}) < expectedFiles ({})", finishedFiles, expectedFiles);
- return;
- }
log.info("[DeleteBrand] tryFinalizeTask calling finalizeTask -> finishedFiles: {}, expectedFiles: {}", finishedFiles, expectedFiles);
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 2623dfc..afd8b27 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
@@ -20,7 +20,8 @@ import java.time.ZoneId;
import java.util.Map;
/**
- * 鍒犻櫎鍝佺墝浠诲姟鐨勮秴鏃跺洖鏀朵笌 finalize 琛ュ伩锛涘苟涓庡垹闄ゅ搧鐗屽叡鐢ㄥ悓涓€濂楀畾鏃惰皟搴︼紝瀵瑰晢鍝侀闄╋紙PRODUCT_RISK_RESOLVE锛夐暱鏃堕棿鏃犲洖浼犲仛澶辫触鏀跺熬銆?
+ * 删除品牌任务的超时回收与 finalize 补偿。
+ * 同时复用这套定时调度,对商品风险和匹配店铺任务做超时兜底收尾。
*/
@Service
@RequiredArgsConstructor
@@ -66,7 +67,7 @@ public class DeleteBrandStaleTaskService {
private void failStaleDeleteBrandTasks() {
LocalDateTime threshold = LocalDateTime.now().minusMinutes(deleteBrandProgressProperties.getHeartbeatTimeoutMinutes());
- // 鍏堟寜 DB updatedAt 绮楃瓫锛岄伩鍏嶅叏琛ㄦ壂鎻?
+ // 先按 DB updatedAt 粗筛,避免全表扫描。
java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper()
.eq(FileTaskEntity::getModuleType, MODULE_TYPE_DELETE_BRAND)
.eq(FileTaskEntity::getStatus, "RUNNING")
@@ -96,19 +97,17 @@ public class DeleteBrandStaleTaskService {
}
LocalDateTime lastActivityTime;
- // 鍙湁褰?has_progress 涓?true 涓旇秴杩?15 鍒嗛挓娌″績璺筹紝鎵嶈涓烘槸寮傚父鍗℃
+ // 只有 has_progress=true 且心跳超时,才判定为异常卡住。
if (lastHeartbeatAt > 0 && isActive) {
- // 鏈夊績璺筹紝鐢ㄦ渶鍚庡績璺虫椂闂村姣?15 鍒嗛挓 (threshold 鏄?now - 15)
lastActivityTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastHeartbeatAt), ZoneId.systemDefault());
if (lastActivityTime.isAfter(threshold)) {
- continue; // 娌¤秴鏃?
+ continue;
}
} else {
- // 娌℃湁蹇冭烦锛屾垨鑰呭綋鍓嶅鍦?has_progress: false 锛堢瓑寰呯敤鎴风偣鍑讳笅涓€涓换鍔℃帹閫佺殑闈欓粯鏈燂級
- // 闈欓粯鏈熷拰鎺掗槦鏈熺殑瀹介檺鏈熶竴鏍凤紝璁句负 12 涓皬鏃?
+ // 没有心跳,或仍处于静默等待阶段时,使用更长的初始宽限期。
LocalDateTime queuedThreshold = LocalDateTime.now().minusHours(12);
if (task.getCreatedAt() != null && task.getCreatedAt().isAfter(queuedThreshold)) {
- continue; // 绛夊緟涓嬩釜闃熷垪鎺ㄩ€佷腑锛屼笉瑕佹潃瀹冿紒
+ continue;
}
}
@@ -117,7 +116,7 @@ public class DeleteBrandStaleTaskService {
.eq(FileTaskEntity::getModuleType, MODULE_TYPE_DELETE_BRAND)
.eq(FileTaskEntity::getStatus, "RUNNING")
.set(FileTaskEntity::getStatus, "FAILED")
- .set(FileTaskEntity::getErrorMessage, "缁撴灉鍥炰紶闀挎椂闂存棤鍝嶅簲锛屼换鍔″凡鑷姩澶辫触")
+ .set(FileTaskEntity::getErrorMessage, "结果回传长时间无响应,任务已自动失败")
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
@@ -170,7 +169,7 @@ public class DeleteBrandStaleTaskService {
.eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRODUCT_RISK)
.eq(FileTaskEntity::getStatus, "RUNNING")
.set(FileTaskEntity::getStatus, "FAILED")
- .set(FileTaskEntity::getErrorMessage, "闀挎椂闂存湭鏀跺埌 Python 缁撴灉锛屼换鍔″凡鑷姩澶辫触")
+ .set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败")
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated > 0) {
@@ -252,7 +251,7 @@ public class DeleteBrandStaleTaskService {
try {
deleteBrandRunService.tryFinalizeTask(task.getId(), true);
} catch (Exception ignored) {
- // 瀹氭椂琛ュ伩涓嶅奖鍝嶄富娴佺▼锛涗笅娆¤皟搴︽垨浜哄伐閲嶈瘯鏃跺啀澶勭悊
+ // 定时补偿不影响主流程;下次调度或人工重试时再处理。
}
}
}
@@ -271,4 +270,3 @@ public class DeleteBrandStaleTaskService {
private int skippedTaskCount;
}
}
-
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/controller/PermissionMenuController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/controller/PermissionMenuController.java
new file mode 100644
index 0000000..6db3afb
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/controller/PermissionMenuController.java
@@ -0,0 +1,83 @@
+package com.nanri.aiimage.modules.permission.controller;
+
+import com.nanri.aiimage.common.api.ApiResponse;
+import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuCreateRequest;
+import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuUpdateRequest;
+import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
+import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
+import com.nanri.aiimage.modules.permission.model.vo.UserColumnIdsVo;
+import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/admin")
+@Tag(name = "菜单权限管理", description = "统一维护软件端与后台管理端的菜单权限配置")
+public class PermissionMenuController {
+
+ private final PermissionMenuService permissionMenuService;
+
+ @GetMapping("/permission-menus")
+ @Operation(summary = "查询菜单权限列表")
+ public ApiResponse> listMenus(
+ @Parameter(description = "菜单类型: app/admin") @RequestParam(required = false) String menuType) {
+ return ApiResponse.success(permissionMenuService.list(menuType));
+ }
+
+ @PostMapping("/permission-menus")
+ @Operation(summary = "新增菜单权限项")
+ public ApiResponse createMenu(@Valid @RequestBody PermissionMenuCreateRequest request) {
+ return ApiResponse.success("创建成功", permissionMenuService.create(request));
+ }
+
+ @PutMapping("/permission-menus/{id}")
+ @Operation(summary = "编辑菜单权限项")
+ public ApiResponse updateMenu(@PathVariable Long id,
+ @Valid @RequestBody PermissionMenuUpdateRequest request) {
+ return ApiResponse.success("更新成功", permissionMenuService.update(id, request));
+ }
+
+ @DeleteMapping("/permission-menus/{id}")
+ @Operation(summary = "删除菜单权限项")
+ public ApiResponse deleteMenu(@PathVariable Long id) {
+ permissionMenuService.delete(id);
+ return ApiResponse.success("删除成功", null);
+ }
+
+ @GetMapping("/permission-users/{userId}/columns")
+ @Operation(summary = "查询用户菜单权限 ID 列表")
+ public ApiResponse getUserColumnIds(@PathVariable Long userId,
+ @RequestParam(required = false) String menuType) {
+ return ApiResponse.success(permissionMenuService.getUserColumnIds(userId, menuType));
+ }
+
+ @PutMapping("/permission-users/{userId}/columns")
+ @Operation(summary = "更新用户菜单权限")
+ public ApiResponse updateUserColumnIds(@PathVariable Long userId,
+ @RequestBody(required = false) UserColumnPermissionUpdateRequest request) {
+ permissionMenuService.updateUserColumnPermissions(userId, request);
+ return ApiResponse.success("保存成功", null);
+ }
+
+ @GetMapping("/permission-users/{userId}/column-permissions")
+ @Operation(summary = "查询用户菜单权限详情")
+ public ApiResponse> getUserColumnPermissions(@PathVariable Long userId,
+ @RequestParam(required = false) String menuType) {
+ return ApiResponse.success(permissionMenuService.getUserColumnPermissions(userId, menuType));
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/AdminUserMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/AdminUserMapper.java
new file mode 100644
index 0000000..4e0c7ef
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/AdminUserMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.permission.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface AdminUserMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/PermissionMenuMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/PermissionMenuMapper.java
new file mode 100644
index 0000000..0aeb022
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/PermissionMenuMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.permission.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface PermissionMenuMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/UserColumnPermissionMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/UserColumnPermissionMapper.java
new file mode 100644
index 0000000..569af53
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/mapper/UserColumnPermissionMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.permission.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.permission.model.entity.UserColumnPermissionEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserColumnPermissionMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java
new file mode 100644
index 0000000..b40ab05
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java
@@ -0,0 +1,20 @@
+package com.nanri.aiimage.modules.permission.model.dto;
+
+import jakarta.validation.constraints.NotBlank;
+import lombok.Data;
+
+@Data
+public class PermissionMenuCreateRequest {
+
+ @NotBlank(message = "菜单名称不能为空")
+ private String name;
+
+ @NotBlank(message = "菜单标识不能为空")
+ private String columnKey;
+
+ @NotBlank(message = "菜单类型不能为空")
+ private String menuType;
+
+ @NotBlank(message = "菜单路由不能为空")
+ private String routePath;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java
new file mode 100644
index 0000000..38ef597
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java
@@ -0,0 +1,20 @@
+package com.nanri.aiimage.modules.permission.model.dto;
+
+import jakarta.validation.constraints.NotBlank;
+import lombok.Data;
+
+@Data
+public class PermissionMenuUpdateRequest {
+
+ @NotBlank(message = "菜单名称不能为空")
+ private String name;
+
+ @NotBlank(message = "菜单标识不能为空")
+ private String columnKey;
+
+ @NotBlank(message = "菜单类型不能为空")
+ private String menuType;
+
+ @NotBlank(message = "菜单路由不能为空")
+ private String routePath;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/UserColumnPermissionUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/UserColumnPermissionUpdateRequest.java
new file mode 100644
index 0000000..64ea470
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/UserColumnPermissionUpdateRequest.java
@@ -0,0 +1,11 @@
+package com.nanri.aiimage.modules.permission.model.dto;
+
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class UserColumnPermissionUpdateRequest {
+
+ private List columnIds;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java
new file mode 100644
index 0000000..b3af65b
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java
@@ -0,0 +1,15 @@
+package com.nanri.aiimage.modules.permission.model.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+@Data
+@TableName("users")
+public class AdminUserEntity {
+
+ @TableId(type = IdType.AUTO)
+ private Long id;
+ private String role;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java
new file mode 100644
index 0000000..c8e4262
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java
@@ -0,0 +1,21 @@
+package com.nanri.aiimage.modules.permission.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("columns")
+public class PermissionMenuEntity {
+
+ @TableId(type = IdType.AUTO)
+ private Long id;
+ private String name;
+ private String columnKey;
+ private String menuType;
+ private String routePath;
+ private LocalDateTime createdAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/UserColumnPermissionEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/UserColumnPermissionEntity.java
new file mode 100644
index 0000000..41108bc
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/UserColumnPermissionEntity.java
@@ -0,0 +1,16 @@
+package com.nanri.aiimage.modules.permission.model.entity;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+@Data
+@TableName("user_column_permission")
+public class UserColumnPermissionEntity {
+
+ @TableField("user_id")
+ private Long userId;
+
+ @TableField("column_id")
+ private Long columnId;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java
new file mode 100644
index 0000000..875dc87
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java
@@ -0,0 +1,16 @@
+package com.nanri.aiimage.modules.permission.model.vo;
+
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+@Data
+public class PermissionMenuItemVo {
+
+ private Long id;
+ private String name;
+ private String columnKey;
+ private String menuType;
+ private String routePath;
+ private LocalDateTime createdAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/UserColumnIdsVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/UserColumnIdsVo.java
new file mode 100644
index 0000000..9879826
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/UserColumnIdsVo.java
@@ -0,0 +1,11 @@
+package com.nanri.aiimage.modules.permission.model.vo;
+
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class UserColumnIdsVo {
+
+ private List columnIds;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java
new file mode 100644
index 0000000..bf00c99
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java
@@ -0,0 +1,55 @@
+package com.nanri.aiimage.modules.permission.service;
+
+import jakarta.annotation.PostConstruct;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+
+@Component
+@RequiredArgsConstructor
+@Slf4j
+public class PermissionMenuSchemaInitializer {
+
+ private final JdbcTemplate jdbcTemplate;
+
+ @PostConstruct
+ public void initialize() {
+ executeQuietly("""
+ CREATE TABLE IF NOT EXISTS columns (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(128) NOT NULL COMMENT '栏目名',
+ column_key VARCHAR(64) NOT NULL COMMENT '栏目标识',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY uk_column_key (column_key)
+ )
+ """);
+ executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key");
+ executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type");
+ executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''");
+ executeQuietly("""
+ INSERT INTO columns (name, column_key, menu_type, route_path)
+ SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage'
+ WHERE NOT EXISTS (
+ SELECT 1 FROM columns WHERE column_key = 'admin_shop_manage'
+ )
+ """);
+ executeQuietly("""
+ CREATE TABLE IF NOT EXISTS user_column_permission (
+ user_id INT NOT NULL,
+ column_id INT NOT NULL,
+ PRIMARY KEY (user_id, column_id),
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ FOREIGN KEY (column_id) REFERENCES columns(id) ON DELETE CASCADE
+ )
+ """);
+ }
+
+ private void executeQuietly(String sql) {
+ try {
+ jdbcTemplate.execute(sql);
+ } catch (Exception ex) {
+ log.debug("[permission-menu] schema init skipped: {}", ex.getMessage());
+ }
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java
new file mode 100644
index 0000000..a0ef8f0
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java
@@ -0,0 +1,253 @@
+package com.nanri.aiimage.modules.permission.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper;
+import com.nanri.aiimage.modules.permission.mapper.PermissionMenuMapper;
+import com.nanri.aiimage.modules.permission.mapper.UserColumnPermissionMapper;
+import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuCreateRequest;
+import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuUpdateRequest;
+import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
+import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
+import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
+import com.nanri.aiimage.modules.permission.model.entity.UserColumnPermissionEntity;
+import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
+import com.nanri.aiimage.modules.permission.model.vo.UserColumnIdsVo;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+@Service
+@RequiredArgsConstructor
+public class PermissionMenuService {
+
+ public static final String MENU_TYPE_APP = "app";
+ public static final String MENU_TYPE_ADMIN = "admin";
+
+ private final PermissionMenuMapper permissionMenuMapper;
+ private final UserColumnPermissionMapper userColumnPermissionMapper;
+ private final AdminUserMapper adminUserMapper;
+
+ public List list(String menuType) {
+ LambdaQueryWrapper query = new LambdaQueryWrapper()
+ .eq(isValidMenuType(menuType), PermissionMenuEntity::getMenuType, normalizeMenuType(menuType))
+ .orderByAsc(PermissionMenuEntity::getId);
+ return permissionMenuMapper.selectList(query).stream()
+ .map(this::toItemVo)
+ .toList();
+ }
+
+ @Transactional
+ public PermissionMenuItemVo create(PermissionMenuCreateRequest request) {
+ String name = normalizeRequired(request.getName(), "菜单名称不能为空");
+ String columnKey = normalizeRequired(request.getColumnKey(), "菜单标识不能为空");
+ String menuType = normalizeMenuTypeRequired(request.getMenuType());
+ String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空");
+ ensureUniqueColumnKey(columnKey, null);
+
+ PermissionMenuEntity entity = new PermissionMenuEntity();
+ entity.setName(name);
+ entity.setColumnKey(columnKey);
+ entity.setMenuType(menuType);
+ entity.setRoutePath(routePath);
+ permissionMenuMapper.insert(entity);
+ return toItemVo(getMenuById(entity.getId()));
+ }
+
+ @Transactional
+ public PermissionMenuItemVo update(Long id, PermissionMenuUpdateRequest request) {
+ PermissionMenuEntity entity = getMenuById(id);
+ String name = normalizeRequired(request.getName(), "菜单名称不能为空");
+ String columnKey = normalizeRequired(request.getColumnKey(), "菜单标识不能为空");
+ String menuType = normalizeMenuTypeRequired(request.getMenuType());
+ String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空");
+ ensureUniqueColumnKey(columnKey, id);
+
+ entity.setName(name);
+ entity.setColumnKey(columnKey);
+ entity.setMenuType(menuType);
+ entity.setRoutePath(routePath);
+ permissionMenuMapper.updateById(entity);
+ return toItemVo(getMenuById(id));
+ }
+
+ @Transactional
+ public void delete(Long id) {
+ PermissionMenuEntity entity = getMenuById(id);
+ userColumnPermissionMapper.delete(new LambdaUpdateWrapper()
+ .eq(UserColumnPermissionEntity::getColumnId, entity.getId()));
+ permissionMenuMapper.deleteById(entity.getId());
+ }
+
+ public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) {
+ AdminUserEntity user = getUserById(userId);
+ List columnIds;
+ if (isSuperAdmin(user)) {
+ columnIds = list(menuType).stream().map(PermissionMenuItemVo::getId).toList();
+ } else {
+ List assignedIds = userColumnPermissionMapper.selectList(
+ new LambdaQueryWrapper()
+ .eq(UserColumnPermissionEntity::getUserId, userId))
+ .stream()
+ .map(UserColumnPermissionEntity::getColumnId)
+ .distinct()
+ .toList();
+ if (assignedIds.isEmpty()) {
+ columnIds = List.of();
+ } else if (isValidMenuType(menuType)) {
+ Set allowedIds = list(menuType).stream()
+ .map(PermissionMenuItemVo::getId)
+ .collect(Collectors.toSet());
+ columnIds = assignedIds.stream().filter(allowedIds::contains).toList();
+ } else {
+ columnIds = assignedIds;
+ }
+ }
+ UserColumnIdsVo vo = new UserColumnIdsVo();
+ vo.setColumnIds(columnIds);
+ return vo;
+ }
+
+ public List getUserColumnPermissions(Long userId, String menuType) {
+ AdminUserEntity user = getUserById(userId);
+ if (isSuperAdmin(user)) {
+ return list(menuType);
+ }
+ List assignedIds = userColumnPermissionMapper.selectList(
+ new LambdaQueryWrapper()
+ .eq(UserColumnPermissionEntity::getUserId, userId))
+ .stream()
+ .map(UserColumnPermissionEntity::getColumnId)
+ .distinct()
+ .toList();
+ if (assignedIds.isEmpty()) {
+ return List.of();
+ }
+ List menus = permissionMenuMapper.selectBatchIds(assignedIds);
+ Map menuMap = menus.stream()
+ .collect(Collectors.toMap(PermissionMenuEntity::getId, Function.identity()));
+ String safeMenuType = normalizeMenuType(menuType);
+ return assignedIds.stream()
+ .map(menuMap::get)
+ .filter(menu -> menu != null)
+ .filter(menu -> safeMenuType == null || safeMenuType.equals(menu.getMenuType()))
+ .map(this::toItemVo)
+ .toList();
+ }
+
+ @Transactional
+ public void updateUserColumnPermissions(Long userId, UserColumnPermissionUpdateRequest request) {
+ getUserById(userId);
+ List requestedIds = request == null ? List.of() : normalizeColumnIds(request.getColumnIds());
+ if (!requestedIds.isEmpty()) {
+ Long validCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper()
+ .in(PermissionMenuEntity::getId, requestedIds));
+ if (validCount == null || validCount != requestedIds.size()) {
+ throw new BusinessException("存在无效的菜单权限项");
+ }
+ }
+
+ userColumnPermissionMapper.delete(new LambdaUpdateWrapper()
+ .eq(UserColumnPermissionEntity::getUserId, userId));
+ for (Long columnId : requestedIds) {
+ UserColumnPermissionEntity entity = new UserColumnPermissionEntity();
+ entity.setUserId(userId);
+ entity.setColumnId(columnId);
+ userColumnPermissionMapper.insert(entity);
+ }
+ }
+
+ private PermissionMenuEntity getMenuById(Long id) {
+ PermissionMenuEntity entity = permissionMenuMapper.selectById(id);
+ if (entity == null) {
+ throw new BusinessException("菜单权限项不存在");
+ }
+ return entity;
+ }
+
+ private AdminUserEntity getUserById(Long userId) {
+ AdminUserEntity entity = adminUserMapper.selectById(userId);
+ if (entity == null) {
+ throw new BusinessException("用户不存在");
+ }
+ return entity;
+ }
+
+ private boolean isSuperAdmin(AdminUserEntity user) {
+ return user != null && "super_admin".equalsIgnoreCase(normalizeRequired(user.getRole(), ""));
+ }
+
+ private void ensureUniqueColumnKey(String columnKey, Long excludeId) {
+ PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper()
+ .eq(PermissionMenuEntity::getColumnKey, columnKey)
+ .last("LIMIT 1"));
+ if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) {
+ throw new BusinessException("菜单标识已存在");
+ }
+ }
+
+ private String normalizeRequired(String value, String message) {
+ String normalized = value == null ? "" : value.trim();
+ if (normalized.isEmpty() && !message.isEmpty()) {
+ throw new BusinessException(message);
+ }
+ return normalized;
+ }
+
+ private boolean isValidMenuType(String menuType) {
+ return normalizeMenuType(menuType) != null;
+ }
+
+ private String normalizeMenuTypeRequired(String menuType) {
+ String normalized = normalizeMenuType(menuType);
+ if (normalized == null) {
+ throw new BusinessException("菜单类型仅支持 app 或 admin");
+ }
+ return normalized;
+ }
+
+ private String normalizeMenuType(String menuType) {
+ String normalized = menuType == null ? "" : menuType.trim().toLowerCase(Locale.ROOT);
+ if (normalized.isEmpty()) {
+ return null;
+ }
+ if (MENU_TYPE_APP.equals(normalized) || MENU_TYPE_ADMIN.equals(normalized)) {
+ return normalized;
+ }
+ return null;
+ }
+
+ private List normalizeColumnIds(List columnIds) {
+ if (columnIds == null || columnIds.isEmpty()) {
+ return List.of();
+ }
+ Set uniqueIds = new LinkedHashSet<>();
+ for (Long columnId : columnIds) {
+ if (columnId != null && columnId > 0) {
+ uniqueIds.add(columnId);
+ }
+ }
+ return new ArrayList<>(uniqueIds);
+ }
+
+ private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity) {
+ PermissionMenuItemVo vo = new PermissionMenuItemVo();
+ vo.setId(entity.getId());
+ vo.setName(entity.getName());
+ vo.setColumnKey(entity.getColumnKey());
+ vo.setMenuType(entity.getMenuType());
+ vo.setRoutePath(entity.getRoutePath());
+ vo.setCreatedAt(entity.getCreatedAt());
+ return vo;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java
index 17be534..e401ccb 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java
@@ -26,6 +26,8 @@ import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
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;
@@ -36,8 +38,6 @@ 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 org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
import java.io.InputStream;
import java.net.URI;
@@ -50,214 +50,131 @@ import java.util.List;
@RequestMapping("/api/product-risk-resolve")
@Tag(
name = "商品风险解决",
- description = "亚马逊商品风险处理:备选店铺、紫鸟匹配、创建任务、Python 队列与回传、生成 zip。"
- + "查询类接口需带 Query 参数 user_id(与登录用户一致)。")
+ description = "亚马逊商品风险处理:备选店铺、紫鸟匹配、创建任务、Python 队列与回传、生成 zip。查询类接口需要携带 Query 参数 user_id。")
public class ProductRiskResolveController {
private final ProductRiskResolveService productRiskResolveService;
private final ProductRiskTaskService productRiskTaskService;
@GetMapping("/candidates")
- @Operation(
- summary = "查询备选店铺列表",
- description = "返回当前用户在「商品风险」模块中已保存的备选店铺,按创建时间倒序。用于前端勾选后再调用匹配接口。")
+ @Operation(summary = "查询备选店铺列表", description = "返回当前用户在商品风险模块中已保存的备选店铺。")
public ApiResponse> listCandidates(
- @Parameter(
- name = "user_id",
- description = "当前用户 ID,仅返回该用户下的备选店铺",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
return ApiResponse.success(productRiskResolveService.listCandidates(userId));
}
@PostMapping("/candidates")
- @Operation(
- summary = "新增备选店铺",
- description = "将店铺名写入用户备选表;店铺名会规范化去重。仅用于前端勾选与匹配流程,与任务/结果表无强绑定。")
+ @Operation(summary = "新增备选店铺", description = "将店铺名写入用户备选表,用于前端勾选和匹配流程。")
public ApiResponse addCandidate(@Valid @RequestBody ProductRiskCandidateAddRequest request) {
return ApiResponse.success(productRiskResolveService.addCandidate(request));
}
@DeleteMapping("/candidates/{id}")
- @Operation(
- summary = "删除备选店铺",
- description = "按主键删除一条备选记录;`id` 必须属于当前 `user_id`,否则报错。")
+ @Operation(summary = "删除备选店铺", description = "删除一条备选记录,id 必须属于当前 user_id。")
public ApiResponse deleteCandidate(
- @Parameter(description = "备选店铺记录主键(biz_product_risk_shop_candidate.id)", example = "10")
- @PathVariable Long id,
- @Parameter(
- name = "user_id",
- description = "当前用户 ID,用于校验数据归属",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(description = "备选店铺记录主键", example = "10") @PathVariable Long id,
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
productRiskResolveService.deleteCandidate(userId, id);
return ApiResponse.success(null);
}
@GetMapping("/country-preference")
- @Operation(
- summary = "查询用户五国处理顺序",
- description = "返回当前用户已保存的国家代码列表(顺序即处理顺序);未保存时返回默认:DE、UK、FR、IT、ES(全选)。")
+ @Operation(summary = "查询国家处理顺序", description = "返回当前用户保存的国家代码列表,顺序即处理顺序。")
public ApiResponse getCountryPreference(
- @Parameter(
- name = "user_id",
- description = "当前用户 ID",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
return ApiResponse.success(productRiskResolveService.getCountryPreference(userId));
}
@PutMapping("/country-preference")
- @Operation(
- summary = "保存用户五国处理顺序",
- description = "写入 biz_product_risk_country_pref;country_codes 为 ProductRiskCountryCode 枚举名,至少 1 个、无重复。")
+ @Operation(summary = "保存国家处理顺序", description = "保存当前用户的国家勾选与处理顺序。")
public ApiResponse saveCountryPreference(
@Valid @RequestBody ProductRiskCountryPreferenceSaveRequest request) {
return ApiResponse.success(productRiskResolveService.saveCountryPreference(request));
}
@PostMapping("/match-shops")
- @Operation(
- summary = "批量匹配店铺(紫鸟索引)",
- description = "按店名查紫鸟索引,返回 shopId、platform、companyName、matchStatus 等;items 可作队列 data.items。"
- + "未命中时 matched=false,不可创建任务。")
+ @Operation(summary = "批量匹配店铺", description = "按店名查询紫鸟索引,返回 shopId、platform、companyName、matchStatus 等。")
public ApiResponse matchShops(@Valid @RequestBody ProductRiskMatchShopsRequest request) {
return ApiResponse.success(productRiskResolveService.matchShops(request));
}
@GetMapping("/dashboard")
- @Operation(
- summary = "统计看板",
- description = "汇总当前用户:备选店铺数量;商品风险模块下已结束任务数(SUCCESS/FAILED);其中成功任务数、失败任务数。")
+ @Operation(summary = "统计看板", description = "返回候选店铺数量、已结束任务数、成功任务数和失败任务数。")
public ApiResponse dashboard(
- @Parameter(
- name = "user_id",
- description = "当前用户 ID",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
return ApiResponse.success(productRiskTaskService.dashboard(userId));
}
@GetMapping("/history")
- @Operation(
- summary = "处理记录列表(含进行中与已结束)",
- description = "返回当前用户商品风险模块下各店结果行(biz_file_result),按创建时间倒序最多 100 条;"
- + "含 resultId、taskId、店名、任务状态、success、错误、输出文件名等。")
+ @Operation(summary = "处理记录列表", description = "返回当前用户商品风险模块下各店结果行,含运行中与历史记录。")
public ApiResponse history(
- @Parameter(
- name = "user_id",
- description = "当前用户 ID",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
return ApiResponse.success(productRiskTaskService.listHistory(userId));
}
@DeleteMapping("/history/{resultId}")
- @Operation(
- summary = "删除单条店铺结果记录",
- description = "删除一条 biz_file_result(须为本模块且归属 user_id);随后重算父任务,无子结果则删任务。")
+ @Operation(summary = "删除单条店铺结果记录", description = "删除一条 biz_file_result,并在后端同步重算父任务状态。")
public ApiResponse deleteHistory(
- @Parameter(description = "结果行主键 biz_file_result.id", example = "1001")
- @PathVariable Long resultId,
- @Parameter(
- name = "user_id",
- description = "当前用户 ID,用于校验该结果归属",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(description = "结果行主键 biz_file_result.id", example = "1001") @PathVariable Long resultId,
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
productRiskTaskService.deleteHistory(resultId, userId);
return ApiResponse.success(null);
}
@PostMapping("/tasks")
- @Operation(
- summary = "创建商品风险处理任务",
- description = "推 Python 队列前调用:落库 RUNNING 任务及各店 biz_file_result;响应 taskId 写入队列 data.taskId,"
- + "items 含各店 resultId。请求 items 须全为 matched=true,店名会去重。")
+ @Operation(summary = "创建商品风险处理任务", description = "落库 RUNNING 任务及各店占位结果,返回 taskId 与 items。")
public ApiResponse createTask(@Valid @RequestBody ProductRiskCreateTaskRequest request) {
return ApiResponse.success(productRiskTaskService.createTask(request));
}
@DeleteMapping("/tasks/{taskId}")
- @Operation(
- summary = "删除整条任务",
- description = "删除该任务及下属全部结果行(RUNNING/SUCCESS/FAILED 均可);user_id 须与任务归属一致。")
+ @Operation(summary = "删除整条任务", description = "删除该任务及其下属全部结果行,RUNNING/SUCCESS/FAILED 均可。")
public ApiResponse deleteTask(
- @Parameter(description = "任务主键 biz_file_task.id", example = "200")
- @PathVariable Long taskId,
- @Parameter(
- name = "user_id",
- description = "当前用户 ID,须与任务归属一致",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(description = "任务主键 biz_file_task.id", example = "200") @PathVariable Long taskId,
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId) {
productRiskTaskService.deleteTask(taskId, userId);
return ApiResponse.success(null);
}
@DeleteMapping("/pending-shop-result")
- @Operation(
- summary = "按店铺名删除运行中任务下的一条结果",
- description = "仅在 RUNNING 任务下按规范化店名删一条 biz_file_result 并重算任务;无匹配时 removed=false。"
- + "用于前端从匹配列表移除店铺时同步后端占位。")
+ @Operation(summary = "按店铺名删除运行中结果", description = "仅在 RUNNING 任务下按规范化店名删除一条 biz_file_result,并重算任务。")
public ApiResponse deletePendingShopResult(
- @Parameter(
- name = "user_id",
- description = "当前用户 ID",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId,
- @Parameter(
- name = "shop_name",
- description = "店铺名称(与匹配/创建任务时一致;服务端会按紫鸟规则规范化后再与库中 source_filename 比对)",
- required = true,
- in = ParameterIn.QUERY,
- example = "某某店铺")
+ @Parameter(name = "shop_name", description = "店铺名称", required = true, in = ParameterIn.QUERY, example = "某某店铺")
@RequestParam("shop_name") String shopName) {
return ApiResponse.success(productRiskTaskService.deletePendingShopResult(userId, shopName));
}
@PostMapping("/tasks/batch")
- @Operation(
- summary = "批量查询任务详情(轮询)",
- description = "按 taskIds 返回任务概要及各店结果;无效 id 记入 missingTaskIds。供前端轮询 RUNNING 至结束。")
+ @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概览与各店结果,供前端轮询使用。")
public ApiResponse tasksBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) {
return ApiResponse.success(productRiskTaskService.getTaskDetailsBatch(request.getTaskIds()));
}
@PostMapping("/tasks/{taskId}/result")
@Operation(
- summary = "Python 回传处理结果(可多次、可分批)",
- description = "Python 调用;同一 taskId 可多次,未出现在 shops 中的店保持待处理。"
- + "有 error 则标店失败;否则按 countries(键为五国枚举 DE/FR/ES/IT/UK)生成 xlsx/zip 上传 OSS,"
- + "Excel 内仍为中文工作表名。全部店终态后任务 SUCCESS/FAILED。")
+ summary = "Python 回传处理结果",
+ description = "同一 taskId 可多次回传。成功时按 countries 生成 xlsx/zip 并上传 OSS,全部店铺终态后任务进入 SUCCESS/FAILED。")
public ApiResponse submitResult(
- @Parameter(description = "任务主键,须为 RUNNING 状态", example = "200")
- @PathVariable Long taskId,
+ @Parameter(description = "任务主键,需处于 RUNNING 状态", example = "200") @PathVariable Long taskId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(
- description = "按店铺回传:成功时 `countries` 的 key 为枚举 ProductRiskCountryCode(JSON 与枚举名一致:DE、FR、ES、IT、UK);"
- + "失败时填 `error`,可不传 `countries`",
+ description = "按店铺回传结果;失败时填写 error,成功时填写 countries。",
required = true,
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ProductRiskSubmitResultRequest.class),
examples = {
@ExampleObject(
- name = "成功(单店,五国含样例行)",
- summary = "DE、UK 各一行,其余国可为空数组",
+ name = "成功示例",
+ summary = "DE、UK 各一行,其余国家可为空数组",
value = """
{
"shops": [
@@ -269,7 +186,7 @@ public class ProductRiskResolveController {
"shopName": "模拟旗舰店A",
"productAsinSku": "B0DEMO1234",
"status": "风险待解除",
- "done": "否",
+ "done": true,
"removeAsin": "B0OLD5678",
"removeStatus": "排队中"
}
@@ -282,7 +199,7 @@ public class ProductRiskResolveController {
"shopName": "模拟旗舰店A",
"productAsinSku": "B0UKDEMO99",
"status": "正常",
- "done": "是",
+ "done": true,
"removeAsin": "",
"removeStatus": ""
}
@@ -293,7 +210,7 @@ public class ProductRiskResolveController {
}
"""),
@ExampleObject(
- name = "失败(单店仅 error)",
+ name = "失败示例",
summary = "该店标记失败,不生成 zip",
value = """
{
@@ -312,18 +229,10 @@ public class ProductRiskResolveController {
}
@GetMapping("/results/{resultId}/download")
- @Operation(
- summary = "流式下载单个店铺的 zip 结果",
- description = "从 OSS 拉取 zip 以附件写入响应体(非 JSON);须归属 user_id;无文件则 404。")
+ @Operation(summary = "下载单个店铺的 zip 结果", description = "从 OSS 拉取 zip 并以附件流返回;需校验 user_id 归属。")
public void downloadResult(
- @Parameter(description = "店铺结果行主键 biz_file_result.id", example = "1001")
- @PathVariable Long resultId,
- @Parameter(
- name = "user_id",
- description = "当前用户 ID",
- required = true,
- in = ParameterIn.QUERY,
- example = "1")
+ @Parameter(description = "结果行主键 biz_file_result.id", example = "1001") @PathVariable Long resultId,
+ @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1")
@RequestParam("user_id") Long userId,
jakarta.servlet.http.HttpServletResponse response) {
String url = productRiskTaskService.resolveResultDownloadUrl(resultId, userId);
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java
index fe24cc6..ef4448f 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java
@@ -201,11 +201,13 @@ public class ProductRiskTaskService {
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
return;
}
+ String oldStatus = task.getStatus();
List latest = fileResultMapper.selectList(new LambdaQueryWrapper()
.eq(FileResultEntity::getTaskId, taskId)
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
.orderByAsc(FileResultEntity::getId));
if (latest.isEmpty()) {
+ log.warn("[product-risk] reconcile delete empty taskId={} oldStatus={} -> deleting task", taskId, oldStatus);
fileTaskMapper.deleteById(taskId);
return;
}
@@ -255,6 +257,8 @@ public class ProductRiskTaskService {
log.warn("[product-risk] compact result json failed: {}", ex.getMessage());
}
fileTaskMapper.updateById(task);
+ log.warn("[product-risk] reconcile status changed taskId={} oldStatus={} newStatus={} ok={} fail={} allDone={} errorMessage={}",
+ taskId, oldStatus, task.getStatus(), ok, fail, allDone, task.getErrorMessage());
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
productRiskTaskCacheService.deleteTaskCache(taskId);
@@ -384,8 +388,11 @@ public class ProductRiskTaskService {
throw new BusinessException("任务不存在");
}
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
+ log.warn("[product-risk] submitResult rejected taskId={} status={} payloadShopCount={}",
+ taskId, task.getStatus(), request.getShops() == null ? 0 : request.getShops().size());
throw new BusinessException("任务已结束,拒绝重复提交");
}
+ String oldStatus = task.getStatus();
List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper()
.eq(FileResultEntity::getTaskId, taskId)
@@ -525,6 +532,9 @@ public class ProductRiskTaskService {
log.warn("[product-risk] compact result json failed: {}", ex.getMessage());
}
fileTaskMapper.updateById(task);
+ log.warn("[product-risk] submitResult status evaluated taskId={} oldStatus={} newStatus={} ok={} fail={} allDone={} matchedShopCount={} skippedUnmatchedCount={} waitingCount={} assembledCount={} fallbackMatchedCount={} batchErrors={}",
+ taskId, oldStatus, task.getStatus(), ok, fail, allDone, matchedShopCount, skippedUnmatchedCount,
+ waitingCount, assembledCount, fallbackMatchedCount, batchErrors);
}
@Transactional
@@ -537,8 +547,11 @@ public class ProductRiskTaskService {
return false;
}
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
+ log.warn("[product-risk] stale finalize skipped taskId={} status={} fromCompensation={}",
+ taskId, task.getStatus(), fromCompensation);
return true;
}
+ String oldStatus = task.getStatus();
List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper()
.eq(FileResultEntity::getTaskId, taskId)
@@ -620,6 +633,8 @@ public class ProductRiskTaskService {
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
.orderByAsc(FileResultEntity::getId));
updateTaskStatusFromLatestRows(task, latest, batchErrors);
+ log.warn("[product-risk] stale finalize status evaluated taskId={} oldStatus={} newStatus={} changed={} cachedPayloadCount={} fromCompensation={} batchErrors={}",
+ taskId, oldStatus, task.getStatus(), changed, cachedPayloadByShop.size(), fromCompensation, batchErrors);
return true;
}
@@ -677,6 +692,7 @@ public class ProductRiskTaskService {
private void updateTaskStatusFromLatestRows(FileTaskEntity task,
List latest,
List batchErrors) {
+ String oldStatus = task.getStatus();
int ok = 0;
int fail = 0;
List allErrors = new ArrayList<>();
@@ -721,6 +737,8 @@ public class ProductRiskTaskService {
log.warn("[product-risk] compact result json failed: {}", ex.getMessage());
}
fileTaskMapper.updateById(task);
+ log.warn("[product-risk] status updated from latest rows taskId={} oldStatus={} newStatus={} ok={} fail={} allDone={} batchErrors={} errorMessage={}",
+ task.getId(), oldStatus, task.getStatus(), ok, fail, allDone, batchErrors, task.getErrorMessage());
}
private ProductRiskTaskDetailVo buildTaskDetail(FileTaskEntity task) {
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java
index 8fcad42..dea5548 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java
@@ -61,7 +61,7 @@ public class ShopMatchTaskService {
public ProductRiskDashboardVo dashboard(Long userId) {
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
ProductRiskDashboardVo vo = new ProductRiskDashboardVo();
vo.setCandidateCount(candidateMapper.selectCount(new LambdaQueryWrapper()
@@ -86,7 +86,7 @@ public class ShopMatchTaskService {
public ProductRiskHistoryVo listHistory(Long userId) {
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
ProductRiskHistoryVo vo = new ProductRiskHistoryVo();
List entities = fileResultMapper.selectList(new LambdaQueryWrapper()
@@ -118,11 +118,11 @@ public class ShopMatchTaskService {
@Transactional
public void deleteHistory(Long resultId, Long userId) {
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
FileResultEntity entity = fileResultMapper.selectById(resultId);
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("记录不存在");
}
Long taskId = entity.getTaskId();
fileResultMapper.deleteById(resultId);
@@ -134,11 +134,11 @@ public class ShopMatchTaskService {
@Transactional
public void deleteTask(Long taskId, Long userId) {
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !MODULE_TYPE.equals(task.getModuleType()) || !userId.equals(task.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
fileResultMapper.delete(new LambdaQueryWrapper()
.eq(FileResultEntity::getTaskId, taskId)
@@ -186,10 +186,10 @@ public class ShopMatchTaskService {
public String resolveResultDownloadUrl(Long resultId, Long userId) {
FileResultEntity entity = fileResultMapper.selectById(resultId);
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("记录不存在");
}
if (entity.getResultFileUrl() == null || entity.getResultFileUrl().isBlank()) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl());
}
@@ -197,7 +197,7 @@ public class ShopMatchTaskService {
public String resolveResultDownloadFilename(Long resultId, Long userId) {
FileResultEntity entity = fileResultMapper.selectById(resultId);
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
return entity.getResultFilename() != null && !entity.getResultFilename().isBlank()
? entity.getResultFilename()
@@ -207,18 +207,18 @@ public class ShopMatchTaskService {
@Transactional
public ProductRiskCreateTaskVo createTask(ShopMatchCreateTaskRequest request) {
if (request.getUserId() == null || request.getUserId() <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
if (request.getItems() == null || request.getItems().isEmpty()) {
- throw new BusinessException("items 涓嶈兘涓虹┖");
+ throw new BusinessException("items 不能为空");
}
List uniqueItems = dedupeQueueItems(request.getItems());
if (uniqueItems.isEmpty()) {
- throw new BusinessException("items 涓嶈兘涓虹┖");
+ throw new BusinessException("items 不能为空");
}
for (ProductRiskShopQueueItemVo item : uniqueItems) {
if (item == null || !item.isMatched()) {
- throw new BusinessException("瀛樺湪鏈尮閰嶅簵閾猴紝鏃犳硶鍒涘缓浠诲姟");
+ throw new BusinessException("存在未匹配店铺,无法创建任务");
}
}
@@ -254,7 +254,7 @@ public class ShopMatchTaskService {
for (ProductRiskShopQueueItemVo item : uniqueItems) {
String normalized = ziniaoShopSwitchService.normalizeShopName(item.getShopName());
if (normalized.isBlank()) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务数据已失效,请刷新后重试");
}
FileResultEntity result = new FileResultEntity();
result.setTaskId(task.getId());
@@ -271,7 +271,7 @@ public class ShopMatchTaskService {
task.setRequestJson(objectMapper.writeValueAsString(persistedRequest));
task.setResultJson(objectMapper.writeValueAsString(snapshot));
} catch (Exception ex) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("task 不存在");
}
fileTaskMapper.updateById(task);
@@ -284,34 +284,34 @@ public class ShopMatchTaskService {
@Transactional
public void activateTask(Long taskId, Long userId, Integer stageIndex) {
if (taskId == null || taskId <= 0) {
- throw new BusinessException("taskId is invalid");
+ throw new BusinessException("taskId 不合法");
}
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
if (stageIndex == null || stageIndex < 0) {
- throw new BusinessException("stage_index is invalid");
+ throw new BusinessException("stage_index 不合法");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !MODULE_TYPE.equals(task.getModuleType()) || !userId.equals(task.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务状态不正确");
}
if (!"SCHEDULED".equals(task.getStatus())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务状态不正确");
}
- if (task.getScheduledAt() != null && LocalDateTime.now().isBefore(task.getScheduledAt())) {
- throw new BusinessException("鏈埌瀹氭椂鎵ц鏃堕棿");
+ if (task.getScheduledAt() != null && LocalDateTime.now().isBefore(task.getScheduledAt().minusSeconds(90))) {
+ throw new BusinessException("未到定时执行时间");
}
ShopMatchCreateTaskRequest state = parseTaskRequest(task);
int currentStageIndex = state.getCurrentStageIndex() == null ? 0 : state.getCurrentStageIndex();
if (currentStageIndex != stageIndex) {
- throw new BusinessException("褰撳墠杞宸插彉鍖栵紝璇峰埛鏂板悗閲嶈瘯");
+ throw new BusinessException("当前轮次已变化,请刷新后重试");
}
if (state.getScheduleTimes() == null || stageIndex >= state.getScheduleTimes().size()) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("轮次配置缺失");
}
state.setActiveStageIndex(stageIndex);
task.setStatus("RUNNING");
@@ -323,28 +323,28 @@ public class ShopMatchTaskService {
@Transactional
public void completeStage(Long taskId, Long userId, ShopMatchStageCompleteRequest request) {
if (taskId == null || taskId <= 0) {
- throw new BusinessException("taskId is invalid");
+ throw new BusinessException("taskId 不合法");
}
if (userId == null || userId <= 0) {
- throw new BusinessException("user_id is invalid");
+ throw new BusinessException("user_id 不合法");
}
if (request == null || request.getStageIndex() == null || request.getStageIndex() < 0) {
- throw new BusinessException("stage_index is invalid");
+ throw new BusinessException("stage_index 不合法");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !MODULE_TYPE.equals(task.getModuleType()) || !userId.equals(task.getUserId())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
if (!"RUNNING".equals(task.getStatus())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务状态不正确");
}
ShopMatchCreateTaskRequest state = parseTaskRequest(task);
if (state.getActiveStageIndex() == null || !state.getActiveStageIndex().equals(request.getStageIndex())) {
- throw new BusinessException("杞鐘舵€佷笉鍖归厤");
+ throw new BusinessException("轮次状态不匹配");
}
int nextIndex = request.getStageIndex() + 1;
if (state.getScheduleTimes() == null || nextIndex >= state.getScheduleTimes().size()) {
- throw new BusinessException("Current stage is already the final stage");
+ throw new BusinessException("当前轮次已经是最后一轮");
}
state.setCurrentStageIndex(nextIndex);
state.setActiveStageIndex(null);
@@ -360,18 +360,18 @@ public class ShopMatchTaskService {
@Transactional
public void submitResult(Long taskId, ShopMatchSubmitResultRequest request) {
if (taskId == null || taskId <= 0) {
- throw new BusinessException("taskId is invalid");
+ throw new BusinessException("taskId 不合法");
}
if (request == null || request.getShops() == null || request.getShops().isEmpty()) {
- throw new BusinessException("shops 涓嶈兘涓虹┖");
+ throw new BusinessException("shops 不能为空");
}
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("任务不存在");
}
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
- throw new BusinessException("浠诲姟宸茬粨鏉燂紝鎷掔粷閲嶅鎻愪氦");
+ throw new BusinessException("任务已结束,拒绝重复提交");
}
List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper()
@@ -408,7 +408,7 @@ public class ShopMatchTaskService {
continue;
}
if (countPayloadRows(merged) <= 0) {
- markResultFailed(result, "No result rows received for assembly");
+ markResultFailed(result, "未收到可用于组装的结果数据");
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
continue;
}
@@ -416,7 +416,7 @@ public class ShopMatchTaskService {
assembleShopResult(result, shopKey, merged, workRoot);
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
} catch (Exception ex) {
- markResultFailed(result, ex.getMessage() == null ? "assemble failed" : ex.getMessage());
+ markResultFailed(result, ex.getMessage() == null ? "结果组装失败" : ex.getMessage());
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
}
}
@@ -468,8 +468,8 @@ public class ShopMatchTaskService {
ShopMatchShopPayloadDto cachedPayload = shopKey == null ? null : cachedPayloadByShop.get(shopKey);
if (cachedPayload == null) {
- markResultFailed(result, "Python interrupted before this shop finished uploading results");
- batchErrors.add(shopKey + ": Python interrupted before this shop finished uploading results");
+ markResultFailed(result, "Python 在该店铺结果上传完成前中断");
+ batchErrors.add(shopKey + ": Python 在该店铺结果上传完成前中断");
changed = true;
continue;
}
@@ -483,7 +483,7 @@ public class ShopMatchTaskService {
}
if (countPayloadRows(cachedPayload) <= 0 && payloadHasAnyDoneTrue(cachedPayload)) {
- markResultFailed(result, "No result rows received for assembly");
+ markResultFailed(result, "未收到可用于组装的结果数据");
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
changed = true;
log.warn("[shop-match] stale finalize finished without data taskId={} shop={} fromCompensation={}",
@@ -492,8 +492,8 @@ public class ShopMatchTaskService {
}
if (countPayloadRows(cachedPayload) <= 0) {
- markResultFailed(result, "Python interrupted before any assembleable rows were uploaded");
- batchErrors.add(shopKey + ": Python interrupted before any assembleable rows were uploaded");
+ markResultFailed(result, "Python 在上传可组装结果前中断");
+ batchErrors.add(shopKey + ": Python 在上传可组装结果前中断");
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
changed = true;
continue;
@@ -506,7 +506,7 @@ public class ShopMatchTaskService {
log.warn("[shop-match] stale finalize assembled taskId={} shop={} fromCompensation={} completedFlag={}",
taskId, shopKey, fromCompensation, isShopPayloadCompleted(cachedPayload));
} catch (Exception ex) {
- String message = ex.getMessage() == null ? "assemble failed" : ex.getMessage();
+ String message = ex.getMessage() == null ? "结果组装失败" : ex.getMessage();
markResultFailed(result, message);
batchErrors.add(shopKey + ": " + message);
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
@@ -595,11 +595,11 @@ public class ShopMatchTaskService {
task.setFinishedAt(LocalDateTime.now());
} else if (ok > 0) {
task.setStatus("SUCCESS");
- task.setErrorMessage(String.join("; ", errors.isEmpty() ? batchErrors : errors));
+ task.setErrorMessage(String.join(";", errors.isEmpty() ? batchErrors : errors));
task.setFinishedAt(LocalDateTime.now());
} else {
task.setStatus("FAILED");
- task.setErrorMessage(errors.isEmpty() ? "all shops failed" : String.join("; ", errors));
+ task.setErrorMessage(errors.isEmpty() ? "全部店铺处理失败" : String.join(";", errors));
task.setFinishedAt(LocalDateTime.now());
}
try {
@@ -633,7 +633,7 @@ public class ShopMatchTaskService {
.orderByAsc(FileResultEntity::getId));
List items = new ArrayList<>();
for (FileResultEntity row : rows) {
- throw new BusinessException("Task request payload is missing");
+ items.add(toHistoryItemVo(row, taskStatus));
}
return items;
}
@@ -778,7 +778,7 @@ public class ShopMatchTaskService {
private ShopMatchCreateTaskRequest parseTaskRequest(FileTaskEntity task) {
ShopMatchCreateTaskRequest request = parseTaskRequestSilently(task);
if (request == null) {
- throw new BusinessException("浠诲姟閰嶇疆缂哄け");
+ throw new BusinessException("任务配置缺失");
}
if (request.getItems() == null) {
request.setItems(new ArrayList<>());
@@ -807,7 +807,7 @@ public class ShopMatchTaskService {
try {
task.setRequestJson(objectMapper.writeValueAsString(request));
} catch (Exception ex) {
- throw new BusinessException("Invalid request");
+ throw new BusinessException("序列化任务数据失败");
}
}
@@ -831,7 +831,7 @@ public class ShopMatchTaskService {
private List normalizeCountryCodes(List raw) {
if (raw == null || raw.isEmpty()) {
- throw new BusinessException("country_codes 涓嶈兘涓虹┖");
+ throw new BusinessException("country_codes 不能为空");
}
LinkedHashSet out = new LinkedHashSet<>();
for (String code : raw) {
@@ -842,12 +842,12 @@ public class ShopMatchTaskService {
try {
ProductRiskCountryCode.valueOf(normalized);
} catch (IllegalArgumentException ex) {
- throw new BusinessException("闈炴硶鍥藉浠g爜: " + code);
+ throw new BusinessException("非法国家代码: " + code);
}
out.add(normalized);
}
if (out.isEmpty()) {
- throw new BusinessException("country_codes 涓嶈兘涓虹┖");
+ throw new BusinessException("country_codes 不能为空");
}
return new ArrayList<>(out);
}
@@ -864,16 +864,16 @@ public class ShopMatchTaskService {
continue;
}
if (!time.isAfter(now)) {
- throw new BusinessException("schedule_times 蹇呴』鏅氫簬褰撳墠鏃堕棿");
+ throw new BusinessException("schedule_times 必须晚于当前时间");
}
if (previous != null && !time.isAfter(previous)) {
- throw new BusinessException("schedule_times 蹇呴』鎸夋椂闂撮€掑");
+ throw new BusinessException("schedule_times 必须按时间递增");
}
out.add(time);
previous = time;
}
if (out.isEmpty()) {
- throw new BusinessException("schedule_times 涓嶈兘涓虹┖");
+ throw new BusinessException("schedule_times 不能为空");
}
return out;
}
diff --git a/backend-java/src/main/resources/db/V20__columns_add_menu_type_and_route_path.sql b/backend-java/src/main/resources/db/V20__columns_add_menu_type_and_route_path.sql
new file mode 100644
index 0000000..0fadbea
--- /dev/null
+++ b/backend-java/src/main/resources/db/V20__columns_add_menu_type_and_route_path.sql
@@ -0,0 +1,9 @@
+ALTER TABLE `columns`
+ ADD COLUMN `menu_type` VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER `column_key`,
+ ADD COLUMN `route_path` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER `menu_type`;
+
+INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`)
+SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage'
+WHERE NOT EXISTS (
+ SELECT 1 FROM `columns` WHERE `column_key` = 'admin_shop_manage'
+);
diff --git a/backend/__pycache__/config.cpython-312.pyc b/backend/__pycache__/config.cpython-312.pyc
index 7003e12..02e3b90 100644
Binary files a/backend/__pycache__/config.cpython-312.pyc and b/backend/__pycache__/config.cpython-312.pyc differ
diff --git a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc
index 7f09ff3..df04bc0 100644
Binary files a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc and b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc differ
diff --git a/backend/blueprints/admin_api.py b/backend/blueprints/admin_api.py
index 5b00eb5..00694bb 100644
--- a/backend/blueprints/admin_api.py
+++ b/backend/blueprints/admin_api.py
@@ -70,6 +70,26 @@ def _proxy_backend_java(method, path, *, params=None, json_data=None, files=None
return data, None, 200
+def _format_permission_item(item):
+ return {
+ 'id': item.get('id'),
+ 'name': item.get('name') or '',
+ 'column_key': item.get('columnKey') or '',
+ 'menu_type': item.get('menuType') or 'app',
+ 'route_path': item.get('routePath') or '',
+ 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16],
+ }
+
+
+def _sync_user_column_permissions(user_id, column_ids):
+ _, error_response, status = _proxy_backend_java(
+ 'PUT',
+ f'/api/admin/permission-users/{user_id}/columns',
+ json_data={'columnIds': [int(x) for x in (column_ids or []) if str(x).isdigit()]},
+ )
+ return error_response, status
+
+
# ---------- 用户管理 ----------
@admin_api.route('/users')
@@ -155,6 +175,7 @@ def list_users():
'total': total,
'page': page,
'page_size': page_size,
+ 'current_user_id': session.get('user_id'),
'current_user_role': role,
'current_user_username': current_row.get('username') or '',
'admins': admins,
@@ -203,9 +224,7 @@ def create_user():
want_created_by = current_row['id']
is_admin = 1 if want_role in ('super_admin', 'admin') else 0
pwd_hash = generate_password_hash(password, method='pbkdf2:sha256')
- column_ids = data.get('column_ids')
- if column_ids is None:
- column_ids = []
+ column_ids = data.get('column_ids') or []
try:
conn = get_db()
with conn.cursor() as cur:
@@ -214,9 +233,11 @@ def create_user():
(username, pwd_hash, is_admin, want_role, want_created_by),
)
new_uid = cur.lastrowid
- _set_user_column_permissions(cur, new_uid, column_ids)
conn.commit()
conn.close()
+ error_response, status = _sync_user_column_permissions(new_uid, column_ids)
+ if error_response is not None:
+ return error_response, status
return jsonify({'success': True, 'msg': '用户创建成功'})
except pymysql.IntegrityError:
return jsonify({'success': False, 'error': '用户名已存在'})
@@ -270,10 +291,12 @@ def update_user(uid):
(is_admin, want_role, uid),
)
column_ids = data.get('column_ids')
- if column_ids is not None:
- _set_user_column_permissions(cur, uid, column_ids)
conn.commit()
conn.close()
+ if column_ids is not None:
+ error_response, status = _sync_user_column_permissions(uid, column_ids)
+ if error_response is not None:
+ return error_response, status
return jsonify({'success': True, 'msg': '更新成功'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@@ -388,156 +411,124 @@ def history():
@admin_api.route('/columns')
@admin_required
def list_columns():
- """获取栏目列表(用于栏目配置与用户权限选择)"""
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute(
- "SELECT id, name, column_key, created_at FROM columns ORDER BY id"
- )
- rows = cur.fetchall()
- conn.close()
- items = [
- {
- 'id': r['id'],
- 'name': r['name'] or '',
- 'column_key': r['column_key'] or '',
- 'created_at': r['created_at'].strftime('%Y-%m-%d %H:%M') if r.get('created_at') else '',
- }
- for r in rows
- ]
- return jsonify({'success': True, 'items': items})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ params = {}
+ menu_type = (request.args.get('menu_type') or '').strip()
+ if menu_type:
+ params['menuType'] = menu_type
+ result, error_response, status = _proxy_backend_java(
+ 'GET',
+ '/api/admin/permission-menus',
+ params=params or None,
+ )
+ if error_response is not None:
+ return error_response, status
+ return jsonify({'success': True, 'items': [_format_permission_item(item) for item in (result.get('data') or [])]})
@admin_api.route('/column', methods=['POST'])
@admin_required
def create_column():
- """新增栏目"""
data = request.get_json() or {}
name = (data.get('name') or '').strip()
column_key = (data.get('column_key') or '').strip()
+ menu_type = (data.get('menu_type') or 'app').strip() or 'app'
+ route_path = (data.get('route_path') or '').strip()
if not name:
return jsonify({'success': False, 'error': '栏目名不能为空'})
if not column_key:
return jsonify({'success': False, 'error': '栏目标识不能为空'})
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute(
- "INSERT INTO columns (name, column_key) VALUES (%s, %s)",
- (name, column_key),
- )
- cid = cur.lastrowid
- conn.commit()
- conn.close()
- return jsonify({'success': True, 'msg': '创建成功', 'id': cid})
- except pymysql.IntegrityError:
- return jsonify({'success': False, 'error': '栏目标识已存在'})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ if not route_path:
+ return jsonify({'success': False, 'error': '菜单路由不能为空'})
+ result, error_response, status = _proxy_backend_java(
+ 'POST',
+ '/api/admin/permission-menus',
+ json_data={
+ 'name': name,
+ 'columnKey': column_key,
+ 'menuType': menu_type,
+ 'routePath': route_path,
+ },
+ )
+ if error_response is not None:
+ return error_response, status
+ item = result.get('data') or {}
+ return jsonify({'success': True, 'msg': result.get('message') or '创建成功', 'id': item.get('id')})
@admin_api.route('/column/', methods=['PUT'])
@admin_required
def update_column(cid):
- """更新栏目"""
data = request.get_json() or {}
name = (data.get('name') or '').strip()
column_key = (data.get('column_key') or '').strip()
+ menu_type = (data.get('menu_type') or 'app').strip() or 'app'
+ route_path = (data.get('route_path') or '').strip()
if not name:
return jsonify({'success': False, 'error': '栏目名不能为空'})
if not column_key:
return jsonify({'success': False, 'error': '栏目标识不能为空'})
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute(
- "UPDATE columns SET name = %s, column_key = %s WHERE id = %s",
- (name, column_key, cid),
- )
- if cur.rowcount == 0:
- conn.close()
- return jsonify({'success': False, 'error': '栏目不存在'})
- conn.commit()
- conn.close()
- return jsonify({'success': True, 'msg': '更新成功'})
- except pymysql.IntegrityError:
- return jsonify({'success': False, 'error': '栏目标识已存在'})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ if not route_path:
+ return jsonify({'success': False, 'error': '菜单路由不能为空'})
+ result, error_response, status = _proxy_backend_java(
+ 'PUT',
+ f'/api/admin/permission-menus/{cid}',
+ json_data={
+ 'name': name,
+ 'columnKey': column_key,
+ 'menuType': menu_type,
+ 'routePath': route_path,
+ },
+ )
+ if error_response is not None:
+ return error_response, status
+ return jsonify({'success': True, 'msg': result.get('message') or '更新成功'})
@admin_api.route('/column/', methods=['DELETE'])
@admin_required
def delete_column(cid):
- """删除栏目(会同步删除用户栏目权限关联)"""
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute("DELETE FROM user_column_permission WHERE column_id = %s", (cid,))
- cur.execute("DELETE FROM columns WHERE id = %s", (cid,))
- if cur.rowcount == 0:
- conn.close()
- return jsonify({'success': False, 'error': '栏目不存在'})
- conn.commit()
- conn.close()
- return jsonify({'success': True, 'msg': '删除成功'})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ result, error_response, status = _proxy_backend_java(
+ 'DELETE',
+ f'/api/admin/permission-menus/{cid}',
+ )
+ if error_response is not None:
+ return error_response, status
+ return jsonify({'success': True, 'msg': result.get('message') or '删除成功'})
@admin_api.route('/user//columns')
@admin_required
def get_user_columns(uid):
- """获取某用户的栏目权限 ID 列表(编辑用户时回显)"""
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute(
- "SELECT column_id FROM user_column_permission WHERE user_id = %s",
- (uid,),
- )
- rows = cur.fetchall()
- conn.close()
- column_ids = [r['column_id'] for r in rows]
- return jsonify({'success': True, 'column_ids': column_ids})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ params = {}
+ menu_type = (request.args.get('menu_type') or '').strip()
+ if menu_type:
+ params['menuType'] = menu_type
+ result, error_response, status = _proxy_backend_java(
+ 'GET',
+ f'/api/admin/permission-users/{uid}/columns',
+ params=params or None,
+ )
+ if error_response is not None:
+ return error_response, status
+ payload = result.get('data') or {}
+ return jsonify({'success': True, 'column_ids': payload.get('columnIds') or []})
@admin_api.route('/user//column-permissions')
@admin_required
def get_user_column_permissions(uid):
- """根据用户获取其拥有的栏目权限详细信息"""
- try:
- conn = get_db()
- with conn.cursor() as cur:
- cur.execute(
- """
- SELECT c.id, c.name, c.column_key, c.created_at
- FROM user_column_permission ucp
- JOIN columns c ON c.id = ucp.column_id
- WHERE ucp.user_id = %s
- ORDER BY c.id
- """,
- (uid,),
- )
- rows = cur.fetchall()
- conn.close()
- items = [
- {
- 'id': r['id'],
- 'name': r['name'] or '',
- 'column_key': r['column_key'] or '',
- 'created_at': r['created_at'].strftime('%Y-%m-%d %H:%M') if r.get('created_at') else '',
- }
- for r in rows
- ]
- return jsonify({'success': True, 'items': items})
- except Exception as e:
- return jsonify({'success': False, 'error': str(e)})
+ params = {}
+ menu_type = (request.args.get('menu_type') or '').strip()
+ if menu_type:
+ params['menuType'] = menu_type
+ result, error_response, status = _proxy_backend_java(
+ 'GET',
+ f'/api/admin/permission-users/{uid}/column-permissions',
+ params=params or None,
+ )
+ if error_response is not None:
+ return error_response, status
+ return jsonify({'success': True, 'items': [_format_permission_item(item) for item in (result.get('data') or [])]})
def _set_user_column_permissions(cur, user_id, column_ids):
diff --git a/backend/config.py b/backend/config.py
index 97a3eb7..6692838 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -23,8 +23,8 @@ bucket_path = "nanri-image/"
file_url_pre = f"https://{bucket}.oss-cn-hangzhou.aliyuncs.com/"
import os
-backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://127.0.0.1:18080').rstrip('/')
-# backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://8.136.19.173:18080').rstrip('/')
+# backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://127.0.0.1:18080').rstrip('/')
+backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://8.136.19.173:18080').rstrip('/')
os.environ['OSS_ACCESS_KEY_ID'] = accessKeyId
os.environ['OSS_ACCESS_KEY_SECRET'] = accessKeySecret
os.environ['SECRET_KEY'] = "ddffc7c1d02121d9554d7b080b2511b6"
diff --git a/backend/utils/__pycache__/db.cpython-312.pyc b/backend/utils/__pycache__/db.cpython-312.pyc
index fef6ce0..74e0984 100644
Binary files a/backend/utils/__pycache__/db.cpython-312.pyc and b/backend/utils/__pycache__/db.cpython-312.pyc differ
diff --git a/backend/utils/db.py b/backend/utils/db.py
index bb156fd..0e72f51 100644
--- a/backend/utils/db.py
+++ b/backend/utils/db.py
@@ -114,6 +114,18 @@ def init_db():
UNIQUE KEY uk_column_key (column_key)
)
""")
+ try:
+ cur.execute("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key")
+ except Exception:
+ pass
+ try:
+ cur.execute("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type")
+ except Exception:
+ pass
+ try:
+ cur.execute("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''")
+ except Exception:
+ pass
cur.execute("""
CREATE TABLE IF NOT EXISTS user_column_permission (
user_id INT NOT NULL,
diff --git a/backend/web_source/admin.html b/backend/web_source/admin.html
index 6c27684..cfca98b 100644
--- a/backend/web_source/admin.html
+++ b/backend/web_source/admin.html
@@ -637,8 +637,11 @@
// ========== 用户管理 ==========
var userPage = 1, userPageSize = 15;
+ var currentUserId = null;
var currentUserRole = 'admin';
var currentUserUsername = '';
+ var currentUserAdminPermissionKeys = {};
+ var currentUserAdminPermissionRoutes = {};
var adminsList = [];
function roleLabel(role) {
if (role === 'super_admin') return '超级管理员';
@@ -663,6 +666,7 @@
tbody.innerHTML = '| 加载失败: ' + (res.error || '') + ' |
';
return;
}
+ currentUserId = res.current_user_id || null;
currentUserRole = res.current_user_role || 'admin';
currentUserUsername = (res.current_user_username || '').trim();
adminsList = res.admins || [];
@@ -683,6 +687,7 @@
updateCreateFormByRole();
updateUserFilterByRole();
updateDedupeTotalDataAccess();
+ loadCurrentUserAdminPermissions();
})
.catch(function() {
document.getElementById('userListBody').innerHTML = '| 请求失败 |
';
@@ -722,6 +727,50 @@
if (usersPanel) usersPanel.classList.add('active');
}
}
+ function updateShopManageAccess() {
+ var tab = document.querySelector('.tab[data-tab="shop-manage"]');
+ var panel = document.getElementById('panel-shop-manage');
+ if (!tab || !panel) return;
+ var canUse = currentUserRole === 'super_admin' ||
+ !!currentUserAdminPermissionKeys['admin_shop_manage'] ||
+ !!currentUserAdminPermissionRoutes['shop-manage'];
+ tab.style.display = canUse ? '' : 'none';
+ panel.style.display = canUse ? '' : 'none';
+ if (!canUse && tab.classList.contains('active')) {
+ tab.classList.remove('active');
+ panel.classList.remove('active');
+ var usersTab = document.querySelector('.tab[data-tab="users"]');
+ var usersPanel = document.getElementById('panel-users');
+ if (usersTab) usersTab.classList.add('active');
+ if (usersPanel) usersPanel.classList.add('active');
+ }
+ }
+ function loadCurrentUserAdminPermissions() {
+ currentUserAdminPermissionKeys = {};
+ currentUserAdminPermissionRoutes = {};
+ if (!currentUserId || currentUserRole === 'super_admin') {
+ updateShopManageAccess();
+ return;
+ }
+ fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin')
+ .then(function(r) { return r.json(); })
+ .then(function(res) {
+ if (!res.success) {
+ updateShopManageAccess();
+ return;
+ }
+ (res.items || []).forEach(function(item) {
+ var columnKey = (item.column_key || '').trim();
+ var routePath = (item.route_path || '').trim();
+ if (columnKey) currentUserAdminPermissionKeys[columnKey] = true;
+ if (routePath) currentUserAdminPermissionRoutes[routePath] = true;
+ });
+ updateShopManageAccess();
+ })
+ .catch(function() {
+ updateShopManageAccess();
+ });
+ }
var allColumnsList = [];
function loadColumnsForPermission() {
fetch('/api/admin/columns')
diff --git a/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue b/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue
index 4c37ee5..9e3f585 100644
--- a/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue
+++ b/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue
@@ -345,6 +345,29 @@ function removeSessionTaskFromStorage(taskId: number) {
}
}
+function isTerminalStatus(status?: string | null) {
+ return status === 'SUCCESS' || status === 'FAILED' || status === 'COMPLETED'
+}
+
+function pruneTerminalSessionTasksByHistory(items: DeleteBrandResultItem[]) {
+ if (!items?.length) return false
+ const terminalTaskIds = new Set()
+ items.forEach((item) => {
+ if (item.taskId && isTerminalStatus(item.taskStatus)) {
+ terminalTaskIds.add(item.taskId)
+ }
+ })
+ if (!terminalTaskIds.size) return false
+
+ const oldLen = sessionTasks.value.length
+ sessionTasks.value = sessionTasks.value.filter((task) => !terminalTaskIds.has(task.taskId))
+ if (sessionTasks.value.length !== oldLen) {
+ persistSessionTasks()
+ return true
+ }
+ return false
+}
+
const historySectionItems = computed(() =>
historyItems.value.filter(
@@ -681,7 +704,7 @@ function formatProgressPercent(item: DeleteBrandResultItem) {
function isTaskTerminal(taskId: number) {
const status = taskDetails.value[taskId]?.task?.status
- return status === 'SUCCESS' || status === 'FAILED'
+ return isTerminalStatus(status)
}
function getPollingTaskIds() {
@@ -1061,6 +1084,7 @@ async function loadHistory() {
try {
const response = await getDeleteBrandHistory()
historyItems.value = normalizeDeleteBrandItems(response.items || [])
+ pruneTerminalSessionTasksByHistory(historyItems.value)
syncResultState()
// 关键:页面加载历史后,立刻拉取详情触发状态机
diff --git a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue
index 2d52ca5..8284ef5 100644
--- a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue
+++ b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue
@@ -129,8 +129,11 @@ const pollTimer = ref(null)
const pollingInFlight = ref(false)
const dispatchTimers = new Map()
const scheduledDispatchInFlight = ref(false)
-const currentSectionItems = computed(() => uniqueTaskRows(historyItems.value.filter((item) => { const taskId = normalizeTaskId(item.taskId); return !!taskId && !isTaskTerminalById(taskId) }), taskSnapshots.value, 'current'))
-const historySectionItems = computed(() => uniqueTaskRows(historyItems.value.filter((item) => { const taskId = normalizeTaskId(item.taskId); return !taskId || isTaskTerminalById(taskId) }), taskSnapshots.value, 'history'))
+let scheduleHeartbeatTimer: number | null = null
+let lastScheduledErrorAt = 0
+let lastScheduledErrorKey = ''
+const currentSectionItems = computed(() => uniqueTaskRows(historyItems.value.filter((item) => { const taskId = normalizeTaskId(item.taskId); return !!taskId && !isTaskTerminalItem(item) }), taskSnapshots.value, 'current'))
+const historySectionItems = computed(() => uniqueTaskRows(historyItems.value.filter((item) => { const taskId = normalizeTaskId(item.taskId); return !taskId || isTaskTerminalItem(item) }), taskSnapshots.value, 'history'))
const hasVisibleList = computed(() => currentSectionItems.value.length > 0 || historySectionItems.value.length > 0)
const countryCheckboxRows = computed(() => { const selectedSet = new Set(orderedCountryCodes.value); return [...orderedCountryCodes.value.map((code) => ({ code, label: countryLabel(code) })), ...COUNTRY_OPTIONS.filter((item) => !selectedSet.has(item.code)).map((item) => ({ code: item.code, label: item.label }))] })
@@ -173,7 +176,14 @@ function addPollingTask(taskId: number) { if (!pollingTaskIds.value.includes(tas
function clearDispatchTimer(taskId: number) { const timer = dispatchTimers.get(taskId); if (timer) { window.clearTimeout(timer); dispatchTimers.delete(taskId) } }
function removePollingTask(taskId: number) { clearDispatchTimer(taskId); pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId); delete taskDetails.value[taskId]; savePollingIds(); saveTaskDetailsToStorage() }
function stopPollingTask(taskId: number, keepStatus = true) { pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId); if (!keepStatus) delete taskDetails.value[taskId]; savePollingIds(); saveTaskDetailsToStorage() }
-function isTaskTerminalById(taskId?: number) { if (!taskId) return false; const status = taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status; return status === 'SUCCESS' || status === 'FAILED' }
+function isTaskTerminalStatus(status?: string) { return status === 'SUCCESS' || status === 'FAILED' || status === 'COMPLETED' }
+function isTaskTerminalById(taskId?: number) { if (!taskId) return false; const status = taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status; return isTaskTerminalStatus(status) }
+function isTaskTerminalItem(item: ShopMatchHistoryItem) {
+ const taskId = normalizeTaskId(item.taskId)
+ if (taskId && isTaskTerminalById(taskId)) return true
+ if (isTaskTerminalStatus(item.taskStatus)) return true
+ return !!item.success
+}
async function loadCandidates() { candidates.value = await listShopMatchCandidates() }
async function loadDashboard() { dashboard.value = await getShopMatchDashboard() }
async function loadHistory() { const data = await getShopMatchHistory(); historyItems.value = data.items || [] }
@@ -201,33 +211,56 @@ function removeMatchedRowsLocally(rows: ShopMatchHistoryItem[] | ShopMatchShopQu
function parseScheduleValues() { if (!scheduleEnabled.value) return undefined; const values = schedulePickerValues.value.map((item) => item.trim()).filter(Boolean); if (!values.length) throw new Error('请至少选择一个执行时间'); const withTime = values.map((value) => { const normalized = normalizeScheduleValue(value); const date = resolveScheduleDateTime(normalized); if (!date) throw new Error(`时间格式无效: ${value}`); return { raw: formatScheduleDateTime(date), time: date.getTime() } }).sort((a, b) => a.time - b.time); for (let i = 1; i < withTime.length; i += 1) if (withTime[i].time === withTime[i - 1].time) throw new Error('执行时间不能重复'); return withTime.map((item) => item.raw) }
function buildQueuePayload(taskId: number, item: Pick, countryCodes: string[], stageIndex?: number, finalStage = true) { return { type: 'shop-match-run', ts: Date.now(), data: { taskId, user_id: currentUserId(), items: [{ shopName: item.shopName, shopId: item.shopId, platform: item.platform, companyName: item.companyName, matched: true, matchStatus: item.matchStatus, matchMessage: item.matchMessage }], country_codes: [...countryCodes], stage_index: stageIndex, final_stage: finalStage } } }
function nextScheduleStage(taskId: number) { const task = taskSnapshots.value[taskId]?.task; const stages = task?.scheduleStages || []; const currentStageIndex = task?.currentStageIndex; if (typeof currentStageIndex !== 'number') return null; const stage = stages.find((item) => item.stageIndex === currentStageIndex); if (!stage?.scheduledAt) return null; return { stageIndex: currentStageIndex, scheduledAt: stage.scheduledAt, finalStage: currentStageIndex === stages.length - 1 } }
-async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await activateShopMatchTask(taskId, stage.stageIndex); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已推送第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) }
+async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await activateShopMatchTask(taskId, stage.stageIndex); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; if (snapshot?.task) taskSnapshots.value = { ...taskSnapshots.value, [taskId]: { ...snapshot, task: { ...snapshot.task, status: 'RUNNING', activeStageIndex: stage.stageIndex } } }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已推送第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) }
function hasRunningTask() { return Object.values(taskDetails.value).some((status) => status === 'RUNNING') || Object.values(taskSnapshots.value).some((detail) => detail.task?.status === 'RUNNING') }
-function findNextReadyScheduledTask() { const taskIds = new Set(pollingTaskIds.value); for (const key of Object.keys(taskSnapshots.value)) { const id = normalizeTaskId(key); if (id > 0) taskIds.add(id) } for (const item of historyItems.value) { const id = normalizeTaskId(item.taskId); if (id > 0) taskIds.add(id) } const ready = Array.from(taskIds).map((taskId) => { const snapshot = taskSnapshots.value[taskId]; const taskStatus = snapshot?.task?.status || taskDetails.value[taskId]; const item = snapshot?.items?.[0] || historyItems.value.find((row) => normalizeTaskId(row.taskId) === taskId); const stage = nextScheduleStage(taskId); if (taskStatus !== 'SCHEDULED' || !item || !stage?.scheduledAt) return null; const scheduledTime = new Date(stage.scheduledAt).getTime(); if (!Number.isFinite(scheduledTime) || scheduledTime > Date.now()) return null; return { taskId, item, scheduledTime } }).filter((item): item is { taskId: number; item: ShopMatchHistoryItem; scheduledTime: number } => !!item); ready.sort((a, b) => a.scheduledTime - b.scheduledTime || a.taskId - b.taskId); return ready[0] || null }
-async function pumpScheduledQueue() { if (scheduledDispatchInFlight.value || hasRunningTask()) return; const readyTask = findNextReadyScheduledTask(); if (!readyTask) return; scheduledDispatchInFlight.value = true; try { await dispatchScheduledTask(readyTask.taskId, readyTask.item) } catch (error) { const message = error instanceof Error ? error.message : `任务 ${readyTask.taskId} 调度失败`; queuePushResult.value = message; ElMessage.error(message) } finally { scheduledDispatchInFlight.value = false } }
+function findNextReadyScheduledTask() { const taskIds = new Set(pollingTaskIds.value); for (const key of Object.keys(taskSnapshots.value)) { const id = normalizeTaskId(key); if (id > 0) taskIds.add(id) } for (const item of historyItems.value) { const id = normalizeTaskId(item.taskId); if (id > 0) taskIds.add(id) } const ready = Array.from(taskIds).map((taskId) => { const snapshot = taskSnapshots.value[taskId]; const taskStatus = taskDetails.value[taskId] || snapshot?.task?.status; const item = snapshot?.items?.[0] || historyItems.value.find((row) => normalizeTaskId(row.taskId) === taskId); const stage = nextScheduleStage(taskId); if (taskStatus !== 'SCHEDULED' || !item || !stage?.scheduledAt) return null; const scheduledTime = new Date(stage.scheduledAt).getTime(); if (!Number.isFinite(scheduledTime) || scheduledTime > Date.now()) return null; return { taskId, item, scheduledTime } }).filter((item): item is { taskId: number; item: ShopMatchHistoryItem; scheduledTime: number } => !!item); ready.sort((a, b) => a.scheduledTime - b.scheduledTime || a.taskId - b.taskId); return ready[0] || null }
+async function pumpScheduledQueue() { if (scheduledDispatchInFlight.value || hasRunningTask()) return; const readyTask = findNextReadyScheduledTask(); if (!readyTask) return; scheduledDispatchInFlight.value = true; try { await dispatchScheduledTask(readyTask.taskId, readyTask.item) } catch (error) { const message = error instanceof Error ? error.message : `任务 ${readyTask.taskId} 调度失败`; const key = `${readyTask.taskId}:${message}`; const now = Date.now(); queuePushResult.value = message; if (lastScheduledErrorKey !== key || now - lastScheduledErrorAt > 10000) { lastScheduledErrorKey = key; lastScheduledErrorAt = now; ElMessage.error(message) } await Promise.allSettled([loadHistory(), refreshTaskBatch()]) } finally { scheduledDispatchInFlight.value = false } }
function scheduleDispatch(taskId: number, scheduledAt?: string) { if (!scheduledAt) return; clearDispatchTimer(taskId); const time = new Date(scheduledAt).getTime(); if (!Number.isFinite(time)) return; const delay = Math.max(0, time - Date.now()); const timer = window.setTimeout(() => { dispatchTimers.delete(taskId); void pumpScheduledQueue() }, delay); dispatchTimers.set(taskId, timer) }
function restoreScheduledDispatches() { const taskIds = new Set(pollingTaskIds.value); for (const key of Object.keys(taskSnapshots.value)) { const id = normalizeTaskId(key); if (id > 0) taskIds.add(id) } for (const item of historyItems.value) { const id = normalizeTaskId(item.taskId); if (id > 0) taskIds.add(id) } for (const taskId of taskIds) { const snapshot = taskSnapshots.value[taskId]; const taskStatus = snapshot?.task?.status || taskDetails.value[taskId]; const stage = nextScheduleStage(taskId); if (taskStatus === 'SCHEDULED' && stage?.scheduledAt) scheduleDispatch(taskId, stage.scheduledAt); else clearDispatchTimer(taskId) } void pumpScheduledQueue() }
-async function refreshTaskBatch() { if (!pollingTaskIds.value.length) return { settledTaskIds: [] as number[] }; try { const batch = await getShopMatchTasksBatch(pollingTaskIds.value); const nextSnapshots = { ...taskSnapshots.value }; const settledTaskIds = new Set(); for (const missingId of batch.missingTaskIds || []) { removePollingTask(missingId); delete nextSnapshots[missingId] } for (const detail of batch.items || []) { const taskId = detail.task?.id; if (!taskId) continue; nextSnapshots[taskId] = detail; const status = detail.task?.status || ''; if (!status) continue; taskDetails.value[taskId] = status; if (status === 'SUCCESS' || status === 'FAILED') { removePollingTask(taskId); settledTaskIds.add(taskId); continue } if (status === 'SCHEDULED') { stopPollingTask(taskId); settledTaskIds.add(taskId) } } taskSnapshots.value = nextSnapshots; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); restoreScheduledDispatches(); return { settledTaskIds: Array.from(settledTaskIds) } } catch { return { settledTaskIds: [] as number[] } } }
+function startScheduleHeartbeat() { if (scheduleHeartbeatTimer) return; scheduleHeartbeatTimer = window.setInterval(() => { void pumpScheduledQueue() }, 1000) }
+function stopScheduleHeartbeat() { if (!scheduleHeartbeatTimer) return; window.clearInterval(scheduleHeartbeatTimer); scheduleHeartbeatTimer = null }
+function handleScheduleRecovery() { restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) }
+async function refreshTaskBatch() { if (!pollingTaskIds.value.length) return { settledTaskIds: [] as number[] }; try { const batch = await getShopMatchTasksBatch(pollingTaskIds.value); const nextSnapshots = { ...taskSnapshots.value }; const settledTaskIds = new Set(); for (const missingId of batch.missingTaskIds || []) { removePollingTask(missingId); delete nextSnapshots[missingId] } for (const detail of batch.items || []) { const taskId = detail.task?.id; if (!taskId) continue; nextSnapshots[taskId] = detail; const status = detail.task?.status || ''; if (!status) continue; taskDetails.value[taskId] = status; if (isTaskTerminalStatus(status)) { removePollingTask(taskId); settledTaskIds.add(taskId); continue } if (status === 'SCHEDULED') { stopPollingTask(taskId); settledTaskIds.add(taskId) } } taskSnapshots.value = nextSnapshots; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); restoreScheduledDispatches(); return { settledTaskIds: Array.from(settledTaskIds) } } catch { return { settledTaskIds: [] as number[] } } }
function getPollIntervalMs() { return document.visibilityState === 'visible' ? 4000 : 10000 }
function scheduleNextPoll(immediate = false) { if (pollTimer.value) { if (!immediate) return; window.clearTimeout(pollTimer.value); pollTimer.value = null } const run = async () => { pollTimer.value = null; if (pollingInFlight.value || !pollingTaskIds.value.length) { if (pollingTaskIds.value.length) scheduleNextPoll(); return } pollingInFlight.value = true; try { const { settledTaskIds } = await refreshTaskBatch(); if (settledTaskIds.length) await Promise.allSettled([loadHistory(), loadDashboard()]) } finally { pollingInFlight.value = false } if (pollingTaskIds.value.length) pollTimer.value = window.setTimeout(run, getPollIntervalMs()) }; if (immediate) void run(); else pollTimer.value = window.setTimeout(run, getPollIntervalMs()) }
function ensurePolling(immediate = false) { scheduleNextPoll(immediate) }
function stopPolling() { if (pollTimer.value) { window.clearTimeout(pollTimer.value); pollTimer.value = null } }
-async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (status === 'SUCCESS' || status === 'FAILED') { removePollingTask(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } }
+async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } }
function resolvedTaskStatus(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); if (!taskId) return item.taskStatus || ''; return taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status || item.taskStatus || '' }
function taskSnapshotOf(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); return taskId ? taskSnapshots.value[taskId] : undefined }
function currentTaskStageText(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (!stages.length) return ''; const total = stages.length; const activeIndex = typeof task?.activeStageIndex === 'number' ? task.activeStageIndex : undefined; const currentIndex = typeof task?.currentStageIndex === 'number' ? task.currentStageIndex : undefined; if (typeof activeIndex === 'number') return `执行进度: 第 ${activeIndex + 1}/${total} 次执行中`; if (typeof currentIndex === 'number') return `执行进度: 等待第 ${currentIndex + 1}/${total} 次`; return `执行进度: 共 ${total} 次`}
function nextScheduledDisplay(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (typeof task?.currentStageIndex === 'number') { const stage = stages.find((entry) => entry.stageIndex === task.currentStageIndex); if (stage?.scheduledAt) return formatTimeOnly(stage.scheduledAt) } if (item.scheduledAt) return formatTimeOnly(item.scheduledAt); return '' }
-function statusText(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); if (status === 'SCHEDULED') return '待执行'; if (status === 'RUNNING') return '执行中'; if (status === 'SUCCESS') return '已完成'; if (status === 'FAILED') return '失败'; return item.success ? '已完成' : '未知' }
-function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return status === 'SUCCESS' ? 'success' : status === 'FAILED' ? 'failed' : 'running' }
-function canDownload(item: ShopMatchHistoryItem) { return !!item.resultId && !!item.downloadUrl && resolvedTaskStatus(item) === 'SUCCESS' }
+function statusText(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); if (status === 'SCHEDULED') return '待执行'; if (status === 'RUNNING') return '执行中'; if (status === 'SUCCESS' || status === 'COMPLETED') return '已完成'; if (status === 'FAILED') return '失败'; return item.success ? '已完成' : '未知' }
+function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return status === 'SUCCESS' || status === 'COMPLETED' ? 'success' : status === 'FAILED' ? 'failed' : 'running' }
+function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && !!item.downloadUrl && (status === 'SUCCESS' || status === 'COMPLETED') }
async function downloadResult(item: ShopMatchHistoryItem) { if (!item.resultId) return; const api = getPywebviewApi(); if (!api?.save_file_from_url_new) { ElMessage.error('当前客户端未提供下载能力'); return } const url = getShopMatchResultDownloadUrl(item.resultId); const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx`; const result = await api.save_file_from_url_new(url, filename); if (result.success) ElMessage.success(`已保存: ${result.path || filename}`); else if (result.error && result.error !== '用户取消') ElMessage.error(result.error) }
-async function deleteTaskRecord(item: ShopMatchHistoryItem) { try { if (item.resultId) await deleteShopMatchHistory(item.resultId); else if (item.taskId) { await deleteShopMatchTask(item.taskId); removePollingTask(item.taskId) } await loadHistory(); await loadCandidates(); await loadDashboard() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '删除失败') } }
+async function deleteTaskRecord(item: ShopMatchHistoryItem) {
+ const taskId = normalizeTaskId(item.taskId)
+ const resultId = Number(item.resultId || 0)
+ try {
+ if (taskId > 0) {
+ await deleteShopMatchTask(taskId)
+ removePollingTask(taskId)
+ historyItems.value = historyItems.value.filter((row) => normalizeTaskId(row.taskId) !== taskId)
+ delete taskSnapshots.value[taskId]
+ saveTaskSnapshotsToStorage()
+ } else if (resultId > 0) {
+ await deleteShopMatchHistory(resultId)
+ historyItems.value = historyItems.value.filter((row) => Number(row.resultId || 0) !== resultId)
+ } else {
+ throw new Error('缺少可删除的任务标识')
+ }
+ await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()])
+ } catch (error) {
+ ElMessage.error(error instanceof Error ? error.message : '删除失败')
+ }
+}
function formatMatchStatus(status?: string) { const value = (status || '').trim(); return { MATCHED: '已匹配', PENDING: '待匹配', CONFLICT: '需人工确认', INDEX_STALE: '索引过期' }[value] || value || '—' }
function formatMatchRemark(row: ShopMatchShopQueueItem) { const message = (row.matchMessage || '').trim(); if (message) return message; if (row.matched && row.matchStatus === 'MATCHED') return '紫鸟索引已命中,可推送队列'; if (row.matched) return '已关联索引,请结合状态列查看是否可推送'; return '未命中或未就绪,请检查店铺名与索引刷新' }
-async function pushToPythonQueue() { const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } pushing.value = true; queuePayloadText.value = ''; try { for (let index = 0; index < matched.length; index += 1) { const item = matched[index]; const created = await createShopMatchTask([item], orderedCountryCodes.value, scheduleValues); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) continue; if (scheduleValues?.length) { scheduleDispatch(taskId, scheduleValues[0]); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = matched.length > 1 ? `任务 ${taskId} 已入队,等待完成后继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已入队,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { throw new Error(`任务 ${taskId} 执行失败,已停止后续店铺推送`) } queuePushResult.value = index + 1 < matched.length ? `任务 ${taskId} 已完成,继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已完成` } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); ElMessage.success(scheduleValues?.length ? '定时任务已创建,后续会按时间串行推入 Python 队列' : `已按顺序完成 ${matched.length} 条店铺推送`) } catch (error) { const message = error instanceof Error ? error.message : '推送失败'; queuePushResult.value = message; ElMessage.error(message) } finally { pushing.value = false } }
+async function pushToPythonQueue() { const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } pushing.value = true; queuePayloadText.value = ''; try { for (let index = 0; index < matched.length; index += 1) { const item = matched[index]; const created = await createShopMatchTask([item], orderedCountryCodes.value, scheduleValues); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) continue; if (scheduleValues?.length) { restoreScheduledDispatches(); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = matched.length > 1 ? `任务 ${taskId} 已入队,等待完成后继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已入队,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { throw new Error(`任务 ${taskId} 执行失败,已停止后续店铺推送`) } queuePushResult.value = index + 1 < matched.length ? `任务 ${taskId} 已完成,继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已完成` } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); ElMessage.success(scheduleValues?.length ? '定时任务已创建,后续会按时间串行推入 Python 队列' : `已按顺序完成 ${matched.length} 条店铺推送`) } catch (error) { const message = error instanceof Error ? error.message : '推送失败'; queuePushResult.value = message; ElMessage.error(message) } finally { pushing.value = false } }
-onMounted(async () => { loadPollingIdsFromStorage(); loadTaskDetailsFromStorage(); loadTaskSnapshotsFromStorage(); loadMatchedItemsFromStorage(); syncPollingIdsWithTaskState(); await Promise.allSettled([loadCandidates(), loadCountryPreference(), loadHistory(), loadDashboard()]); restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) })
-onUnmounted(() => { stopPolling(); if (countryPrefSaveTimer) clearTimeout(countryPrefSaveTimer); for (const timer of dispatchTimers.values()) window.clearTimeout(timer); dispatchTimers.clear() })
+onMounted(async () => { loadPollingIdsFromStorage(); loadTaskDetailsFromStorage(); loadTaskSnapshotsFromStorage(); loadMatchedItemsFromStorage(); syncPollingIdsWithTaskState(); await Promise.allSettled([loadCandidates(), loadCountryPreference(), loadHistory(), loadDashboard()]); startScheduleHeartbeat(); window.addEventListener('focus', handleScheduleRecovery); document.addEventListener('visibilitychange', handleScheduleRecovery); restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) })
+onUnmounted(() => { stopPolling(); stopScheduleHeartbeat(); window.removeEventListener('focus', handleScheduleRecovery); document.removeEventListener('visibilitychange', handleScheduleRecovery); if (countryPrefSaveTimer) clearTimeout(countryPrefSaveTimer); for (const timer of dispatchTimers.values()) window.clearTimeout(timer); dispatchTimers.clear() })