diff --git a/app/.env b/app/.env index 085b36a..856e41a 100644 --- a/app/.env +++ b/app/.env @@ -12,7 +12,7 @@ zn_username=%E8%87%AA%E5%8A%A8%E5%8C%96_Robot client_name=ShuFuAI -# java_api_base=http://127.0.0.1:18080 -java_api_base=http://8.136.19.173:18080 +java_api_base=http://127.0.0.1:18080 +# java_api_base=http://8.136.19.173:18080 diff --git a/app/assets/convert.js b/app/assets/convert.js index bbc3d43..20f8bcb 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 j,B as z,e as s,F as w,r as F,t as r,f as _,n as E,w as K,u as M,x as q,g as u,h as T,y as J,i as k,E as i,j as L,z as O,A as G,C as Q,_ as W,q as X,s as Y}from"./pywebview-Dee3nQjE.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 L(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 O({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 G();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 Q(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){const l=await e.save_file_from_url(a.downloadUrl,t);l.success?i.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&i.error(l.error);return}window.open(a.downloadUrl,"_blank")}return H(()=>{B().catch(()=>{}),x().catch(()=>{})}),(a,e)=>(n(),o("div",Z,[j(z,{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}])},[K(s("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>c.value=l),type:"radio",value:t.id,name:"convert-template"},null,8,ie),[[M,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=W(Ve,[["__scopeId","data-v-89690cc3"]]);X(Ae).use(Y).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 i,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 r,y as L,z as O,A as G,_ as Q,p as W,q as X}from"./pywebview-BCPdlDdb.js";import{e as Y}from"./brand-CFZZtTv8.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"},re=["value"],ie={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),r.success(e)}async function $(){const a=k();if(!a?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await a.select_brand_xlsx_files();if(!e?.length)return;await N(e,`已选择 ${e.length} 个待转换文件`)}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function D(){const a=k();if(!a?.select_brand_folder){r.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),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function R(){if(!f.value.length){r.warning("请先选择待转换 Excel 文件或文件夹");return}if(!c.value){r.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(),r.success("格式转换完成")}catch(a){r.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(),r.success("已删除")}catch(e){r.error(e instanceof Error?e.message:"删除失败")}}async function U(a){const e=k();if(!a.downloadUrl){r.warning("当前结果没有下载地址");return}const t=a.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.txt`;if(e?.save_file_from_url){const l=await e.save_file_from_url(a.downloadUrl,t);l.success?r.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&r.error(l.error);return}window.open(a.downloadUrl,"_blank")}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},i(t),1))),128)),v.value.length>C.value.length?(n(),o("span",le," 还有 "+i(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,re),[[j,c.value]]),s("div",ie,[s("div",null,[s("span",ce,[q(i(t.templateName)+" ",1),t.isDefault?(n(),o("span",ue,"默认")):t.builtIn?(n(),o("span",de,"内置")):(n(),o("span",ve,"自定义"))]),s("div",pe,"输出文件:"+i(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,"当前模板:"+i(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},i(m.value?"转换中...":"开始转换"),9,ge),s("span",be,i(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,i(h.value.total),1)]),s("div",Fe,[e[9]||(e[9]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,i(h.value.successCount),1)]),s("div",Pe,[e[10]||(e[10]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,i(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},i(t.sourceFilename||"-"),9,Ne),t.outputFilename?(n(),o("div",$e,"压缩包文件:"+i(t.outputFilename),1)):_("",!0),t.error?(n(),o("div",De,"错误信息:"+i(t.error),1)):_("",!0)]),s("div",Re,[s("span",{class:E(["status",t.success?"success":"failed"])},i(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-89690cc3"]]);W(Ae).use(X).mount("#app"); diff --git a/app/assets/dedupe.js b/app/assets/dedupe.js index 26b7525..42cc314 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,p as Y,_ as Z,q as ee,s as se}from"./pywebview-Dee3nQjE.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 Y(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 O(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 G({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 Q();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 X(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){const a=await e.save_file_from_url(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}window.open(l.downloadUrl,"_blank")}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=Z(Ae,[["__scopeId","data-v-6b14da88"]]);ee(He).use(se).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-BCPdlDdb.js";import{e as se}from"./brand-CFZZtTv8.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){const a=await e.save_file_from_url(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}window.open(l.downloadUrl,"_blank")}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-6b14da88"]]);Z(He).use(ee).mount("#app"); diff --git a/app/assets/delete-brand.js b/app/assets/delete-brand.js index 36c4f8f..bbbdb3d 100644 --- a/app/assets/delete-brand.js +++ b/app/assets/delete-brand.js @@ -1 +1 @@ -import{d as Me,o as Ae,J as Be,a as u,c as i,b as qe,B as Ue,e as r,F as R,r as Z,t as c,f,K as Ke,L as Ie,n as be,g as p,h as j,M as He,i as M,E as h,j as Je,N as Oe,O as Le,P as je,Q as Ve,_ as ze,q as Ge,s as Qe}from"./pywebview-Dee3nQjE.js";const Xe={class:"page-shell module-page"},We={class:"main-content"},Ye={class:"left-panel"},Ze={class:"upload-zone"},es={class:"selected-files clean-placeholder split-selected-files"},ss={key:0,class:"more-line"},ts={key:1},ns={class:"run-row"},as=["disabled"],ls={class:"loading-msg"},rs={key:0,class:"queue-debug-card"},os={key:0,class:"queue-debug-line"},us={key:1,class:"queue-debug-payload"},is={class:"right-panel"},cs={class:"task-list-wrap"},ds={class:"clean-result-summary"},fs={class:"summary-card"},vs={class:"summary-card"},hs={class:"summary-card"},ps={class:"result-list-wrap"},_s={key:0,class:"empty-tasks"},gs={key:0,class:"result-subsection"},ys={class:"task-list clean-result-list"},ks={class:"left split-result-main"},ms=["title"],Is={class:"files"},bs={class:"files"},ws={key:0,class:"files"},Ss={key:1,class:"files"},Cs={key:2,class:"files"},Fs={key:3,class:"time"},Ts={key:4,class:"delete-brand-progress-block"},xs={class:"delete-brand-progress-header"},Ns={class:"delete-brand-progress-bar"},$s={class:"files delete-brand-progress"},Es={key:5,class:"files split-entry-list delete-brand-preview"},Ps={key:6,class:"files"},Ds={class:"task-right split-result-actions"},Rs=["onClick"],Ms=["onClick"],As=["onClick"],Bs={key:1,class:"result-subsection"},qs={class:"task-list clean-result-list"},Us={class:"left split-result-main"},Ks=["title"],Hs={class:"files"},Js={class:"files"},Os={key:0,class:"files"},Ls={key:1,class:"files"},js={key:2,class:"time"},Vs={key:3,class:"delete-brand-progress-block"},zs={class:"delete-brand-progress-header"},Gs={class:"delete-brand-progress-bar"},Qs={class:"files delete-brand-progress"},Xs={key:4,class:"files split-entry-list delete-brand-preview"},Ws={key:5,class:"files"},Ys={class:"task-right split-result-actions"},Zs=["onClick"],et=["onClick"],st=Me({__name:"BrandDeleteBrandTab",setup(nt){function N(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const C=p([]),A=p([]),$=p(!1),ee=p([]),d=p([]),B=p([]),q=p({total:0,successCount:0,failedCount:0,items:[]}),I=p(""),k=p(""),_=p({}),y=p(null),V=p(!1),F=p(!1),b=p(""),U=p(!1),z=j(()=>C.value.slice(0,10)),m=j(()=>{const e=[];return d.value.forEach(s=>{e.push(...s.items)}),e});function we(){try{const e=typeof window<"u"?window.localStorage.getItem(N()):null;if(e){if(d.value=JSON.parse(e),d.value.length>0){const s=d.value[d.value.length-1];I.value=s.queuePushResult||"",k.value=s.queuePayloadText||""}}else d.value=[]}catch{d.value=[]}}function se(e,s,t,n){const l=s.filter(v=>v.matchStatus==="MATCHED"&&v.success!==!1);if(l.length===0)return;const o={taskId:e,items:l,createdAt:Date.now(),queuePushResult:t,queuePayloadText:n},a=d.value.findIndex(v=>v.taskId===e);a>=0?d.value[a]=o:d.value.push(o),typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}function te(e){const s=d.value.length;d.value=d.value.filter(t=>t.taskId!==e),d.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}const K=j(()=>B.value.filter(e=>!m.value.some(s=>s.taskId===e.taskId||s.resultId&&s.resultId===e.resultId))),Se=j(()=>m.value.length>0||K.value.length>0);function ne(){typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}function E(e){return e?(d.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function G(e){return e&&d.value.find(s=>s.taskId===e)||null}function Q(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 T(e,s){const t=G(e);return t&&t.items.find(n=>Q(n,s))||null}function ae(e){if(!e)return!1;const s=G(e);if(!s)return!1;let t=!1;const n=_.value[e]?.line_progress?.info;if(E(e)&&n?.finished_files!=null&&n.finished_files>=0){const l=s.items.filter(a=>a._pushed),o=Math.max(0,Math.min(n.finished_files,l.length));for(let a=0;a0&&n.current_line>=n.total_lines){const l=m.value.find(a=>x(a)===b.value),o=l&&l.taskId===e?T(e,l):s.items.find(a=>a.sourceFilename===n.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}return t&&ne(),t}function le(e){return e&&_.value[e]?.task?.status||""}function H(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&_.value[s]?.task?.errorMessage||""}function re(e){const s=e.taskId;if(!s)return!1;const t=_.value[s]?.line_progress,n=le(s),l=E(s),o=S(e);if(l){const a=T(s,e),v=x(e)===b.value,g=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return!!(v||g||a?._pushed||(n==="RUNNING"||n==="PENDING"||!n)&&a?._completed)}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function oe(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 ue(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 Ce(){ee.value=[...m.value,...K.value]}function w(){Ce(),Fe(ee.value)}function Fe(e){q.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function ie(e){const s=e.taskId;return s&&(_.value[s]?.fileProgress||[]).find(l=>l.fileKey&&e.fileKey?l.fileKey===e.fileKey:l.sourceFilename&&e.sourceFilename?l.sourceFilename===e.sourceFilename:!1)||null}function ce(e){const s=e.taskId;if(!s)return"";const t=_.value[s],n=t?.line_progress?.info,l=ie(e);if(l){const a=[],v=l.processedRows??0,g=l.totalRows??0;if(l.status&&a.push(`文件状态:${l.status}`),a.push(`文件进度:${v}/${g}`),n?.finished_files!=null){const D=n.file_total&&n.file_total>0?`/${n.file_total}`:"";a.push(`已完成文件:${n.finished_files}${D}`)}return n?.phase&&a.push(`阶段:${n.phase}`),a.join("|")}if(!t?.line_progress?.has_progress||!n){const a=t?.task?.status;return a?`任务状态:${a}`:""}const o=[];if(n.phase&&o.push(`阶段:${n.phase}`),n.file_index&&n.file_total&&o.push(`文件:${n.file_index}/${n.file_total}`),n.file_name&&o.push(`当前文件:${n.file_name}`),n.current_line!=null&&n.total_lines!=null&&o.push(`${E(s)?"当前文件进度":"进度"}:${n.current_line}/${n.total_lines}`),n.current_country&&o.push(`国家:${n.current_country}`),n.current_asin&&o.push(`ASIN:${n.current_asin}`),n.finished_files!=null){const a=n.file_total&&n.file_total>0?`/${n.file_total}`:"";o.push(`已完成文件:${n.finished_files}${a}`)}return o.join("|")}function J(e){const s=e.taskId;if(!s)return 0;const t=ie(e);if(t)return Math.max(0,Math.min(100,t.percent??0));const n=_.value[s]?.line_progress?.info;return n?n.current_line!=null&&n.total_lines&&n.total_lines>0?Math.max(0,Math.min(100,Math.round(n.current_line/n.total_lines*100))):n.finished_files!=null&&n.file_total&&n.file_total>0?Math.max(0,Math.min(100,Math.round(n.finished_files/n.file_total*100))):_.value[s]?.task?.status==="SUCCESS"?100:0:0}function de(e){const s=_.value[e]?.task?.status;return s==="SUCCESS"||s==="FAILED"}function P(){const e=new Set;return d.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function S(e){const s=e.taskId;if(!s||!G(s))return"";const n=T(s,e),l=le(s),o=_.value[s]?.line_progress,a=E(s);if(!a&&(l==="SUCCESS"||l==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(n?._completed)return"本文件解析完毕";if(l==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(a&&!n?._pushed&&!n?._completed)return"未入队";if(a&&l==="SUCCESS")return"本文件解析完毕";if(!a){const v=_.value[s];if(v?.items&&v.items.find(D=>Q(D,e))&&l==="SUCCESS")return"本文件解析完毕"}return n?._pushed?"已入队":"未入队"}function fe(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?_.value[s]?.task?.status==="SUCCESS":!1}function Te(e){const s=e?.task?.id;if(!s||!e?.items?.length)return!1;const t=d.value.find(a=>a.taskId===s);if(!t)return!1;let n=!1;const o=t.items.map(a=>{const v=e.items?.find(D=>Q(D,a));if(!v)return a;const g={...a,...v,success:a.success??v.success,_pushed:a._pushed,_completed:a._completed};return JSON.stringify(g)!==JSON.stringify(a)&&(n=!0),g}).filter(a=>a.matchStatus==="MATCHED"&&a.success!==!1);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,n=!0),n&&ne(),n}async function X(e){const s=e||P();if(s.length)try{const t=await He(s);let n=!1;for(const l of t.items||[]){const o=l?.task?.id;typeof o=="number"&&o>0&&(_.value[o]=l,Te(l)&&(n=!0),ae(o)&&(n=!0))}n&&w()}catch{}}function xe(){return document.visibilityState==="visible"?4500:1e4}function W(e=!1){if(y.value){if(!e)return;clearTimeout(y.value),y.value=null}const s=async()=>{if(y.value=null,V.value){W();return}const t=P();if(!t.length)return;V.value=!0;let n=!1;try{await X(t),await De();for(const l of t)de(l)&&(te(l),n=!0)}finally{V.value=!1}n&&(L(),w()),P().length>0&&W()};e?s():y.value=window.setTimeout(s,xe())}function Y(e=!1){y.value&&!e||W(e)}function O(e){const s=e.taskId?_.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 ve(){y.value&&(window.clearTimeout(y.value),y.value=null)}async function he(e){const s=M();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const n of e){const l=typeof n=="string"?n:n.absolutePath,o=typeof n=="string"?void 0:n.relativePath,a=await s.upload_file_to_java(l,o);if(!a?.success||!a.data)throw new Error(a?.error||a?.message||`上传失败:${l}`);t.push(a.data)}return t}async function Ne(){const e=M();if(!e?.select_brand_xlsx_files){h.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;C.value=s,A.value=await he(s),h.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function $e(){const e=M();if(!e?.select_brand_folder){h.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await Je(s);if(!t.success||!t.items?.length){h.warning(t.error||"该文件夹下没有 xlsx 文件");return}C.value=t.items.map(n=>n.relativePath||n.absolutePath),A.value=await he(t.items),h.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Ee(){if(!A.value.length){h.warning("请先选择待处理文件");return}try{$.value=!0;const e=await Oe({files:A.value.map(l=>({fileKey:l.fileKey,originalFilename:l.originalFilename,relativePath:l.relativePath}))}),s=oe(e.items||[]),t=s.some(l=>l.matchStatus==="MATCHED"),n=s.some(l=>l.matchStatus&&l.matchStatus!=="MATCHED");I.value="解析完成,等待手动点击打开紫鸟进行单任务处理",k.value="",s.length&&s[0].taskId&&se(s[0].taskId,s,I.value,k.value),w(),n?h.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?h.success("删除品牌解析完成,请手动推送"):h.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await L()}catch(e){h.error(e instanceof Error?e.message:"执行失败")}finally{$.value=!1}}async function pe(e){const s=e.taskId;if(!s){h.warning("未找到任务ID");return}const t=M(),n=Le(s),l=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url){const o=await t.save_file_from_url(n,l);o.success?h.success(`已保存:${o.path||l}`):o.error&&o.error!=="用户取消"&&h.error(o.error);return}window.open(n,"_blank")}async function L(){try{const e=await je();B.value=oe(e.items||[]),w(),await X(),Y(!0)}catch(e){console.error("loadHistory error:",e)}}function _e(e){d.value.forEach(t=>{t.items=t.items.filter(n=>n.resultId!==e)});const s=d.value.length;d.value=d.value.filter(t=>t.items.length>0),d.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value)),B.value=B.value.filter(t=>t.resultId!==e),w(),P().length===0&&ve()}async function ge(e){try{await Ve(e),_e(e),await L(),h.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){_e(e),h.success("已删除");return}h.error(t)}}function ye(e){const s=e.slice(0,5).map(n=>`${n.country}:${n.asin}${n.status?`(${n.status})`:""}`);return e.length-s.length>0?`${s.join("、")} 等 ${e.length} 条`:s.join("、")}function at(e,s){}function ke(){for(const e of d.value)for(const s of e.items){const t=S(s);if(t==="已入队"||t==="处理中")return!0}return!1}function x(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Pe(){return m.value.find(e=>!e.openStoreUrl||x(e)===b.value||T(e.taskId,e)?._completed?!1:S(e)==="未入队")}async function me(e,s){if(s?.auto&&ke())return e.taskId,e.sourceFilename,!1;const t=M(),n=e.taskId;if(!n)return!1;const l=d.value.find(g=>g.taskId===n);if(!l)return!1;if(!t?.enqueue_json)return h.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),!1;const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:n,items:[e]}};k.value=JSON.stringify(o,null,2);const a=await t.enqueue_json(o);let v="";if(a?.success){v=`已推送文件 ${e.sourceFilename},当前队列长度:${a.queue_size??"-"}`;const g=T(n,e);g&&(g._pushed=!0,g._completed=!1),b.value=x(e),se(n,l.items,v,k.value),Y(!0)}else v=`推送到 Python 队列失败:${a?.error||"未知错误"}`;return I.value=v,!!a?.success}async function De(){if(!F.value||U.value){F.value,U.value;return}if(ke())return;const e=b.value;if(e){const t=m.value.find(n=>x(n)===e);if(t){const n=t.taskId,l=E(n);l&&(ae(n),S(t),void 0);const o=S(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(l){const a=T(n,t);if(a&&!a._completed){t.sourceFilename,a._pushed,a._completed;return}}}}const s=Pe();if(!s){b.value="",F.value=!1;return}U.value=!0;try{s.taskId,s.sourceFilename,x(s),await me(s,{auto:!0})||(s.taskId,s.sourceFilename,F.value=!1)}finally{U.value=!1}}async function Re(e){F.value=!0,await me(e)||(F.value=!1,b.value="")}return Ae(()=>{we();const e=P();e.length>0?X(e).then(()=>{let s=!1;for(const t of e)de(t)&&(te(t),s=!0);s&&w(),Y(!0)}):w(),L().catch(()=>{})}),Be(()=>{ve()}),(e,s)=>(u(),i("div",Xe,[qe(Ue,{active:"delete-brand"}),r("div",We,[r("aside",Ye,[s[2]||(s[2]=r("div",{class:"section-title"},"选择文件",-1)),r("div",Ze,[s[0]||(s[0]=r("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),r("div",{class:"btns"},[r("button",{type:"button",class:"opt-btn",onClick:Ne},"选择 Excel 文件"),r("button",{type:"button",class:"opt-btn",onClick:$e},"选择文件夹")]),r("div",es,[C.value.length?(u(),i(R,{key:0},[(u(!0),i(R,null,Z(z.value,t=>(u(),i("span",{key:t},c(t),1))),128)),C.value.length>z.value.length?(u(),i("span",ss," 还有 "+c(C.value.length-z.value.length)+" 个文件未展开显示 ",1)):f("",!0)],64)):(u(),i("span",ts,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=Ke('
执行说明
',2)),r("div",ns,[r("button",{type:"button",class:"btn-run",disabled:$.value,onClick:Ee},c($.value?"解析中...":"开始解析"),9,as),r("span",ls,c($.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),I.value||k.value?(u(),i("div",rs,[s[1]||(s[1]=r("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),I.value?(u(),i("div",os,c(I.value),1)):f("",!0),k.value?(u(),i("pre",us,c(k.value),1)):f("",!0)])):f("",!0)]),r("section",is,[s[12]||(s[12]=r("div",{class:"panel-header"},"删除品牌结果",-1)),r("div",cs,[r("div",ds,[r("div",fs,[s[4]||(s[4]=r("span",{class:"summary-label"},"已处理文件",-1)),r("strong",null,c(q.value.total),1)]),r("div",vs,[s[5]||(s[5]=r("span",{class:"summary-label"},"成功结果",-1)),r("strong",null,c(q.value.successCount),1)]),r("div",hs,[s[6]||(s[6]=r("span",{class:"summary-label"},"失败文件",-1)),r("strong",null,c(q.value.failedCount),1)])]),r("div",ps,[s[11]||(s[11]=r("div",{class:"result-list-header"},[r("span",null,"删除品牌结果列表")],-1)),Se.value?(u(),i(R,{key:1},[m.value.length?(u(),i("div",gs,[s[8]||(s[8]=r("div",{class:"result-subsection-title"},"当前任务",-1)),r("ul",ys,[(u(!0),i(R,null,Z(m.value,t=>(u(),i("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",ks,[r("span",{class:"id",title:t.sourceFilename},c(t.sourceFilename||"-"),9,ms),r("div",Is,"店铺名:"+c(t.shopName||"-"),1),r("div",bs,"匹配结果:"+c(ue(t)),1),t.platform?(u(),i("div",ws,"平台:"+c(t.platform),1)):f("",!0),S(t)?(u(),i("div",Ss,"队列状态:"+c(S(t)),1)):f("",!0),t.countryCount!==void 0&&t.matched?(u(),i("div",Cs,"国家数:"+c(t.countryCount),1)):f("",!0),t.totalRows!==void 0&&t.matched?(u(),i("div",Fs,"去重后 "+c(t.totalRows)+" 条 ",1)):f("",!0),re(t)?(u(),i("div",Ts,[r("div",xs,[s[7]||(s[7]=r("span",null,"任务进度",-1)),r("span",null,c(J(t))+"%",1)]),r("div",Ns,[r("div",{class:"delete-brand-progress-bar-fill",style:Ie({width:`${J(t)}%`})},null,4)]),r("div",$s,c(ce(t)),1)])):f("",!0),t.previewRows?.length?(u(),i("div",Es,c(ye(t.previewRows)),1)):f("",!0),H(t)?(u(),i("div",Ps,"错误信息:"+c(H(t)),1)):f("",!0)]),r("div",Ds,[r("span",{class:be(["status",O(t).className])},c(O(t).text),3),t.openStoreUrl?(u(),i("button",{key:0,type:"button",class:"download",onClick:n=>Re(t)}," 打开紫鸟 ",8,Rs)):f("",!0),fe(t)?(u(),i("button",{key:1,type:"button",class:"download",onClick:n=>pe(t)}," 下载 ",8,Ms)):f("",!0),t.resultId?(u(),i("button",{key:2,type:"button",class:"btn-delete",onClick:n=>ge(t.resultId)}," 删除 ",8,As)):f("",!0)])]))),128))])])):f("",!0),K.value.length?(u(),i("div",Bs,[s[10]||(s[10]=r("div",{class:"result-subsection-title"},"历史记录",-1)),r("ul",qs,[(u(!0),i(R,null,Z(K.value,t=>(u(),i("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",Us,[r("span",{class:"id",title:t.sourceFilename},c(t.sourceFilename||"-"),9,Ks),r("div",Hs,"店铺名:"+c(t.shopName||"-"),1),r("div",Js,"匹配结果:"+c(ue(t)),1),t.platform?(u(),i("div",Os,"平台:"+c(t.platform),1)):f("",!0),t.countryCount!==void 0&&t.matched?(u(),i("div",Ls,"国家数:"+c(t.countryCount),1)):f("",!0),t.totalRows!==void 0&&t.matched?(u(),i("div",js,"去重后 "+c(t.totalRows)+" 条 ",1)):f("",!0),re(t)?(u(),i("div",Vs,[r("div",zs,[s[9]||(s[9]=r("span",null,"任务进度",-1)),r("span",null,c(J(t))+"%",1)]),r("div",Gs,[r("div",{class:"delete-brand-progress-bar-fill",style:Ie({width:`${J(t)}%`})},null,4)]),r("div",Qs,c(ce(t)),1)])):f("",!0),t.previewRows?.length?(u(),i("div",Xs,c(ye(t.previewRows)),1)):f("",!0),H(t)?(u(),i("div",Ws,"错误信息:"+c(H(t)),1)):f("",!0)]),r("div",Ys,[r("span",{class:be(["status",O(t).className])},c(O(t).text),3),fe(t)?(u(),i("button",{key:0,type:"button",class:"download",onClick:n=>pe(t)}," 下载 ",8,Zs)):f("",!0),t.resultId?(u(),i("button",{key:1,type:"button",class:"btn-delete",onClick:n=>ge(t.resultId)}," 删除 ",8,et)):f("",!0)])]))),128))])])):f("",!0)],64)):(u(),i("div",_s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),tt=ze(st,[["__scopeId","data-v-7f166b99"]]);Ge(tt).use(Qe).mount("#app"); +import{d as Me,o as Ae,I as Be,a as u,c as i,b as qe,B as Ue,e as r,F as R,r as Z,t as c,f,J as Ke,K as Ie,n as be,g as p,h as j,L as He,i as M,E as h,M as Je,N as Oe,O as Le,P as je,_ as Ve,p as ze,q as Ge}from"./pywebview-BCPdlDdb.js";import{e as Qe}from"./brand-CFZZtTv8.js";const Xe={class:"page-shell module-page"},We={class:"main-content"},Ye={class:"left-panel"},Ze={class:"upload-zone"},es={class:"selected-files clean-placeholder split-selected-files"},ss={key:0,class:"more-line"},ts={key:1},ns={class:"run-row"},as=["disabled"],ls={class:"loading-msg"},rs={key:0,class:"queue-debug-card"},os={key:0,class:"queue-debug-line"},us={key:1,class:"queue-debug-payload"},is={class:"right-panel"},cs={class:"task-list-wrap"},ds={class:"clean-result-summary"},fs={class:"summary-card"},vs={class:"summary-card"},hs={class:"summary-card"},ps={class:"result-list-wrap"},_s={key:0,class:"empty-tasks"},gs={key:0,class:"result-subsection"},ys={class:"task-list clean-result-list"},ks={class:"left split-result-main"},ms=["title"],Is={class:"files"},bs={class:"files"},ws={key:0,class:"files"},Ss={key:1,class:"files"},Cs={key:2,class:"files"},Fs={key:3,class:"time"},Ts={key:4,class:"delete-brand-progress-block"},xs={class:"delete-brand-progress-header"},Ns={class:"delete-brand-progress-bar"},$s={class:"files delete-brand-progress"},Es={key:5,class:"files split-entry-list delete-brand-preview"},Ps={key:6,class:"files"},Ds={class:"task-right split-result-actions"},Rs=["onClick"],Ms=["onClick"],As=["onClick"],Bs={key:1,class:"result-subsection"},qs={class:"task-list clean-result-list"},Us={class:"left split-result-main"},Ks=["title"],Hs={class:"files"},Js={class:"files"},Os={key:0,class:"files"},Ls={key:1,class:"files"},js={key:2,class:"time"},Vs={key:3,class:"delete-brand-progress-block"},zs={class:"delete-brand-progress-header"},Gs={class:"delete-brand-progress-bar"},Qs={class:"files delete-brand-progress"},Xs={key:4,class:"files split-entry-list delete-brand-preview"},Ws={key:5,class:"files"},Ys={class:"task-right split-result-actions"},Zs=["onClick"],et=["onClick"],st=Me({__name:"BrandDeleteBrandTab",setup(nt){function N(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const C=p([]),A=p([]),$=p(!1),ee=p([]),d=p([]),B=p([]),q=p({total:0,successCount:0,failedCount:0,items:[]}),I=p(""),k=p(""),_=p({}),y=p(null),V=p(!1),F=p(!1),b=p(""),U=p(!1),z=j(()=>C.value.slice(0,10)),m=j(()=>{const e=[];return d.value.forEach(s=>{e.push(...s.items)}),e});function we(){try{const e=typeof window<"u"?window.localStorage.getItem(N()):null;if(e){if(d.value=JSON.parse(e),d.value.length>0){const s=d.value[d.value.length-1];I.value=s.queuePushResult||"",k.value=s.queuePayloadText||""}}else d.value=[]}catch{d.value=[]}}function se(e,s,t,n){const l=s.filter(v=>v.matchStatus==="MATCHED"&&v.success!==!1);if(l.length===0)return;const o={taskId:e,items:l,createdAt:Date.now(),queuePushResult:t,queuePayloadText:n},a=d.value.findIndex(v=>v.taskId===e);a>=0?d.value[a]=o:d.value.push(o),typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}function te(e){const s=d.value.length;d.value=d.value.filter(t=>t.taskId!==e),d.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}const K=j(()=>B.value.filter(e=>!m.value.some(s=>s.taskId===e.taskId||s.resultId&&s.resultId===e.resultId))),Se=j(()=>m.value.length>0||K.value.length>0);function ne(){typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value))}function E(e){return e?(d.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function G(e){return e&&d.value.find(s=>s.taskId===e)||null}function Q(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 T(e,s){const t=G(e);return t&&t.items.find(n=>Q(n,s))||null}function ae(e){if(!e)return!1;const s=G(e);if(!s)return!1;let t=!1;const n=_.value[e]?.line_progress?.info;if(E(e)&&n?.finished_files!=null&&n.finished_files>=0){const l=s.items.filter(a=>a._pushed),o=Math.max(0,Math.min(n.finished_files,l.length));for(let a=0;a0&&n.current_line>=n.total_lines){const l=m.value.find(a=>x(a)===b.value),o=l&&l.taskId===e?T(e,l):s.items.find(a=>a.sourceFilename===n.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}return t&&ne(),t}function le(e){return e&&_.value[e]?.task?.status||""}function H(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&_.value[s]?.task?.errorMessage||""}function re(e){const s=e.taskId;if(!s)return!1;const t=_.value[s]?.line_progress,n=le(s),l=E(s),o=S(e);if(l){const a=T(s,e),v=x(e)===b.value,g=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return!!(v||g||a?._pushed||(n==="RUNNING"||n==="PENDING"||!n)&&a?._completed)}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function oe(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 ue(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 Ce(){ee.value=[...m.value,...K.value]}function w(){Ce(),Fe(ee.value)}function Fe(e){q.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function ie(e){const s=e.taskId;return s&&(_.value[s]?.fileProgress||[]).find(l=>l.fileKey&&e.fileKey?l.fileKey===e.fileKey:l.sourceFilename&&e.sourceFilename?l.sourceFilename===e.sourceFilename:!1)||null}function ce(e){const s=e.taskId;if(!s)return"";const t=_.value[s],n=t?.line_progress?.info,l=ie(e);if(l){const a=[],v=l.processedRows??0,g=l.totalRows??0;if(l.status&&a.push(`文件状态:${l.status}`),a.push(`文件进度:${v}/${g}`),n?.finished_files!=null){const D=n.file_total&&n.file_total>0?`/${n.file_total}`:"";a.push(`已完成文件:${n.finished_files}${D}`)}return n?.phase&&a.push(`阶段:${n.phase}`),a.join("|")}if(!t?.line_progress?.has_progress||!n){const a=t?.task?.status;return a?`任务状态:${a}`:""}const o=[];if(n.phase&&o.push(`阶段:${n.phase}`),n.file_index&&n.file_total&&o.push(`文件:${n.file_index}/${n.file_total}`),n.file_name&&o.push(`当前文件:${n.file_name}`),n.current_line!=null&&n.total_lines!=null&&o.push(`${E(s)?"当前文件进度":"进度"}:${n.current_line}/${n.total_lines}`),n.current_country&&o.push(`国家:${n.current_country}`),n.current_asin&&o.push(`ASIN:${n.current_asin}`),n.finished_files!=null){const a=n.file_total&&n.file_total>0?`/${n.file_total}`:"";o.push(`已完成文件:${n.finished_files}${a}`)}return o.join("|")}function J(e){const s=e.taskId;if(!s)return 0;const t=ie(e);if(t)return Math.max(0,Math.min(100,t.percent??0));const n=_.value[s]?.line_progress?.info;return n?n.current_line!=null&&n.total_lines&&n.total_lines>0?Math.max(0,Math.min(100,Math.round(n.current_line/n.total_lines*100))):n.finished_files!=null&&n.file_total&&n.file_total>0?Math.max(0,Math.min(100,Math.round(n.finished_files/n.file_total*100))):_.value[s]?.task?.status==="SUCCESS"?100:0:0}function de(e){const s=_.value[e]?.task?.status;return s==="SUCCESS"||s==="FAILED"}function P(){const e=new Set;return d.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function S(e){const s=e.taskId;if(!s||!G(s))return"";const n=T(s,e),l=le(s),o=_.value[s]?.line_progress,a=E(s);if(!a&&(l==="SUCCESS"||l==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(n?._completed)return"本文件解析完毕";if(l==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(a&&!n?._pushed&&!n?._completed)return"未入队";if(a&&l==="SUCCESS")return"本文件解析完毕";if(!a){const v=_.value[s];if(v?.items&&v.items.find(D=>Q(D,e))&&l==="SUCCESS")return"本文件解析完毕"}return n?._pushed?"已入队":"未入队"}function fe(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?_.value[s]?.task?.status==="SUCCESS":!1}function Te(e){const s=e?.task?.id;if(!s||!e?.items?.length)return!1;const t=d.value.find(a=>a.taskId===s);if(!t)return!1;let n=!1;const o=t.items.map(a=>{const v=e.items?.find(D=>Q(D,a));if(!v)return a;const g={...a,...v,success:a.success??v.success,_pushed:a._pushed,_completed:a._completed};return JSON.stringify(g)!==JSON.stringify(a)&&(n=!0),g}).filter(a=>a.matchStatus==="MATCHED"&&a.success!==!1);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,n=!0),n&&ne(),n}async function X(e){const s=e||P();if(s.length)try{const t=await He(s);let n=!1;for(const l of t.items||[]){const o=l?.task?.id;typeof o=="number"&&o>0&&(_.value[o]=l,Te(l)&&(n=!0),ae(o)&&(n=!0))}n&&w()}catch{}}function xe(){return document.visibilityState==="visible"?4500:1e4}function W(e=!1){if(y.value){if(!e)return;clearTimeout(y.value),y.value=null}const s=async()=>{if(y.value=null,V.value){W();return}const t=P();if(!t.length)return;V.value=!0;let n=!1;try{await X(t),await De();for(const l of t)de(l)&&(te(l),n=!0)}finally{V.value=!1}n&&(L(),w()),P().length>0&&W()};e?s():y.value=window.setTimeout(s,xe())}function Y(e=!1){y.value&&!e||W(e)}function O(e){const s=e.taskId?_.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 ve(){y.value&&(window.clearTimeout(y.value),y.value=null)}async function he(e){const s=M();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const n of e){const l=typeof n=="string"?n:n.absolutePath,o=typeof n=="string"?void 0:n.relativePath,a=await s.upload_file_to_java(l,o);if(!a?.success||!a.data)throw new Error(a?.error||a?.message||`上传失败:${l}`);t.push(a.data)}return t}async function Ne(){const e=M();if(!e?.select_brand_xlsx_files){h.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;C.value=s,A.value=await he(s),h.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function $e(){const e=M();if(!e?.select_brand_folder){h.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await Qe(s);if(!t.success||!t.items?.length){h.warning(t.error||"该文件夹下没有 xlsx 文件");return}C.value=t.items.map(n=>n.relativePath||n.absolutePath),A.value=await he(t.items),h.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){h.error(s instanceof Error?s.message:"选择失败")}}async function Ee(){if(!A.value.length){h.warning("请先选择待处理文件");return}try{$.value=!0;const e=await Je({files:A.value.map(l=>({fileKey:l.fileKey,originalFilename:l.originalFilename,relativePath:l.relativePath}))}),s=oe(e.items||[]),t=s.some(l=>l.matchStatus==="MATCHED"),n=s.some(l=>l.matchStatus&&l.matchStatus!=="MATCHED");I.value="解析完成,等待手动点击打开紫鸟进行单任务处理",k.value="",s.length&&s[0].taskId&&se(s[0].taskId,s,I.value,k.value),w(),n?h.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?h.success("删除品牌解析完成,请手动推送"):h.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await L()}catch(e){h.error(e instanceof Error?e.message:"执行失败")}finally{$.value=!1}}async function pe(e){const s=e.taskId;if(!s){h.warning("未找到任务ID");return}const t=M(),n=Oe(s),l=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url){const o=await t.save_file_from_url(n,l);o.success?h.success(`已保存:${o.path||l}`):o.error&&o.error!=="用户取消"&&h.error(o.error);return}window.open(n,"_blank")}async function L(){try{const e=await Le();B.value=oe(e.items||[]),w(),await X(),Y(!0)}catch(e){console.error("loadHistory error:",e)}}function _e(e){d.value.forEach(t=>{t.items=t.items.filter(n=>n.resultId!==e)});const s=d.value.length;d.value=d.value.filter(t=>t.items.length>0),d.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(d.value)),B.value=B.value.filter(t=>t.resultId!==e),w(),P().length===0&&ve()}async function ge(e){try{await je(e),_e(e),await L(),h.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){_e(e),h.success("已删除");return}h.error(t)}}function ye(e){const s=e.slice(0,5).map(n=>`${n.country}:${n.asin}${n.status?`(${n.status})`:""}`);return e.length-s.length>0?`${s.join("、")} 等 ${e.length} 条`:s.join("、")}function at(e,s){}function ke(){for(const e of d.value)for(const s of e.items){const t=S(s);if(t==="已入队"||t==="处理中")return!0}return!1}function x(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Pe(){return m.value.find(e=>!e.openStoreUrl||x(e)===b.value||T(e.taskId,e)?._completed?!1:S(e)==="未入队")}async function me(e,s){if(s?.auto&&ke())return e.taskId,e.sourceFilename,!1;const t=M(),n=e.taskId;if(!n)return!1;const l=d.value.find(g=>g.taskId===n);if(!l)return!1;if(!t?.enqueue_json)return h.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),!1;const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:n,items:[e]}};k.value=JSON.stringify(o,null,2);const a=await t.enqueue_json(o);let v="";if(a?.success){v=`已推送文件 ${e.sourceFilename},当前队列长度:${a.queue_size??"-"}`;const g=T(n,e);g&&(g._pushed=!0,g._completed=!1),b.value=x(e),se(n,l.items,v,k.value),Y(!0)}else v=`推送到 Python 队列失败:${a?.error||"未知错误"}`;return I.value=v,!!a?.success}async function De(){if(!F.value||U.value){F.value,U.value;return}if(ke())return;const e=b.value;if(e){const t=m.value.find(n=>x(n)===e);if(t){const n=t.taskId,l=E(n);l&&(ae(n),S(t),void 0);const o=S(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(l){const a=T(n,t);if(a&&!a._completed){t.sourceFilename,a._pushed,a._completed;return}}}}const s=Pe();if(!s){b.value="",F.value=!1;return}U.value=!0;try{s.taskId,s.sourceFilename,x(s),await me(s,{auto:!0})||(s.taskId,s.sourceFilename,F.value=!1)}finally{U.value=!1}}async function Re(e){F.value=!0,await me(e)||(F.value=!1,b.value="")}return Ae(()=>{we();const e=P();e.length>0?X(e).then(()=>{let s=!1;for(const t of e)de(t)&&(te(t),s=!0);s&&w(),Y(!0)}):w(),L().catch(()=>{})}),Be(()=>{ve()}),(e,s)=>(u(),i("div",Xe,[qe(Ue,{active:"delete-brand"}),r("div",We,[r("aside",Ye,[s[2]||(s[2]=r("div",{class:"section-title"},"选择文件",-1)),r("div",Ze,[s[0]||(s[0]=r("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),r("div",{class:"btns"},[r("button",{type:"button",class:"opt-btn",onClick:Ne},"选择 Excel 文件"),r("button",{type:"button",class:"opt-btn",onClick:$e},"选择文件夹")]),r("div",es,[C.value.length?(u(),i(R,{key:0},[(u(!0),i(R,null,Z(z.value,t=>(u(),i("span",{key:t},c(t),1))),128)),C.value.length>z.value.length?(u(),i("span",ss," 还有 "+c(C.value.length-z.value.length)+" 个文件未展开显示 ",1)):f("",!0)],64)):(u(),i("span",ts,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=Ke('
执行说明
',2)),r("div",ns,[r("button",{type:"button",class:"btn-run",disabled:$.value,onClick:Ee},c($.value?"解析中...":"开始解析"),9,as),r("span",ls,c($.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),I.value||k.value?(u(),i("div",rs,[s[1]||(s[1]=r("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),I.value?(u(),i("div",os,c(I.value),1)):f("",!0),k.value?(u(),i("pre",us,c(k.value),1)):f("",!0)])):f("",!0)]),r("section",is,[s[12]||(s[12]=r("div",{class:"panel-header"},"删除品牌结果",-1)),r("div",cs,[r("div",ds,[r("div",fs,[s[4]||(s[4]=r("span",{class:"summary-label"},"已处理文件",-1)),r("strong",null,c(q.value.total),1)]),r("div",vs,[s[5]||(s[5]=r("span",{class:"summary-label"},"成功结果",-1)),r("strong",null,c(q.value.successCount),1)]),r("div",hs,[s[6]||(s[6]=r("span",{class:"summary-label"},"失败文件",-1)),r("strong",null,c(q.value.failedCount),1)])]),r("div",ps,[s[11]||(s[11]=r("div",{class:"result-list-header"},[r("span",null,"删除品牌结果列表")],-1)),Se.value?(u(),i(R,{key:1},[m.value.length?(u(),i("div",gs,[s[8]||(s[8]=r("div",{class:"result-subsection-title"},"当前任务",-1)),r("ul",ys,[(u(!0),i(R,null,Z(m.value,t=>(u(),i("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",ks,[r("span",{class:"id",title:t.sourceFilename},c(t.sourceFilename||"-"),9,ms),r("div",Is,"店铺名:"+c(t.shopName||"-"),1),r("div",bs,"匹配结果:"+c(ue(t)),1),t.platform?(u(),i("div",ws,"平台:"+c(t.platform),1)):f("",!0),S(t)?(u(),i("div",Ss,"队列状态:"+c(S(t)),1)):f("",!0),t.countryCount!==void 0&&t.matched?(u(),i("div",Cs,"国家数:"+c(t.countryCount),1)):f("",!0),t.totalRows!==void 0&&t.matched?(u(),i("div",Fs,"去重后 "+c(t.totalRows)+" 条 ",1)):f("",!0),re(t)?(u(),i("div",Ts,[r("div",xs,[s[7]||(s[7]=r("span",null,"任务进度",-1)),r("span",null,c(J(t))+"%",1)]),r("div",Ns,[r("div",{class:"delete-brand-progress-bar-fill",style:Ie({width:`${J(t)}%`})},null,4)]),r("div",$s,c(ce(t)),1)])):f("",!0),t.previewRows?.length?(u(),i("div",Es,c(ye(t.previewRows)),1)):f("",!0),H(t)?(u(),i("div",Ps,"错误信息:"+c(H(t)),1)):f("",!0)]),r("div",Ds,[r("span",{class:be(["status",O(t).className])},c(O(t).text),3),t.openStoreUrl?(u(),i("button",{key:0,type:"button",class:"download",onClick:n=>Re(t)}," 打开紫鸟 ",8,Rs)):f("",!0),fe(t)?(u(),i("button",{key:1,type:"button",class:"download",onClick:n=>pe(t)}," 下载 ",8,Ms)):f("",!0),t.resultId?(u(),i("button",{key:2,type:"button",class:"btn-delete",onClick:n=>ge(t.resultId)}," 删除 ",8,As)):f("",!0)])]))),128))])])):f("",!0),K.value.length?(u(),i("div",Bs,[s[10]||(s[10]=r("div",{class:"result-subsection-title"},"历史记录",-1)),r("ul",qs,[(u(!0),i(R,null,Z(K.value,t=>(u(),i("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[r("div",Us,[r("span",{class:"id",title:t.sourceFilename},c(t.sourceFilename||"-"),9,Ks),r("div",Hs,"店铺名:"+c(t.shopName||"-"),1),r("div",Js,"匹配结果:"+c(ue(t)),1),t.platform?(u(),i("div",Os,"平台:"+c(t.platform),1)):f("",!0),t.countryCount!==void 0&&t.matched?(u(),i("div",Ls,"国家数:"+c(t.countryCount),1)):f("",!0),t.totalRows!==void 0&&t.matched?(u(),i("div",js,"去重后 "+c(t.totalRows)+" 条 ",1)):f("",!0),re(t)?(u(),i("div",Vs,[r("div",zs,[s[9]||(s[9]=r("span",null,"任务进度",-1)),r("span",null,c(J(t))+"%",1)]),r("div",Gs,[r("div",{class:"delete-brand-progress-bar-fill",style:Ie({width:`${J(t)}%`})},null,4)]),r("div",Qs,c(ce(t)),1)])):f("",!0),t.previewRows?.length?(u(),i("div",Xs,c(ye(t.previewRows)),1)):f("",!0),H(t)?(u(),i("div",Ws,"错误信息:"+c(H(t)),1)):f("",!0)]),r("div",Ys,[r("span",{class:be(["status",O(t).className])},c(O(t).text),3),fe(t)?(u(),i("button",{key:0,type:"button",class:"download",onClick:n=>pe(t)}," 下载 ",8,Zs)):f("",!0),t.resultId?(u(),i("button",{key:1,type:"button",class:"btn-delete",onClick:n=>ge(t.resultId)}," 删除 ",8,et)):f("",!0)])]))),128))])])):f("",!0)],64)):(u(),i("div",_s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),tt=Ve(st,[["__scopeId","data-v-7f166b99"]]);ze(tt).use(Ge).mount("#app"); diff --git a/app/assets/split.js b/app/assets/split.js index 30f533d..b45cf3d 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,u as V,D as M,g as d,h as Q,i as F,E as r,j as W,G as X,H as Y,p as Z,v as ss,I as es,_ as ts,q as ls,s as as}from"./pywebview-Dee3nQjE.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"},ds={key:0,class:"more-line"},cs={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"},Is={class:"clean-result-summary"},Rs={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},js={key:1,class:"task-list clean-result-list"},Ds={class:"left split-result-main"},Hs=["title"],Ns={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=d([]),C=d(""),c=d([]),_=d([]),p=d([]),B=d(0),u=d("rows_per_file"),m=d(2e3),y=d(5),g=d(!1),h=d([]),b=d({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 I(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 R(l){const s=await Z(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function j(l,s){f.value=l,C.value="",c.value=await I(l),c.value.length>0&&await R(c.value[0].fileKey),r.success(s)}async function D(){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 j(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function H(){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 W(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),c.value=await I(t.items),c.value.length>0&&await R(c.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 N(){if(!c.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 X({files:c.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:c.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 Y();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await es(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){const o=await s.save_file_from_url(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}window.open(l.downloadUrl,"_blank")}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:D},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:H},"选择文件夹")]),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",ds," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",cs,"暂未选择待拆分文件"))])]),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),[[ss,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:N},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",Is,[e("div",Rs,[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",js,[(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",Ds,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Hs),t.outputFilename?(a(),n("div",Ns,"压缩包文件:"+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=ts(Os,[["__scopeId","data-v-4df71c3f"]]);ls(Qs).use(as).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 d,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-BCPdlDdb.js";import{e as as}from"./brand-CFZZtTv8.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"},ds={key:0,class:"more-line"},cs={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"},Us={class:"summary-card"},Is={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=d([]),C=d(""),c=d([]),_=d([]),p=d([]),B=d(0),u=d("rows_per_file"),m=d(2e3),y=d(5),g=d(!1),h=d([]),b=d({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 I=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(I,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${I}`);t.push(w.data)}return t}async function U(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="",c.value=await R(l),c.value.length>0&&await U(c.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),c.value=await R(t.items),c.value.length>0&&await U(c.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(!c.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:c.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:c.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){const o=await s.save_file_from_url(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}window.open(l.downloadUrl,"_blank")}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",ds," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",cs,"暂未选择待拆分文件"))])]),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",Us,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Is,[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-4df71c3f"]]);ts(Qs).use(ls).mount("#app"); diff --git a/app/new_web_source/convert.html b/app/new_web_source/convert.html index a597d39..469cb72 100644 --- a/app/new_web_source/convert.html +++ b/app/new_web_source/convert.html @@ -5,8 +5,9 @@ 格式转换 - 数富AI - - + + + diff --git a/app/new_web_source/dedupe.html b/app/new_web_source/dedupe.html index f534cb5..5f20d01 100644 --- a/app/new_web_source/dedupe.html +++ b/app/new_web_source/dedupe.html @@ -5,8 +5,9 @@ 数据去重 - 数富AI - - + + + diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html index 79865d0..0607e8e 100644 --- a/app/new_web_source/delete-brand.html +++ b/app/new_web_source/delete-brand.html @@ -5,8 +5,9 @@ 删除品牌 - 数富AI - - + + + diff --git a/app/new_web_source/split.html b/app/new_web_source/split.html index 8988196..fc2834d 100644 --- a/app/new_web_source/split.html +++ b/app/new_web_source/split.html @@ -5,8 +5,9 @@ 数据拆分 - 数富AI - - + + + diff --git a/backend-java/pom.xml b/backend-java/pom.xml index 187f51e..71e4523 100644 --- a/backend-java/pom.xml +++ b/backend-java/pom.xml @@ -61,6 +61,11 @@ easyexcel ${easyexcel.version} + + org.apache.poi + poi-ooxml + 5.2.5 + com.aliyun.oss aliyun-sdk-oss diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java index d0ded5a..77934a4 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java +++ b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java @@ -13,4 +13,9 @@ public class DeleteBrandProgressProperties { * 定时补偿 finalize:用于“分片其实已齐,但最后一次提交断开导致没触发 finalize”的场景。 */ private String finalizeCheckCron = "30 */2 * * * *"; + + /** + * 商品风险(PRODUCT_RISK_RESOLVE)RUNNING 超时自动失败:与删除品牌共用同一定时调度。 + */ + private long productRiskStaleTimeoutHours = 48; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/ModuleCleanupProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/ModuleCleanupProperties.java index ae09b7c..1e26bab 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/config/ModuleCleanupProperties.java +++ b/backend-java/src/main/java/com/nanri/aiimage/config/ModuleCleanupProperties.java @@ -11,5 +11,5 @@ import java.util.List; public class ModuleCleanupProperties { private boolean enabled = true; private String cron = "0 0 0 * * *"; - private List moduleTypes = new ArrayList<>(List.of("DEDUPE", "SPLIT", "CONVERT", "DELETE_BRAND")); + private List moduleTypes = new ArrayList<>(List.of("DEDUPE", "SPLIT", "CONVERT", "DELETE_BRAND", "PRODUCT_RISK_RESOLVE")); } 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 e9968c9..891b2de 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 @@ -1,6 +1,7 @@ package com.nanri.aiimage.modules.deletebrand.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.nanri.aiimage.config.DeleteBrandProgressProperties; import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity; @@ -13,11 +14,15 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Map; +/** + * 删除品牌任务的超时回收与 finalize 补偿;并与删除品牌共用同一套定时调度,对商品风险(PRODUCT_RISK_RESOLVE)长时间无回传做失败收尾。 + */ @Service @RequiredArgsConstructor public class DeleteBrandStaleTaskService { - private static final String MODULE_TYPE = "DELETE_BRAND"; + private static final String MODULE_TYPE_DELETE_BRAND = "DELETE_BRAND"; + private static final String MODULE_TYPE_PRODUCT_RISK = "PRODUCT_RISK_RESOLVE"; private final FileTaskMapper fileTaskMapper; private final DeleteBrandTaskCacheService deleteBrandTaskCacheService; @@ -26,11 +31,16 @@ public class DeleteBrandStaleTaskService { @Scheduled(cron = "${aiimage.delete-brand-progress.stale-check-cron:0 */2 * * * *}") public void failStaleRunningTasks() { + failStaleDeleteBrandTasks(); + failStaleProductRiskResolveTasks(); + } + + private void failStaleDeleteBrandTasks() { LocalDateTime threshold = LocalDateTime.now().minusMinutes(deleteBrandProgressProperties.getHeartbeatTimeoutMinutes()); // 先按 DB updatedAt 粗筛,避免全表扫描 java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper() - .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_DELETE_BRAND) .eq(FileTaskEntity::getStatus, "RUNNING") .lt(FileTaskEntity::getUpdatedAt, threshold) .last("limit 200")); @@ -74,9 +84,9 @@ public class DeleteBrandStaleTaskService { } } - int updated = fileTaskMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper() + int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper() .eq(FileTaskEntity::getId, task.getId()) - .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_DELETE_BRAND) .eq(FileTaskEntity::getStatus, "RUNNING") .set(FileTaskEntity::getStatus, "FAILED") .set(FileTaskEntity::getErrorMessage, "结果回传长时间无响应,任务已自动失败") @@ -89,10 +99,30 @@ public class DeleteBrandStaleTaskService { } } + private void failStaleProductRiskResolveTasks() { + long hours = Math.max(1L, deleteBrandProgressProperties.getProductRiskStaleTimeoutHours()); + LocalDateTime threshold = LocalDateTime.now().minusHours(hours); + java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper() + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRODUCT_RISK) + .eq(FileTaskEntity::getStatus, "RUNNING") + .lt(FileTaskEntity::getUpdatedAt, threshold) + .last("limit 200")); + for (FileTaskEntity task : runningTasks) { + fileTaskMapper.update(null, new LambdaUpdateWrapper() + .eq(FileTaskEntity::getId, task.getId()) + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRODUCT_RISK) + .eq(FileTaskEntity::getStatus, "RUNNING") + .set(FileTaskEntity::getStatus, "FAILED") + .set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果,任务已自动失败") + .set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()) + .set(FileTaskEntity::getFinishedAt, LocalDateTime.now())); + } + } + @Scheduled(cron = "${aiimage.delete-brand-progress.finalize-check-cron:30 */2 * * * *}") public void finalizeCompletedRunningTasks() { java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper() - .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_DELETE_BRAND) .eq(FileTaskEntity::getStatus, "RUNNING") .orderByAsc(FileTaskEntity::getUpdatedAt) .last("limit 100")); 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 new file mode 100644 index 0000000..17be534 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java @@ -0,0 +1,351 @@ +package com.nanri.aiimage.modules.productrisk.controller; + +import com.nanri.aiimage.common.api.ApiResponse; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCreateTaskRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskSubmitResultRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskTaskBatchRequest; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCreateTaskVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskPendingDeleteVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo; +import com.nanri.aiimage.modules.productrisk.service.ProductRiskResolveService; +import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +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.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; + +import java.io.InputStream; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/product-risk-resolve") +@Tag( + name = "商品风险解决", + description = "亚马逊商品风险处理:备选店铺、紫鸟匹配、创建任务、Python 队列与回传、生成 zip。" + + "查询类接口需带 Query 参数 user_id(与登录用户一致)。") +public class ProductRiskResolveController { + + private final ProductRiskResolveService productRiskResolveService; + private final ProductRiskTaskService productRiskTaskService; + + @GetMapping("/candidates") + @Operation( + summary = "查询备选店铺列表", + description = "返回当前用户在「商品风险」模块中已保存的备选店铺,按创建时间倒序。用于前端勾选后再调用匹配接口。") + public ApiResponse> listCandidates( + @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 = "将店铺名写入用户备选表;店铺名会规范化去重。仅用于前端勾选与匹配流程,与任务/结果表无强绑定。") + public ApiResponse addCandidate(@Valid @RequestBody ProductRiskCandidateAddRequest request) { + return ApiResponse.success(productRiskResolveService.addCandidate(request)); + } + + @DeleteMapping("/candidates/{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") + @RequestParam("user_id") Long userId) { + productRiskResolveService.deleteCandidate(userId, id); + return ApiResponse.success(null); + } + + @GetMapping("/country-preference") + @Operation( + summary = "查询用户五国处理顺序", + description = "返回当前用户已保存的国家代码列表(顺序即处理顺序);未保存时返回默认:DE、UK、FR、IT、ES(全选)。") + public ApiResponse getCountryPreference( + @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 个、无重复。") + 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,不可创建任务。") + public ApiResponse matchShops(@Valid @RequestBody ProductRiskMatchShopsRequest request) { + return ApiResponse.success(productRiskResolveService.matchShops(request)); + } + + @GetMapping("/dashboard") + @Operation( + summary = "统计看板", + description = "汇总当前用户:备选店铺数量;商品风险模块下已结束任务数(SUCCESS/FAILED);其中成功任务数、失败任务数。") + public ApiResponse dashboard( + @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、错误、输出文件名等。") + public ApiResponse history( + @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);随后重算父任务,无子结果则删任务。") + 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") + @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,店名会去重。") + public ApiResponse createTask(@Valid @RequestBody ProductRiskCreateTaskRequest request) { + return ApiResponse.success(productRiskTaskService.createTask(request)); + } + + @DeleteMapping("/tasks/{taskId}") + @Operation( + summary = "删除整条任务", + description = "删除该任务及下属全部结果行(RUNNING/SUCCESS/FAILED 均可);user_id 须与任务归属一致。") + 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") + @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。" + + "用于前端从匹配列表移除店铺时同步后端占位。") + public ApiResponse deletePendingShopResult( + @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 = "某某店铺") + @RequestParam("shop_name") String shopName) { + return ApiResponse.success(productRiskTaskService.deletePendingShopResult(userId, shopName)); + } + + @PostMapping("/tasks/batch") + @Operation( + summary = "批量查询任务详情(轮询)", + description = "按 taskIds 返回任务概要及各店结果;无效 id 记入 missingTaskIds。供前端轮询 RUNNING 至结束。") + 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。") + public ApiResponse submitResult( + @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`", + required = true, + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ProductRiskSubmitResultRequest.class), + examples = { + @ExampleObject( + name = "成功(单店,五国含样例行)", + summary = "DE、UK 各一行,其余国可为空数组", + value = """ + { + "shops": [ + { + "shopName": "模拟旗舰店A", + "countries": { + "DE": [ + { + "shopName": "模拟旗舰店A", + "productAsinSku": "B0DEMO1234", + "status": "风险待解除", + "done": "否", + "removeAsin": "B0OLD5678", + "removeStatus": "排队中" + } + ], + "FR": [], + "ES": [], + "IT": [], + "UK": [ + { + "shopName": "模拟旗舰店A", + "productAsinSku": "B0UKDEMO99", + "status": "正常", + "done": "是", + "removeAsin": "", + "removeStatus": "" + } + ] + } + } + ] + } + """), + @ExampleObject( + name = "失败(单店仅 error)", + summary = "该店标记失败,不生成 zip", + value = """ + { + "shops": [ + { + "shopName": "模拟旗舰店B", + "error": "紫鸟会话超时,未能导出表格" + } + ] + } + """) + })) + @Valid @RequestBody ProductRiskSubmitResultRequest request) { + productRiskTaskService.submitResult(taskId, request); + return ApiResponse.success(null); + } + + @GetMapping("/results/{resultId}/download") + @Operation( + summary = "流式下载单个店铺的 zip 结果", + description = "从 OSS 拉取 zip 以附件写入响应体(非 JSON);须归属 user_id;无文件则 404。") + 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") + @RequestParam("user_id") Long userId, + jakarta.servlet.http.HttpServletResponse response) { + String url = productRiskTaskService.resolveResultDownloadUrl(resultId, userId); + String filename = productRiskTaskService.resolveResultDownloadFilename(resultId, userId); + if (url == null || url.isBlank()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "暂无可下载结果"); + } + try { + String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"); + response.setContentType("application/octet-stream"); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + filename + "\"; filename*=UTF-8''" + encodedFilename); + try (InputStream in = URI.create(url).toURL().openStream()) { + byte[] buffer = new byte[65536]; + int read; + while ((read = in.read(buffer)) != -1) { + response.getOutputStream().write(buffer, 0, read); + } + response.getOutputStream().flush(); + } + } catch (Exception ex) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "下载失败"); + } + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskCountryPrefMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskCountryPrefMapper.java new file mode 100644 index 0000000..cf03a44 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskCountryPrefMapper.java @@ -0,0 +1,9 @@ +package com.nanri.aiimage.modules.productrisk.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskCountryPrefEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ProductRiskCountryPrefMapper extends BaseMapper { +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskShopCandidateMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskShopCandidateMapper.java new file mode 100644 index 0000000..ecbb48d --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/mapper/ProductRiskShopCandidateMapper.java @@ -0,0 +1,9 @@ +package com.nanri.aiimage.modules.productrisk.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskShopCandidateEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ProductRiskShopCandidateMapper extends BaseMapper { +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCandidateAddRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCandidateAddRequest.java new file mode 100644 index 0000000..0259ba7 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCandidateAddRequest.java @@ -0,0 +1,22 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +@Data +@Schema(description = "新增备选店铺请求体:写入用户维度的待处理店铺列表,供前端勾选与匹配") +public class ProductRiskCandidateAddRequest { + + @NotNull(message = "user_id 不能为空") + @JsonProperty("user_id") + @Schema(description = "当前用户 ID,数据按用户隔离", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + private Long userId; + + @NotBlank(message = "店铺名不能为空") + @JsonProperty("shop_name") + @Schema(description = "店铺名称(展示用原文;入库前会规范化去重)", requiredMode = Schema.RequiredMode.REQUIRED, example = "测试店铺A") + private String shopName; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCountryPreferenceSaveRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCountryPreferenceSaveRequest.java new file mode 100644 index 0000000..be26f28 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCountryPreferenceSaveRequest.java @@ -0,0 +1,27 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "保存用户五国处理顺序:至少 1 个、最多 5 个,代码须为 DE、FR、ES、IT、UK,无重复") +public class ProductRiskCountryPreferenceSaveRequest { + + @NotNull(message = "user_id 不能为空") + @JsonProperty("user_id") + @Schema(description = "当前用户 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + private Long userId; + + @NotEmpty(message = "country_codes 不能为空") + @Size(max = 5, message = "country_codes 最多 5 项") + @JsonProperty("country_codes") + @Schema(description = "国家代码列表(与 ProductRiskCountryCode 枚举名一致),顺序即队列处理顺序", requiredMode = Schema.RequiredMode.REQUIRED) + private List countryCodes = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java new file mode 100644 index 0000000..e287cc7 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskCreateTaskRequest.java @@ -0,0 +1,30 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "创建商品风险处理任务请求体:在推 Python 队列前调用,落库任务与各店结果占位行") +public class ProductRiskCreateTaskRequest { + + @NotNull(message = "user_id 不能为空") + @JsonProperty("user_id") + @Schema(description = "任务归属用户 ID,写入 biz_file_task.user_id", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + private Long userId; + + @NotEmpty(message = "items 不能为空") + @Valid + @Schema( + description = "已匹配店铺列表(结构同 /match-shops 的 items 元素),每项须 matched=true;" + + "店名会去重;每店生成一条 biz_file_result(含 resultId)。", + requiredMode = Schema.RequiredMode.REQUIRED) + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskMatchShopsRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskMatchShopsRequest.java new file mode 100644 index 0000000..cd7a4b8 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskMatchShopsRequest.java @@ -0,0 +1,27 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.List; + +@Data +@Schema(description = "批量店铺匹配请求体:按名称查询紫鸟索引,返回是否命中及店铺元数据") +public class ProductRiskMatchShopsRequest { + + @NotNull(message = "user_id 不能为空") + @JsonProperty("user_id") + @Schema(description = "当前用户 ID(审计/归属;匹配逻辑主要依赖店名)", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + private Long userId; + + @NotEmpty(message = "shop_names 不能为空") + @JsonProperty("shop_names") + @Schema( + description = "待匹配的店铺名称列表,至少 1 个;服务端按列表顺序逐项查索引,返回体 `items` 与列表顺序一一对应", + requiredMode = Schema.RequiredMode.REQUIRED, + example = "[\"店铺甲\",\"店铺乙\"]") + private List shopNames; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskRowDto.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskRowDto.java new file mode 100644 index 0000000..214cf0b --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskRowDto.java @@ -0,0 +1,33 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "单国 sheet 内一行数据,与商品风险处理 Excel 模板列一致") +public class ProductRiskRowDto { + + @JsonProperty("shopName") + @Schema(description = "店铺名(行内冗余字段,可与 sheet 维度一致)") + private String shopName; + + @JsonProperty("productAsinSku") + @Schema(description = "商品 ASIN/SKU 等业务主键列") + private String productAsinSku; + + @Schema(description = "状态列") + private String status; + + @JsonProperty("done") + @Schema(description = "是否完成等标记列") + private String done; + + @JsonProperty("removeAsin") + @Schema(description = "待移除 ASIN 等") + private String removeAsin; + + @JsonProperty("removeStatus") + @Schema(description = "移除状态") + private String removeStatus; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskShopPayloadDto.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskShopPayloadDto.java new file mode 100644 index 0000000..835d788 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskShopPayloadDto.java @@ -0,0 +1,33 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Data +@Schema(description = "Python 回传的单个店铺:成功时带五国表格数据;失败时仅填 error") +public class ProductRiskShopPayloadDto { + + @JsonProperty("shopName") + @Schema(description = "店铺名称,用于与任务内结果行匹配(会按紫鸟规则规范化后比对)", example = "测试店铺") + private String shopName; + + /** + * 若不为空,表示该店铺处理失败,跳过后续 xlsx 生成。 + */ + @Schema(description = "非空时表示该店处理失败,写入 errorMessage,不生成 zip;为空则须配合 countries 生成文件") + private String error; + + /** + * key 为 {@link ProductRiskCountryCode} 的 JSON 名(DE、FR、ES、IT、UK);写盘时映射为中文工作表。 + */ + @Schema( + description = "五国数据:JSON 对象的键为枚举 ProductRiskCountryCode(DE、FR、ES、IT、UK)," + + "值为该国 sheet 的行列表;省略的键表示该国无数据行。") + private Map> countries = new LinkedHashMap<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskSubmitResultRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskSubmitResultRequest.java new file mode 100644 index 0000000..6285b44 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskSubmitResultRequest.java @@ -0,0 +1,23 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema( + description = "Python 回传处理结果请求体:按店铺提交五国 sheet 数据或错误信息(`countries` 的键为枚举 ProductRiskCountryCode:DE、FR、ES、IT、UK)," + + "可多次调用、可只包含部分店铺") +public class ProductRiskSubmitResultRequest { + + @NotEmpty(message = "shops 不能为空") + @Valid + @Schema( + description = "本次回传涉及的店铺列表,至少 1 个;店名须能与任务下 biz_file_result.source_filename(规范化店名)对应", + requiredMode = Schema.RequiredMode.REQUIRED) + private List shops = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskTaskBatchRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskTaskBatchRequest.java new file mode 100644 index 0000000..c0e798e --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/dto/ProductRiskTaskBatchRequest.java @@ -0,0 +1,20 @@ +package com.nanri.aiimage.modules.productrisk.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotEmpty; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "批量查询任务详情请求体:一次拉取多个 taskId 的概要及下属各店结果,供轮询") +public class ProductRiskTaskBatchRequest { + + @NotEmpty(message = "taskIds 不能为空") + @Schema( + description = "待查询的任务主键列表(biz_file_task.id),不可为空;无效或非本模块 id 会出现在响应 `missingTaskIds`", + requiredMode = Schema.RequiredMode.REQUIRED, + example = "[200,201]") + private List taskIds = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskCountryPrefEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskCountryPrefEntity.java new file mode 100644 index 0000000..fc49f61 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskCountryPrefEntity.java @@ -0,0 +1,18 @@ +package com.nanri.aiimage.modules.productrisk.model.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("biz_product_risk_country_pref") +public class ProductRiskCountryPrefEntity { + + @TableId(type = IdType.INPUT) + private Long userId; + private String countryCodesJson; + private LocalDateTime updatedAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskShopCandidateEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskShopCandidateEntity.java new file mode 100644 index 0000000..f0c47e9 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/entity/ProductRiskShopCandidateEntity.java @@ -0,0 +1,19 @@ +package com.nanri.aiimage.modules.productrisk.model.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("biz_product_risk_shop_candidate") +public class ProductRiskShopCandidateEntity { + + @TableId(type = IdType.AUTO) + private Long id; + private Long userId; + private String shopName; + private LocalDateTime createdAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/enums/ProductRiskCountryCode.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/enums/ProductRiskCountryCode.java new file mode 100644 index 0000000..9c0947c --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/enums/ProductRiskCountryCode.java @@ -0,0 +1,29 @@ +package com.nanri.aiimage.modules.productrisk.model.enums; + +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * 商品风险回传五国:请求 JSON 中 {@code countries} 的键须为该枚举名(大写);生成 Excel 时映射为中文工作表名。 + */ +@Schema( + description = "五国站点代码,用作 countries 的 JSON 键(与枚举名一致):" + + "DE→德国、FR→法国、ES→西班牙、IT→意大利、UK→英国", + enumAsRef = true) +public enum ProductRiskCountryCode { + + DE("德国"), + FR("法国"), + ES("西班牙"), + IT("意大利"), + UK("英国"); + + private final String sheetName; + + ProductRiskCountryCode(String sheetName) { + this.sheetName = sheetName; + } + + public String getSheetName() { + return sheetName; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCandidateVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCandidateVo.java new file mode 100644 index 0000000..72606c3 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCandidateVo.java @@ -0,0 +1,23 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@Schema(description = "备选店铺列表单项") +public class ProductRiskCandidateVo { + + @Schema(description = "记录主键,删除备选时作为路径参数 id") + private Long id; + + @JsonProperty("shop_name") + @Schema(description = "店铺名称(JSON 字段名 shop_name)", example = "测试店铺") + private String shopName; + + @JsonProperty("created_at") + @Schema(description = "创建时间(JSON 字段名 created_at)") + private LocalDateTime createdAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCountryPreferenceVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCountryPreferenceVo.java new file mode 100644 index 0000000..c6b0ab5 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCountryPreferenceVo.java @@ -0,0 +1,17 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "用户五国处理偏好:按顺序的国家代码列表(ProductRiskCountryCode 名,如 DE、UK)") +public class ProductRiskCountryPreferenceVo { + + @JsonProperty("country_codes") + @Schema(description = "已选国家代码,顺序即处理顺序;未持久化时服务端返回默认德国→英国→法国→意大利→西班牙(全选)") + private List countryCodes = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCreateTaskVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCreateTaskVo.java new file mode 100644 index 0000000..8b442f9 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskCreateTaskVo.java @@ -0,0 +1,18 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "创建任务响应:含任务 id 与各店初始快照(含 resultId),用于推队列与前端展示") +public class ProductRiskCreateTaskVo { + + @Schema(description = "新建任务主键 biz_file_task.id,须写入队列消息 data.taskId", example = "200") + private Long taskId; + + @Schema(description = "各店一条结果快照,含 resultId、taskId、店名及初始 taskStatus=RUNNING 等") + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskDashboardVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskDashboardVo.java new file mode 100644 index 0000000..316b6e7 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskDashboardVo.java @@ -0,0 +1,26 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "商品风险模块统计看板(当前用户维度)") +public class ProductRiskDashboardVo { + + @JsonProperty("candidateCount") + @Schema(description = "备选店铺条数(biz_product_risk_shop_candidate)") + private long candidateCount; + + @JsonProperty("processedTaskCount") + @Schema(description = "已结束任务数:状态为 SUCCESS 或 FAILED 的商品风险任务总数") + private long processedTaskCount; + + @JsonProperty("successTaskCount") + @Schema(description = "成功结束的任务数(状态 SUCCESS)") + private long successTaskCount; + + @JsonProperty("failedTaskCount") + @Schema(description = "失败结束的任务数(状态 FAILED)") + private long failedTaskCount; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskHistoryVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskHistoryVo.java new file mode 100644 index 0000000..2611ca0 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskHistoryVo.java @@ -0,0 +1,15 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "处理记录列表响应体:含进行中与已结束任务下的各店结果行") +public class ProductRiskHistoryVo { + + @Schema(description = "按店铺拆分的结果项列表,默认最多返回 100 条,按创建时间倒序") + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskMatchShopsVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskMatchShopsVo.java new file mode 100644 index 0000000..e1cdd05 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskMatchShopsVo.java @@ -0,0 +1,15 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "批量匹配响应体:items 与请求 shop_names 顺序一致") +public class ProductRiskMatchShopsVo { + + @Schema(description = "各店匹配结果列表,一项对应请求中的一个店名") + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskPendingDeleteVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskPendingDeleteVo.java new file mode 100644 index 0000000..bb860cb --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskPendingDeleteVo.java @@ -0,0 +1,12 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "DELETE /pending-shop-result 响应:告知是否在库中删除了运行中任务下的一条店铺结果") +public class ProductRiskPendingDeleteVo { + + @Schema(description = "true:已删除一条匹配到的 biz_file_result 并已重算父任务;false:无匹配记录(未创建任务或任务已结束或店名无对应行)") + private boolean removed; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java new file mode 100644 index 0000000..01cebec --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskResultItemVo.java @@ -0,0 +1,60 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "单店结果项:列表接口与任务详情中共用,对应 biz_file_result 一行 + 任务/请求衍生字段") +public class ProductRiskResultItemVo { + + @Schema(description = "结果行主键 biz_file_result.id;删除单条、下载 zip 时使用", example = "1001") + private Long resultId; + + @Schema(description = "所属任务 id biz_file_task.id", example = "200") + private Long taskId; + + @JsonProperty("shopName") + @Schema(description = "店铺名称(列表接口中可能与库内规范化名一致;详情中会尽量合并创建任务时的展示名)") + private String shopName; + + @JsonProperty("shopId") + @Schema(description = "店铺 ID(紫鸟)") + private String shopId; + + @Schema(description = "平台") + private String platform; + + @JsonProperty("companyName") + @Schema(description = "公司名称") + private String companyName; + + @Schema(description = "创建任务时是否已匹配(列表中一般为 true)") + private boolean matched; + + @JsonProperty("matchStatus") + @Schema(description = "匹配状态码,含义同 ProductRiskShopQueueItemVo.matchStatus") + private String matchStatus; + + @JsonProperty("matchMessage") + @Schema(description = "匹配说明文案") + private String matchMessage; + + @JsonProperty("taskStatus") + @Schema(description = "所属任务当前状态:RUNNING / SUCCESS / FAILED,与各店行一致") + private String taskStatus; + + @Schema(description = "该店是否已成功生成结果文件;null 表示未出终态时可不按布尔处理") + private Boolean success; + + @Schema(description = "该店失败时的错误信息") + private String error; + + @JsonProperty("outputFilename") + @Schema(description = "生成的 zip 文件名(成功后有值)") + private String outputFilename; + + @JsonProperty("downloadUrl") + @Schema(description = "预签名下载 URL(列表里可能带;直链下载也可用 GET /results/{resultId}/download)") + private String downloadUrl; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskShopQueueItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskShopQueueItemVo.java new file mode 100644 index 0000000..17fa8f0 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskShopQueueItemVo.java @@ -0,0 +1,48 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * 与 Python 队列约定字段对齐,供前端原样推入 enqueue_json。 + */ +@Data +@Schema(description = "单店匹配结果(队列项):与 /match-shops 及创建任务请求 items 元素结构一致,可嵌入队列 JSON data.items") +public class ProductRiskShopQueueItemVo { + + @JsonProperty("shopName") + @Schema(description = "店铺名称", example = "某某店") + private String shopName; + + @Schema(description = "是否命中紫鸟索引;false 时不可用于创建任务") + private boolean matched; + + @JsonProperty("shopId") + @Schema(description = "紫鸟侧店铺 ID(字符串),未命中时可能为空") + private String shopId; + + @Schema(description = "平台,如 亚马逊", example = "亚马逊") + private String platform; + + @JsonProperty("companyName") + @Schema(description = "公司名称或主体标识") + private String companyName; + + @JsonProperty("openStoreUrl") + @Schema(description = "打开店铺的地址(由 Python 侧消费)") + private String openStoreUrl; + + @JsonProperty("matchedUserId") + @Schema(description = "索引关联到的用户 ID(若有)") + private Long matchedUserId; + + @JsonProperty("matchStatus") + @Schema( + description = "匹配状态码:如 MATCHED、PENDING、CONFLICT、INDEX_STALE 等,以后端为准。") + private String matchStatus; + + @JsonProperty("matchMessage") + @Schema(description = "人类可读说明,供前端展示") + private String matchMessage; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskBatchVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskBatchVo.java new file mode 100644 index 0000000..774cfd1 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskBatchVo.java @@ -0,0 +1,18 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "批量任务查询响应:每个 id 一条详情;无效 id 记入 missingTaskIds") +public class ProductRiskTaskBatchVo { + + @Schema(description = "与请求 taskIds 顺序不一定一致;仅包含存在且模块类型为商品风险的任务") + private List items = new ArrayList<>(); + + @Schema(description = "请求中存在但数据库不存在或非商品风险模块的 taskId 列表") + private List missingTaskIds = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskDetailVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskDetailVo.java new file mode 100644 index 0000000..61c59da --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskDetailVo.java @@ -0,0 +1,18 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "单个任务详情:任务级概要 + 下属各店结果行") +public class ProductRiskTaskDetailVo { + + @Schema(description = "任务级字段:id、状态、错误信息、时间等") + private ProductRiskTaskItemVo task = new ProductRiskTaskItemVo(); + + @Schema(description = "该任务下每个店铺一条结果记录,顺序一般按结果表 id 升序") + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java new file mode 100644 index 0000000..b313a18 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/model/vo/ProductRiskTaskItemVo.java @@ -0,0 +1,36 @@ +package com.nanri.aiimage.modules.productrisk.model.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "商品风险任务概要(biz_file_task 核心字段)") +public class ProductRiskTaskItemVo { + + @Schema(description = "任务主键", example = "200") + private Long id; + + @JsonProperty("taskNo") + @Schema(description = "业务单号,如 PRODUCT_RISK_RESOLVE-雪花 id") + private String taskNo; + + @Schema(description = "任务状态:RUNNING 执行中;SUCCESS 已结束且至少一店成功;FAILED 已结束且全部失败或整体失败") + private String status; + + @JsonProperty("errorMessage") + @Schema(description = "失败或部分失败时的汇总错误说明;成功且无附加信息时可能为空") + private String errorMessage; + + @JsonProperty("createdAt") + @Schema(description = "创建时间(字符串格式,服务端 LocalDateTime.toString())") + private String createdAt; + + @JsonProperty("updatedAt") + @Schema(description = "最后更新时间") + private String updatedAt; + + @JsonProperty("finishedAt") + @Schema(description = "结束时间;RUNNING 时通常为空") + private String finishedAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskExcelAssemblyService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskExcelAssemblyService.java new file mode 100644 index 0000000..06e1602 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskExcelAssemblyService.java @@ -0,0 +1,110 @@ +package com.nanri.aiimage.modules.productrisk.service; + +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Service +@Slf4j +public class ProductRiskExcelAssemblyService { + + private static final List SHEET_ORDER = java.util.Arrays.stream(ProductRiskCountryCode.values()) + .map(ProductRiskCountryCode::getSheetName) + .toList(); + + private static final String[] HEADER = { + "店铺名", + "商品ASIN/SKU", + "状态", + "完成", + "移除ASIN", + "移除状态" + }; + + public void writeWorkbook(File outputXlsx, String shopDisplayName, Map> countries) { + Map> safe = countries == null ? Map.of() : countries; + try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream fos = new FileOutputStream(outputXlsx)) { + for (String sheetName : SHEET_ORDER) { + Sheet sheet = wb.createSheet(sheetName); + Row headerRow = sheet.createRow(0); + for (int c = 0; c < HEADER.length; c++) { + headerRow.createCell(c).setCellValue(HEADER[c]); + } + List rows = safe.getOrDefault(sheetName, List.of()); + int rowIdx = 1; + for (ProductRiskRowDto dto : rows) { + Row row = sheet.createRow(rowIdx++); + createTextCell(row, 0, firstNonBlank(dto == null ? null : dto.getShopName(), shopDisplayName)); + createTextCell(row, 1, dto == null ? null : dto.getProductAsinSku()); + createTextCell(row, 2, dto == null ? null : dto.getStatus()); + createTextCell(row, 3, dto == null ? null : dto.getDone()); + createTextCell(row, 4, dto == null ? null : dto.getRemoveAsin()); + createTextCell(row, 5, dto == null ? null : dto.getRemoveStatus()); + } + for (int i = 0; i < HEADER.length; i++) { + sheet.autoSizeColumn(i); + } + } + wb.write(fos); + } catch (BusinessException ex) { + throw ex; + } catch (Exception ex) { + log.warn("[product-risk] write workbook failed: {}", ex.getMessage()); + throw new BusinessException("生成 Excel 失败: " + ex.getMessage()); + } + } + + public int countRows(Map> countries) { + if (countries == null || countries.isEmpty()) { + return 0; + } + int n = 0; + for (List list : countries.values()) { + if (list != null) { + n += list.size(); + } + } + return n; + } + + /** + * 将接口中的 {@link ProductRiskCountryCode} 键转为 Excel 中文工作表名 → 行列表。 + */ + public Map> normalizeCountriesMap(Map> raw) { + if (raw == null || raw.isEmpty()) { + return new LinkedHashMap<>(); + } + Map> out = new LinkedHashMap<>(); + for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) { + List rows = raw.get(code); + if (rows != null) { + out.put(code.getSheetName(), rows); + } + } + return out; + } + + private static void createTextCell(Row row, int index, String value) { + Cell cell = row.createCell(index); + cell.setCellValue(value == null ? "" : value); + } + + private static String firstNonBlank(String primary, String fallback) { + if (primary != null && !primary.isBlank()) { + return primary; + } + return fallback == null ? "" : fallback; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskResolveService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskResolveService.java new file mode 100644 index 0000000..002ac48 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskResolveService.java @@ -0,0 +1,284 @@ +package com.nanri.aiimage.modules.productrisk.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.productrisk.mapper.ProductRiskCountryPrefMapper; +import com.nanri.aiimage.modules.productrisk.mapper.ProductRiskShopCandidateMapper; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest; +import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskCountryPrefEntity; +import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskShopCandidateEntity; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo; +import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo; +import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService; +import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +public class ProductRiskResolveService { + + /** + * 默认处理顺序:德国 → 英国 → 法国 → 意大利 → 西班牙(与前端一致)。 + */ + public static final List DEFAULT_COUNTRY_PREFERENCE_ORDER = List.of("DE", "UK", "FR", "IT", "ES"); + + private final ProductRiskShopCandidateMapper candidateMapper; + private final ProductRiskCountryPrefMapper countryPrefMapper; + private final ObjectMapper objectMapper; + private final ZiniaoShopSwitchService ziniaoShopSwitchService; + + public List listCandidates(Long userId) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + List rows = candidateMapper.selectList( + new LambdaQueryWrapper() + .eq(ProductRiskShopCandidateEntity::getUserId, userId) + .orderByDesc(ProductRiskShopCandidateEntity::getId)); + List list = new ArrayList<>(); + for (ProductRiskShopCandidateEntity row : rows) { + if (row == null) { + continue; + } + ProductRiskCandidateVo vo = new ProductRiskCandidateVo(); + vo.setId(row.getId()); + vo.setShopName(row.getShopName()); + vo.setCreatedAt(row.getCreatedAt()); + list.add(vo); + } + return list; + } + + @Transactional + public ProductRiskCandidateVo addCandidate(ProductRiskCandidateAddRequest request) { + if (request.getUserId() == null || request.getUserId() <= 0) { + throw new BusinessException("user_id 不合法"); + } + String normalized = ziniaoShopSwitchService.normalizeShopName(request.getShopName()); + if (normalized.isBlank()) { + throw new BusinessException("店铺名不能为空"); + } + ZiniaoShopMatchResultVo indexHit = ziniaoShopSwitchService.findIndexedStoreByName(normalized, false); + if (indexHit == null || !indexHit.isMatched()) { + String hint = indexHit != null && indexHit.getMatchMessage() != null && !indexHit.getMatchMessage().isBlank() + ? indexHit.getMatchMessage() + : "店铺索引未命中,无法加入备选"; + throw new BusinessException(hint); + } + if (ZiniaoShopIndexService.MATCH_STATUS_CONFLICT.equals(indexHit.getMatchStatus())) { + throw new BusinessException(indexHit.getMatchMessage() != null ? indexHit.getMatchMessage() : "存在多个同名店铺,请人工确认"); + } + ProductRiskShopCandidateEntity existing = candidateMapper.selectOne( + new LambdaQueryWrapper() + .eq(ProductRiskShopCandidateEntity::getUserId, request.getUserId()) + .eq(ProductRiskShopCandidateEntity::getShopName, normalized) + .last("LIMIT 1")); + if (existing != null) { + ProductRiskCandidateVo vo = new ProductRiskCandidateVo(); + vo.setId(existing.getId()); + vo.setShopName(existing.getShopName()); + vo.setCreatedAt(existing.getCreatedAt()); + return vo; + } + ProductRiskShopCandidateEntity entity = new ProductRiskShopCandidateEntity(); + entity.setUserId(request.getUserId()); + entity.setShopName(normalized); + entity.setCreatedAt(LocalDateTime.now()); + candidateMapper.insert(entity); + ProductRiskCandidateVo vo = new ProductRiskCandidateVo(); + vo.setId(entity.getId()); + vo.setShopName(entity.getShopName()); + vo.setCreatedAt(entity.getCreatedAt()); + return vo; + } + + @Transactional + public void deleteCandidate(Long userId, Long id) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + if (id == null || id <= 0) { + throw new BusinessException("id 不合法"); + } + ProductRiskShopCandidateEntity row = candidateMapper.selectById(id); + if (row == null || !userId.equals(row.getUserId())) { + throw new BusinessException("记录不存在"); + } + candidateMapper.deleteById(id); + } + + public ProductRiskMatchShopsVo matchShops(ProductRiskMatchShopsRequest request) { + if (request.getUserId() == null || request.getUserId() <= 0) { + throw new BusinessException("user_id 不合法"); + } + LinkedHashSet ordered = new LinkedHashSet<>(); + for (String raw : request.getShopNames()) { + String n = ziniaoShopSwitchService.normalizeShopName(raw); + if (!n.isBlank()) { + ordered.add(n); + } + } + if (ordered.isEmpty()) { + throw new BusinessException("shop_names 无有效店铺名"); + } + ProductRiskMatchShopsVo vo = new ProductRiskMatchShopsVo(); + for (String shopName : ordered) { + vo.getItems().add(matchOneShop(shopName)); + } + return vo; + } + + public ProductRiskCountryPreferenceVo getCountryPreference(Long userId) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + ProductRiskCountryPrefEntity row = countryPrefMapper.selectById(userId); + ProductRiskCountryPreferenceVo vo = new ProductRiskCountryPreferenceVo(); + if (row == null || row.getCountryCodesJson() == null || row.getCountryCodesJson().isBlank()) { + vo.getCountryCodes().addAll(DEFAULT_COUNTRY_PREFERENCE_ORDER); + return vo; + } + try { + List parsed = objectMapper.readValue(row.getCountryCodesJson(), new TypeReference>() { + }); + vo.getCountryCodes().addAll(sanitizeStoredCodes(parsed)); + } catch (Exception ex) { + vo.getCountryCodes().addAll(DEFAULT_COUNTRY_PREFERENCE_ORDER); + } + return vo; + } + + @Transactional + public ProductRiskCountryPreferenceVo saveCountryPreference(ProductRiskCountryPreferenceSaveRequest request) { + if (request.getUserId() == null || request.getUserId() <= 0) { + throw new BusinessException("user_id 不合法"); + } + List normalized = validateCountryCodesForSave(request.getCountryCodes()); + String json; + try { + json = objectMapper.writeValueAsString(normalized); + } catch (Exception ex) { + throw new BusinessException("保存偏好失败"); + } + ProductRiskCountryPrefEntity row = countryPrefMapper.selectById(request.getUserId()); + if (row == null) { + row = new ProductRiskCountryPrefEntity(); + row.setUserId(request.getUserId()); + row.setCountryCodesJson(json); + countryPrefMapper.insert(row); + } else { + row.setCountryCodesJson(json); + countryPrefMapper.updateById(row); + } + ProductRiskCountryPreferenceVo vo = new ProductRiskCountryPreferenceVo(); + vo.getCountryCodes().addAll(normalized); + return vo; + } + + private static List sanitizeStoredCodes(List raw) { + List parsed = parseValidCountryCodes(raw); + if (parsed.isEmpty()) { + return new ArrayList<>(DEFAULT_COUNTRY_PREFERENCE_ORDER); + } + return parsed; + } + + private static List validateCountryCodesForSave(List raw) { + if (raw == null || raw.isEmpty()) { + throw new BusinessException("country_codes 至少选择 1 个国家"); + } + LinkedHashSet seen = new LinkedHashSet<>(); + List out = new ArrayList<>(); + for (String s : raw) { + if (s == null || s.isBlank()) { + throw new BusinessException("country_codes 含空项"); + } + String u = s.trim().toUpperCase(); + try { + ProductRiskCountryCode.valueOf(u); + } catch (IllegalArgumentException ex) { + throw new BusinessException("非法国家代码: " + s); + } + if (!seen.add(u)) { + throw new BusinessException("country_codes 存在重复: " + u); + } + out.add(u); + } + if (out.size() > ProductRiskCountryCode.values().length) { + throw new BusinessException("country_codes 最多 5 项"); + } + return out; + } + + /** + * 仅保留合法枚举名,去重并保持顺序;非法项静默丢弃(用于读取库内数据)。 + */ + private static List parseValidCountryCodes(List raw) { + if (raw == null || raw.isEmpty()) { + return new ArrayList<>(); + } + LinkedHashSet seen = new LinkedHashSet<>(); + List out = new ArrayList<>(); + for (String s : raw) { + if (s == null || s.isBlank()) { + continue; + } + String u = s.trim().toUpperCase(); + try { + ProductRiskCountryCode.valueOf(u); + } catch (IllegalArgumentException ex) { + continue; + } + if (seen.add(u)) { + out.add(u); + } + } + return out; + } + + private ProductRiskShopQueueItemVo matchOneShop(String shopName) { + ProductRiskShopQueueItemVo item = new ProductRiskShopQueueItemVo(); + item.setShopName(shopName); + try { + ZiniaoShopMatchResultVo m = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); + if (m == null) { + item.setMatched(false); + item.setMatchStatus("PENDING"); + item.setMatchMessage("匹配结果为空"); + return item; + } + item.setMatched(m.isMatched()); + item.setShopId(m.getShopId()); + item.setPlatform(m.getPlatform()); + item.setCompanyName(m.getCompanyName()); + item.setMatchedUserId(m.getMatchedUserId()); + item.setMatchStatus(m.getMatchStatus()); + item.setMatchMessage(m.getMatchMessage()); + } catch (BusinessException ex) { + item.setMatched(false); + item.setMatchStatus("PENDING"); + item.setMatchMessage(ex.getMessage()); + } catch (Exception ex) { + item.setMatched(false); + item.setMatchStatus("PENDING"); + item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常")); + } + return item; + } +} 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 new file mode 100644 index 0000000..fe64cc6 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java @@ -0,0 +1,634 @@ +package com.nanri.aiimage.modules.productrisk.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.file.service.oss.OssStorageService; +import com.nanri.aiimage.modules.productrisk.mapper.ProductRiskShopCandidateMapper; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCreateTaskRequest; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskShopPayloadDto; +import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskSubmitResultRequest; +import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskShopCandidateEntity; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCreateTaskVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskResultItemVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskDetailVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskPendingDeleteVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskItemVo; +import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo; +import com.nanri.aiimage.modules.task.mapper.FileResultMapper; +import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; +import com.nanri.aiimage.modules.task.model.entity.FileResultEntity; +import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity; +import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ZipUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.File; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +@Slf4j +public class ProductRiskTaskService { + + private static final String MODULE_TYPE = "PRODUCT_RISK_RESOLVE"; + private static final String CONTENT_TYPE_ZIP = "application/zip"; + + private final FileTaskMapper fileTaskMapper; + private final FileResultMapper fileResultMapper; + private final ProductRiskShopCandidateMapper candidateMapper; + private final ZiniaoShopSwitchService ziniaoShopSwitchService; + private final ProductRiskExcelAssemblyService excelAssemblyService; + private final OssStorageService ossStorageService; + private final ObjectMapper objectMapper; + + public ProductRiskDashboardVo dashboard(Long userId) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + ProductRiskDashboardVo vo = new ProductRiskDashboardVo(); + vo.setCandidateCount(candidateMapper.selectCount(new LambdaQueryWrapper() + .eq(ProductRiskShopCandidateEntity::getUserId, userId))); + Long processed = fileTaskMapper.selectCount(new LambdaQueryWrapper() + .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getUserId, userId) + .in(FileTaskEntity::getStatus, List.of("SUCCESS", "FAILED"))); + Long success = fileTaskMapper.selectCount(new LambdaQueryWrapper() + .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getUserId, userId) + .eq(FileTaskEntity::getStatus, "SUCCESS")); + Long failed = fileTaskMapper.selectCount(new LambdaQueryWrapper() + .eq(FileTaskEntity::getModuleType, MODULE_TYPE) + .eq(FileTaskEntity::getUserId, userId) + .eq(FileTaskEntity::getStatus, "FAILED")); + vo.setProcessedTaskCount(processed == null ? 0L : processed); + vo.setSuccessTaskCount(success == null ? 0L : success); + vo.setFailedTaskCount(failed == null ? 0L : failed); + return vo; + } + + public ProductRiskHistoryVo listHistory(Long userId) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + ProductRiskHistoryVo vo = new ProductRiskHistoryVo(); + List entities = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .eq(FileResultEntity::getUserId, userId) + .orderByDesc(FileResultEntity::getCreatedAt) + .last("limit 100")); + Map statusByTaskId = new LinkedHashMap<>(); + List taskIds = entities.stream() + .map(FileResultEntity::getTaskId) + .filter(id -> id != null && id > 0) + .distinct() + .toList(); + if (!taskIds.isEmpty()) { + List tasks = fileTaskMapper.selectBatchIds(taskIds); + for (FileTaskEntity t : tasks) { + if (t != null) { + statusByTaskId.put(t.getId(), t.getStatus()); + } + } + } + List items = new ArrayList<>(); + for (FileResultEntity entity : entities) { + items.add(toHistoryItemVo(entity, statusByTaskId.get(entity.getTaskId()))); + } + vo.setItems(items); + return vo; + } + + @Transactional + public void deleteHistory(Long resultId, Long userId) { + if (userId == null || userId <= 0) { + 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("记录不存在"); + } + Long taskId = entity.getTaskId(); + fileResultMapper.deleteById(resultId); + if (taskId != null && taskId > 0) { + reconcileTaskAfterResultRemoval(taskId); + } + } + + /** + * 删除整条商品风险任务及其下所有店铺结果(运行中或已结束均可,需归属当前用户)。 + */ + @Transactional + public void deleteTask(Long taskId, Long userId) { + if (userId == null || userId <= 0) { + 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("任务不存在"); + } + fileResultMapper.delete(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE)); + fileTaskMapper.deleteById(taskId); + } + + /** + * 从用户当前「运行中」的商品风险任务里,按规范化店铺名删除一条结果(用于前端移除匹配列表后同步后端)。 + * 若无对应记录则 removed=false。 + */ + @Transactional + public ProductRiskPendingDeleteVo deletePendingShopResult(Long userId, String shopName) { + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + if (shopName == null || shopName.isBlank()) { + throw new BusinessException("shop_name 不能为空"); + } + String norm = ziniaoShopSwitchService.normalizeShopName(shopName); + if (norm.isBlank()) { + throw new BusinessException("店铺名无效"); + } + List candidates = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getUserId, userId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .eq(FileResultEntity::getSourceFilename, norm) + .orderByDesc(FileResultEntity::getId) + .last("limit 30")); + ProductRiskPendingDeleteVo vo = new ProductRiskPendingDeleteVo(); + vo.setRemoved(false); + for (FileResultEntity fr : candidates) { + if (fr.getTaskId() == null) { + continue; + } + FileTaskEntity t = fileTaskMapper.selectById(fr.getTaskId()); + if (t == null || !MODULE_TYPE.equals(t.getModuleType()) || !userId.equals(t.getUserId())) { + continue; + } + if (!"RUNNING".equals(t.getStatus())) { + continue; + } + Long tid = fr.getTaskId(); + fileResultMapper.deleteById(fr.getId()); + reconcileTaskAfterResultRemoval(tid); + vo.setRemoved(true); + return vo; + } + return vo; + } + + /** + * 删除一条 file_result 后重算父任务状态;若无剩余结果则删除任务。 + */ + private void reconcileTaskAfterResultRemoval(Long taskId) { + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + return; + } + List latest = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + if (latest.isEmpty()) { + fileTaskMapper.deleteById(taskId); + return; + } + int ok = 0; + int fail = 0; + List allErrors = new ArrayList<>(); + boolean allDone = true; + for (FileResultEntity fr : latest) { + boolean success = fr.getSuccess() != null && fr.getSuccess() == 1; + boolean failed = fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank(); + if (success) { + ok++; + } else if (failed) { + fail++; + allErrors.add(fr.getSourceFilename() + ": " + fr.getErrorMessage()); + } else { + allDone = false; + } + } + task.setSourceFileCount(latest.size()); + task.setSuccessFileCount(ok); + task.setFailedFileCount(fail); + task.setUpdatedAt(LocalDateTime.now()); + if (!allDone) { + task.setStatus("RUNNING"); + task.setErrorMessage(null); + task.setFinishedAt(null); + } else if (ok > 0 && fail == 0) { + task.setStatus("SUCCESS"); + task.setErrorMessage(null); + task.setFinishedAt(LocalDateTime.now()); + } else if (ok > 0) { + task.setStatus("SUCCESS"); + task.setErrorMessage(String.join(";", allErrors)); + task.setFinishedAt(LocalDateTime.now()); + } else { + task.setStatus("FAILED"); + task.setErrorMessage(allErrors.isEmpty() ? "全部店铺处理失败" : String.join(";", allErrors)); + task.setFinishedAt(LocalDateTime.now()); + } + try { + task.setResultJson(objectMapper.writeValueAsString(buildSnapshotFromDb(taskId, task.getStatus()))); + } catch (Exception ex) { + log.warn("[product-risk] compact result json failed: {}", ex.getMessage()); + } + fileTaskMapper.updateById(task); + } + + public ProductRiskTaskBatchVo getTaskDetailsBatch(List taskIds) { + ProductRiskTaskBatchVo batch = new ProductRiskTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + batch.getItems().add(buildTaskDetail(task)); + } + return batch; + } + + 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("记录不存在"); + } + if (entity.getResultFileUrl() == null || entity.getResultFileUrl().isBlank()) { + throw new BusinessException("暂无可下载文件"); + } + return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl()); + } + + 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("记录不存在"); + } + if (entity.getResultFilename() != null && !entity.getResultFilename().isBlank()) { + return entity.getResultFilename(); + } + return safeFileStem(entity.getSourceFilename()) + ".zip"; + } + + @Transactional + public ProductRiskCreateTaskVo createTask(ProductRiskCreateTaskRequest request) { + if (request.getUserId() == null || request.getUserId() <= 0) { + throw new BusinessException("user_id 不合法"); + } + if (request.getItems() == null || request.getItems().isEmpty()) { + throw new BusinessException("items 不能为空"); + } + List uniqueItems = dedupeQueueItems(request.getItems()); + if (uniqueItems.isEmpty()) { + throw new BusinessException("items 不能为空"); + } + for (ProductRiskShopQueueItemVo item : uniqueItems) { + if (item == null || !item.isMatched()) { + String name = item == null ? "" : Objects.toString(item.getShopName(), ""); + throw new BusinessException("存在未匹配店铺,无法创建任务: " + name); + } + } + + FileTaskEntity task = new FileTaskEntity(); + task.setTaskNo(MODULE_TYPE + "-" + IdUtil.getSnowflakeNextIdStr()); + task.setModuleType(MODULE_TYPE); + task.setTaskMode("PYTHON_QUEUE"); + task.setStatus("RUNNING"); + task.setSourceFileCount(uniqueItems.size()); + task.setSuccessFileCount(0); + task.setFailedFileCount(0); + task.setCreatedBy("user:" + request.getUserId()); + task.setUserId(request.getUserId()); + task.setCreatedAt(LocalDateTime.now()); + task.setUpdatedAt(LocalDateTime.now()); + fileTaskMapper.insert(task); + + List snapshot = new ArrayList<>(); + for (ProductRiskShopQueueItemVo item : uniqueItems) { + String norm = ziniaoShopSwitchService.normalizeShopName(item.getShopName()); + if (norm.isBlank()) { + throw new BusinessException("店铺名无效"); + } + FileResultEntity fr = new FileResultEntity(); + fr.setTaskId(task.getId()); + fr.setModuleType(MODULE_TYPE); + fr.setSourceFilename(norm); + fr.setSourceFileUrl(item.getShopId()); + fr.setUserId(request.getUserId()); + fr.setSuccess(0); + fr.setCreatedAt(LocalDateTime.now()); + fileResultMapper.insert(fr); + snapshot.add(toSnapshotVo(fr, item, task.getStatus())); + } + + try { + ProductRiskCreateTaskRequest persisted = new ProductRiskCreateTaskRequest(); + persisted.setUserId(request.getUserId()); + persisted.setItems(uniqueItems); + task.setRequestJson(objectMapper.writeValueAsString(persisted)); + task.setResultJson(objectMapper.writeValueAsString(snapshot)); + } catch (Exception ex) { + throw new BusinessException("序列化任务数据失败"); + } + fileTaskMapper.updateById(task); + + ProductRiskCreateTaskVo vo = new ProductRiskCreateTaskVo(); + vo.setTaskId(task.getId()); + vo.setItems(snapshot); + return vo; + } + + @Transactional + public void submitResult(Long taskId, ProductRiskSubmitResultRequest request) { + if (taskId == null || taskId <= 0) { + throw new BusinessException("taskId 不合法"); + } + if (request == null || request.getShops() == null || request.getShops().isEmpty()) { + throw new BusinessException("shops 不能为空"); + } + + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + throw new BusinessException("任务不存在"); + } + if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { + throw new BusinessException("任务已结束,拒绝重复提交"); + } + + List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + + Map payloadByShop = new LinkedHashMap<>(); + for (ProductRiskShopPayloadDto p : request.getShops()) { + if (p == null) { + continue; + } + String key = ziniaoShopSwitchService.normalizeShopName(p.getShopName()); + if (!key.isBlank()) { + payloadByShop.put(key, p); + } + } + + File workRoot = FileUtil.mkdir(FileUtil.file(System.getProperty("java.io.tmpdir"), "product-risk-result", String.valueOf(taskId))); + + List batchErrors = new ArrayList<>(); + + for (FileResultEntity fr : resultRows) { + String shopKey = fr.getSourceFilename(); + ProductRiskShopPayloadDto payload = shopKey == null ? null : payloadByShop.get(shopKey); + if (payload == null) { + // 与删除品牌一致:支持队列逐条处理、分次回传,未在本次 payload 中的店铺保持待处理 + continue; + } + if (payload.getError() != null && !payload.getError().isBlank()) { + markResultFailed(fr, payload.getError()); + batchErrors.add(shopKey + ": " + payload.getError()); + continue; + } + try { + Map> countries = excelAssemblyService.normalizeCountriesMap(payload.getCountries()); + String displayName = payload.getShopName() != null && !payload.getShopName().isBlank() + ? payload.getShopName().trim() + : shopKey; + String stem = safeFileStem(displayName); + File xlsx = FileUtil.file(workRoot, stem + ".xlsx"); + excelAssemblyService.writeWorkbook(xlsx, displayName, countries); + File zip = FileUtil.file(workRoot, stem + ".zip"); + ZipUtil.zip(zip, false, xlsx); + String objectKey = ossStorageService.uploadResultFile(zip, MODULE_TYPE); + fr.setResultFilename(stem + ".zip"); + fr.setResultFileUrl(objectKey); + fr.setResultFileSize(zip.length()); + fr.setResultContentType(CONTENT_TYPE_ZIP); + fr.setRowCount(excelAssemblyService.countRows(countries)); + fr.setSuccess(1); + fr.setErrorMessage(null); + fileResultMapper.updateById(fr); + FileUtil.del(xlsx); + FileUtil.del(zip); + } catch (Exception ex) { + log.warn("[product-risk] shop assemble failed taskId={} shop={} msg={}", taskId, shopKey, ex.getMessage()); + markResultFailed(fr, ex.getMessage() == null ? "组装失败" : ex.getMessage()); + batchErrors.add(shopKey + ": " + ex.getMessage()); + } + } + + List latest = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + + int ok = 0; + int fail = 0; + List allErrors = new ArrayList<>(); + boolean allDone = true; + for (FileResultEntity fr : latest) { + boolean success = fr.getSuccess() != null && fr.getSuccess() == 1; + boolean failed = fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank(); + if (success) { + ok++; + } else if (failed) { + fail++; + allErrors.add(fr.getSourceFilename() + ": " + fr.getErrorMessage()); + } else { + allDone = false; + } + } + + task.setSuccessFileCount(ok); + task.setFailedFileCount(fail); + task.setUpdatedAt(LocalDateTime.now()); + + if (!allDone) { + task.setStatus("RUNNING"); + task.setErrorMessage(null); + task.setFinishedAt(null); + } else if (ok > 0 && fail == 0) { + task.setStatus("SUCCESS"); + task.setErrorMessage(null); + task.setFinishedAt(LocalDateTime.now()); + } else if (ok > 0) { + task.setStatus("SUCCESS"); + task.setErrorMessage(String.join(";", allErrors.isEmpty() ? batchErrors : allErrors)); + task.setFinishedAt(LocalDateTime.now()); + } else { + task.setStatus("FAILED"); + task.setErrorMessage(allErrors.isEmpty() ? "全部店铺处理失败" : String.join(";", allErrors)); + task.setFinishedAt(LocalDateTime.now()); + } + try { + task.setResultJson(objectMapper.writeValueAsString(buildSnapshotFromDb(taskId, task.getStatus()))); + } catch (Exception ex) { + log.warn("[product-risk] compact result json failed: {}", ex.getMessage()); + } + fileTaskMapper.updateById(task); + } + + private void markResultFailed(FileResultEntity fr, String message) { + fr.setSuccess(0); + fr.setErrorMessage(message); + fr.setResultFilename(null); + fr.setResultFileUrl(null); + fr.setResultFileSize(0L); + fileResultMapper.updateById(fr); + } + + private ProductRiskTaskDetailVo buildTaskDetail(FileTaskEntity task) { + ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + List rows = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, task.getId()) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + for (FileResultEntity fr : rows) { + detail.getItems().add(toHistoryItemVo(fr, task.getStatus())); + } + return detail; + } + + private List buildSnapshotFromDb(Long taskId, String taskStatus) { + List rows = fileResultMapper.selectList(new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + List list = new ArrayList<>(); + for (FileResultEntity fr : rows) { + list.add(toHistoryItemVo(fr, taskStatus)); + } + return list; + } + + private ProductRiskTaskItemVo toTaskItemVo(FileTaskEntity task) { + ProductRiskTaskItemVo vo = new ProductRiskTaskItemVo(); + vo.setId(task.getId()); + vo.setTaskNo(task.getTaskNo()); + vo.setStatus(task.getStatus()); + vo.setErrorMessage(task.getErrorMessage()); + vo.setCreatedAt(fmt(task.getCreatedAt())); + vo.setUpdatedAt(fmt(task.getUpdatedAt())); + vo.setFinishedAt(fmt(task.getFinishedAt())); + return vo; + } + + private ProductRiskResultItemVo toSnapshotVo(FileResultEntity fr, ProductRiskShopQueueItemVo item, String taskStatus) { + ProductRiskResultItemVo vo = new ProductRiskResultItemVo(); + vo.setResultId(fr.getId()); + vo.setTaskId(fr.getTaskId()); + vo.setShopName(item.getShopName()); + vo.setShopId(item.getShopId()); + vo.setPlatform(item.getPlatform()); + vo.setCompanyName(item.getCompanyName()); + vo.setMatched(item.isMatched()); + vo.setMatchStatus(item.getMatchStatus()); + vo.setMatchMessage(item.getMatchMessage()); + vo.setTaskStatus(taskStatus); + vo.setSuccess(false); + vo.setError(null); + vo.setOutputFilename(null); + vo.setDownloadUrl(null); + return vo; + } + + private ProductRiskResultItemVo toHistoryItemVo(FileResultEntity entity, String taskStatus) { + ProductRiskResultItemVo vo = new ProductRiskResultItemVo(); + vo.setResultId(entity.getId()); + vo.setTaskId(entity.getTaskId()); + vo.setShopName(entity.getSourceFilename()); + vo.setShopId(entity.getSourceFileUrl()); + vo.setTaskStatus(taskStatus); + boolean ok = entity.getSuccess() != null && entity.getSuccess() == 1; + vo.setSuccess(ok); + vo.setError(entity.getErrorMessage()); + vo.setOutputFilename(entity.getResultFilename()); + vo.setDownloadUrl(entity.getResultFileUrl() == null || entity.getResultFileUrl().isBlank() + ? null + : ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl())); + vo.setMatched(true); + if (entity.getTaskId() != null) { + mergeQueueFieldsFromRequest(vo, entity.getTaskId()); + } + return vo; + } + + private void mergeQueueFieldsFromRequest(ProductRiskResultItemVo vo, Long taskId) { + FileTaskEntity t = fileTaskMapper.selectById(taskId); + if (t == null || t.getRequestJson() == null || t.getRequestJson().isBlank()) { + return; + } + try { + ProductRiskCreateTaskRequest req = objectMapper.readValue(t.getRequestJson(), ProductRiskCreateTaskRequest.class); + if (req.getItems() == null) { + return; + } + String key = ziniaoShopSwitchService.normalizeShopName(vo.getShopName()); + for (ProductRiskShopQueueItemVo item : req.getItems()) { + if (item == null) { + continue; + } + if (key.equals(ziniaoShopSwitchService.normalizeShopName(item.getShopName()))) { + vo.setShopName(item.getShopName()); + vo.setShopId(item.getShopId()); + vo.setPlatform(item.getPlatform()); + vo.setCompanyName(item.getCompanyName()); + vo.setMatchStatus(item.getMatchStatus()); + vo.setMatchMessage(item.getMatchMessage()); + break; + } + } + } catch (Exception ignored) { + } + } + + private static String fmt(LocalDateTime t) { + return t == null ? null : t.toString(); + } + + private List dedupeQueueItems(List raw) { + Map byNorm = new LinkedHashMap<>(); + for (ProductRiskShopQueueItemVo item : raw) { + if (item == null) { + continue; + } + String k = ziniaoShopSwitchService.normalizeShopName(item.getShopName()); + if (k.isBlank()) { + continue; + } + byNorm.putIfAbsent(k, item); + } + return new ArrayList<>(byNorm.values()); + } + + private static String safeFileStem(String shopName) { + String s = shopName == null ? "shop" : shopName.trim(); + if (s.isBlank()) { + s = "shop"; + } + return s.replaceAll("[\\\\/:*?\"<>|]", "_"); + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopIndexService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopIndexService.java index 3a42ad9..60df370 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopIndexService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopIndexService.java @@ -74,7 +74,10 @@ public class ZiniaoShopIndexService { return cursor; } - public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName) { + /** + * @param buildOpenStoreUrl 是否拼接紫鸟打开店铺 URL;商品风险等由 Python 侧自行拼地址时应传 false,避免多余鉴权调用且不因链接失败误判匹配状态。 + */ + public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName, boolean buildOpenStoreUrl) { String normalizedShopName = normalizeShopName(targetShopName); if (normalizedShopName.isBlank()) { return pendingResult("店铺名为空,无法匹配索引"); @@ -98,6 +101,20 @@ public class ZiniaoShopIndexService { return pendingResult("店铺索引信息不完整,请等待后台刷新"); } + if (!buildOpenStoreUrl) { + ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo(); + vo.setMatched(true); + vo.setShopId(entry.getShopId()); + vo.setShopName(entry.getShopName()); + vo.setCompanyName(entry.getCompanyName()); + vo.setPlatform(entry.getPlatform()); + vo.setMatchedUserId(entry.getMatchedUserId()); + vo.setOpenStoreUrl(null); + vo.setMatchStatus(isFresh(entry) ? MATCH_STATUS_MATCHED : MATCH_STATUS_STALE); + vo.setMatchMessage(isFresh(entry) ? null : "店铺索引已过保鲜期,请等待后台刷新"); + return vo; + } + String apiKey = findApiKeyByHash(entry.getApiKeyHash()); if (apiKey == null) { return pendingResult("店铺索引所依赖的紫鸟 key 已失效,请等待后台刷新"); @@ -134,6 +151,10 @@ public class ZiniaoShopIndexService { return vo; } + public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName) { + return findIndexedStoreByName(targetShopName, true); + } + public void refreshShopIndex() { long now = Instant.now().toEpochMilli(); ZiniaoShopIndexRefreshCursorDto previousCursor = ziniaoTransientCacheService diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopSwitchService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopSwitchService.java index a63fdb9..cf9629b 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopSwitchService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/ziniao/service/ZiniaoShopSwitchService.java @@ -34,6 +34,10 @@ public class ZiniaoShopSwitchService { return ziniaoShopIndexService.findIndexedStoreByName(targetShopName); } + public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName, boolean buildOpenStoreUrl) { + return ziniaoShopIndexService.findIndexedStoreByName(targetShopName, buildOpenStoreUrl); + } + public ZiniaoShopMatchResultVo emptyMatchResult() { ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo(); vo.setMatched(false); diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml index 858a1a9..ecc5f73 100644 --- a/backend-java/src/main/resources/application.yml +++ b/backend-java/src/main/resources/application.yml @@ -81,10 +81,11 @@ aiimage: heartbeat-timeout-minutes: ${AIIMAGE_DELETE_BRAND_HEARTBEAT_TIMEOUT_MINUTES:15} stale-check-cron: ${AIIMAGE_DELETE_BRAND_STALE_CHECK_CRON:0 */2 * * * *} finalize-check-cron: ${AIIMAGE_DELETE_BRAND_FINALIZE_CHECK_CRON:30 */2 * * * *} + product-risk-stale-timeout-hours: ${AIIMAGE_PRODUCT_RISK_STALE_TIMEOUT_HOURS:48} module-cleanup: enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true} cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *} - module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND} + module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE} ziniao: enabled: ${AIIMAGE_ZINIAO_ENABLED:false} base-url: ${AIIMAGE_ZINIAO_BASE_URL:https://sbappstoreapi.ziniao.com/openapi-router} diff --git a/backend-java/src/main/resources/db/V10__product_risk_country_pref.sql b/backend-java/src/main/resources/db/V10__product_risk_country_pref.sql new file mode 100644 index 0000000..85a605a --- /dev/null +++ b/backend-java/src/main/resources/db/V10__product_risk_country_pref.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS biz_product_risk_country_pref ( + user_id BIGINT NOT NULL PRIMARY KEY COMMENT '用户 ID', + country_codes_json VARCHAR(256) NOT NULL COMMENT 'JSON 数组:五国代码按处理顺序,如 ["DE","UK","FR"]', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' +) COMMENT='商品风险-用户五国处理顺序与勾选(子集)'; diff --git a/backend-java/src/main/resources/db/V9__product_risk_shop_candidate.sql b/backend-java/src/main/resources/db/V9__product_risk_shop_candidate.sql new file mode 100644 index 0000000..778616b --- /dev/null +++ b/backend-java/src/main/resources/db/V9__product_risk_shop_candidate.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS biz_product_risk_shop_candidate ( + id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键', + user_id BIGINT NOT NULL COMMENT '用户 ID', + shop_name VARCHAR(255) NOT NULL COMMENT '店铺名(已规范化)', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + UNIQUE KEY uk_user_shop (user_id, shop_name), + KEY idx_user_id (user_id) +) COMMENT='商品风险解决-用户备选店铺'; diff --git a/frontend-vue/product-risk.html b/frontend-vue/product-risk.html new file mode 100644 index 0000000..97c8101 --- /dev/null +++ b/frontend-vue/product-risk.html @@ -0,0 +1,12 @@ + + + + + + 商品风险解决 - 数富AI + + +
+ + + diff --git a/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue b/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue new file mode 100644 index 0000000..6e41ad4 --- /dev/null +++ b/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue @@ -0,0 +1,1487 @@ + + + + + diff --git a/frontend-vue/src/pages/brand/components/BrandTopBar.vue b/frontend-vue/src/pages/brand/components/BrandTopBar.vue index e6d25de..77b0e96 100644 --- a/frontend-vue/src/pages/brand/components/BrandTopBar.vue +++ b/frontend-vue/src/pages/brand/components/BrandTopBar.vue @@ -38,7 +38,7 @@