diff --git a/app/.env b/app/.env index 8a4270d..a8104b3 100644 --- a/app/.env +++ b/app/.env @@ -13,7 +13,7 @@ client_name=ShuFuAI # java_api_base=http://47.111.163.154:18080 -# java_api_base=http://127.0.0.1:18080 -java_api_base=http://8.136.19.173:18080 +java_api_base=http://127.0.0.1:18080 +# java_api_base=http://8.136.19.173:18080 diff --git a/app/amazon/__pycache__/del_brand.cpython-312.pyc b/app/amazon/__pycache__/del_brand.cpython-312.pyc index eabb299..755c69a 100644 Binary files a/app/amazon/__pycache__/del_brand.cpython-312.pyc and b/app/amazon/__pycache__/del_brand.cpython-312.pyc differ diff --git a/app/amazon/__pycache__/match_action.cpython-312.pyc b/app/amazon/__pycache__/match_action.cpython-312.pyc index 6555d3d..18b3b8a 100644 Binary files a/app/amazon/__pycache__/match_action.cpython-312.pyc and b/app/amazon/__pycache__/match_action.cpython-312.pyc differ diff --git a/app/assets/convert.js b/app/assets/convert.js index 28d4ed6..5785fc1 100644 --- a/app/assets/convert.js +++ b/app/assets/convert.js @@ -1 +1 @@ -import{d as A,o as H,a as n,c as o,b as z,B as K,e as s,F as w,r as F,t as r,f as _,n as E,w as M,s as j,u as q,g as u,h as T,x as J,i as k,E as i,y as L,z as O,A as G,_ as Q,p as W,q as X}from"./pywebview-D808cNhy.js";import{e as Y}from"./brand-DRn3N4FA.js";const Z={class:"page-shell module-page"},ee={class:"main-content"},se={class:"left-panel"},te={class:"upload-zone"},ae={class:"selected-files clean-placeholder"},le={key:0,class:"more-line"},ne={key:1},oe={class:"option-group"},ie=["value"],re={class:"template-item-content"},ce={class:"label"},ue={key:0,class:"template-tag"},de={key:1,class:"template-tag muted"},ve={key:2,class:"template-tag custom"},pe={class:"desc"},_e={key:0,class:"empty-option"},fe={class:"option-group"},me={class:"radio-item active"},he={class:"desc"},ye={class:"run-row"},ge=["disabled"],be={class:"loading-msg"},we={class:"right-panel"},ke={class:"task-list-wrap"},Ce={class:"clean-result-summary"},xe={class:"summary-card"},Fe={class:"summary-card"},Pe={class:"summary-card"},Ee={class:"result-list-wrap"},Te={key:0,class:"empty-tasks"},Ie={key:1,class:"task-list clean-result-list"},Be={class:"left"},Ne=["title"],$e={key:0,class:"files"},De={key:1,class:"files"},Re={class:"task-right"},Se=["onClick"],Ue=["onClick"],Ve=A({__name:"BrandConvertTab",setup(He){const v=u([]),g=u(""),f=u([]),m=u(!1),b=u([]),h=u({total:0,successCount:0,failedCount:0,items:[]}),d=u([]),c=u(""),C=T(()=>v.value.slice(0,8)),I=T(()=>d.value.find(a=>a.id===c.value)||null);async function P(a){const e=k();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const l of a){const p=typeof l=="string"?l:l.absolutePath,V=typeof l=="string"?void 0:l.relativePath,y=await e.upload_file_to_java(p,V);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${p}`);t.push(y.data)}return t}async function B(a){const e=await J();d.value=e||[];const t=d.value.find(p=>p.id===c.value);if(t){c.value=t.id;return}const l=d.value.find(p=>p.isDefault);if(l){c.value=l.id;return}c.value=d.value[0]?.id||""}async function N(a,e){v.value=a,g.value="",f.value=await P(a),i.success(e)}async function $(){const a=k();if(!a?.select_brand_xlsx_files){i.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await a.select_brand_xlsx_files();if(!e?.length)return;await N(e,`已选择 ${e.length} 个待转换文件`)}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function D(){const a=k();if(!a?.select_brand_folder){i.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await a.select_brand_folder();if(!e)return;g.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await Y(e);if(t.success&&t.items?.length){v.value=t.items.map(l=>l.relativePath),f.value=await P(t.items),i.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}i.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function R(){if(!f.value.length){i.warning("请先选择待转换 Excel 文件或文件夹");return}if(!c.value){i.warning("请先选择模板");return}try{m.value=!0;const a=await L({files:f.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),templateId:c.value,archiveName:f.value.some(e=>!!e.relativePath)&&g.value?g.value:void 0});h.value=a,b.value=a.items||[],await x(),i.success("格式转换完成")}catch(a){i.error(a instanceof Error?a.message:"格式转换失败")}finally{m.value=!1}}async function x(){try{const a=await O();b.value=a.items||[],h.value={total:a.items?.length||0,successCount:a.items?.filter(e=>e.success).length||0,failedCount:a.items?.filter(e=>!e.success).length||0,items:a.items||[]}}catch{}}async function S(a){try{await G(a),await x(),i.success("已删除")}catch(e){i.error(e instanceof Error?e.message:"删除失败")}}async function U(a){const e=k();if(!a.downloadUrl){i.warning("当前结果没有下载地址");return}const t=a.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.txt`;if(e?.save_file_from_url_new){const l=await e.save_file_from_url_new(a.downloadUrl,t);l.success?i.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&i.error(l.error);return}}return H(()=>{B().catch(()=>{}),x().catch(()=>{})}),(a,e)=>(n(),o("div",Z,[z(K,{active:"convert"}),s("div",ee,[s("aside",se,[e[5]||(e[5]=s("div",{class:"section-title"},"选择文件",-1)),s("div",te,[e[1]||(e[1]=s("div",{class:"hint"},"选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:$},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:D},"选择文件夹")]),s("div",ae,[v.value.length?(n(),o(w,{key:0},[(n(!0),o(w,null,F(C.value,t=>(n(),o("span",{key:t},r(t),1))),128)),v.value.length>C.value.length?(n(),o("span",le," 还有 "+r(v.value.length-C.value.length)+" 个文件未展开显示 ",1)):_("",!0)],64)):(n(),o("span",ne,"暂未选择待转换文件"))])]),e[6]||(e[6]=s("div",{class:"section-title"},"模板选择",-1)),s("div",oe,[(n(!0),o(w,null,F(d.value,t=>(n(),o("label",{key:t.id,class:E(["radio-item",{active:c.value===t.id}])},[M(s("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>c.value=l),type:"radio",value:t.id,name:"convert-template"},null,8,ie),[[j,c.value]]),s("div",re,[s("div",null,[s("span",ce,[q(r(t.templateName)+" ",1),t.isDefault?(n(),o("span",ue,"默认")):t.builtIn?(n(),o("span",de,"内置")):(n(),o("span",ve,"自定义"))]),s("div",pe,"输出文件:"+r(t.outputFilename),1)])])],2))),128)),d.value.length?_("",!0):(n(),o("div",_e,"暂无可用模板"))]),e[7]||(e[7]=s("div",{class:"section-title"},"转换说明",-1)),s("div",fe,[s("label",me,[e[3]||(e[3]=s("input",{type:"checkbox",checked:"",disabled:""},null,-1)),s("div",null,[e[2]||(e[2]=s("span",{class:"label"},"按当前模板输出",-1)),s("div",he,"当前模板:"+r(I.value?.templateName||"未加载模板"),1)])]),e[4]||(e[4]=s("label",{class:"radio-item active"},[s("input",{type:"checkbox",checked:"",disabled:""}),s("div",null,[s("span",{class:"label"},"SKU 使用雪花ID-序号"),s("div",{class:"desc"},"例如 1773816146796-1")])],-1))]),s("div",ye,[s("button",{type:"button",class:"btn-run",disabled:m.value,onClick:R},r(m.value?"转换中...":"开始转换"),9,ge),s("span",be,r(m.value?"正在生成并上传结果,请稍候…":"选择文件后即可执行格式转换,结果会显示在右侧供下载"),1)])]),s("section",we,[e[12]||(e[12]=s("div",{class:"panel-header"},"转换结果",-1)),s("div",ke,[s("div",Ce,[s("div",xe,[e[8]||(e[8]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,r(h.value.total),1)]),s("div",Fe,[e[9]||(e[9]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,r(h.value.successCount),1)]),s("div",Pe,[e[10]||(e[10]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,r(h.value.failedCount),1)])]),s("div",Ee,[e[11]||(e[11]=s("div",{class:"result-list-header"},[s("span",null,"生成的结果压缩包列表")],-1)),b.value.length===0?(n(),o("div",Te," 暂无转换结果,完成格式转换后会在这里展示结果压缩包 ")):(n(),o("ul",Ie,[(n(!0),o(w,null,F(b.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Be,[s("span",{class:"id",title:t.sourceFilename},r(t.sourceFilename||"-"),9,Ne),t.outputFilename?(n(),o("div",$e,"压缩包文件:"+r(t.outputFilename),1)):_("",!0),t.error?(n(),o("div",De,"错误信息:"+r(t.error),1)):_("",!0)]),s("div",Re,[s("span",{class:E(["status",t.success?"success":"failed"])},r(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:l=>U(t)}," 下载压缩包 ",8,Se)):_("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:l=>S(t.resultId)}," 删除 ",8,Ue)):_("",!0)])]))),128))]))])])])])]))}}),Ae=Q(Ve,[["__scopeId","data-v-7c280b44"]]);W(Ae).use(X).mount("#app"); +import{d as A,o as H,a as n,c as o,b as z,B as K,e as s,F as w,r as F,t as r,f as _,n as E,w as M,s as j,u as q,g as u,h as T,x as J,i as k,E as i,y as L,z as O,A as G,_ as Q,p as W,q as X}from"./pywebview-DiP0HdY6.js";import{e as Y}from"./brand-BATjYfEL.js";const Z={class:"page-shell module-page"},ee={class:"main-content"},se={class:"left-panel"},te={class:"upload-zone"},ae={class:"selected-files clean-placeholder"},le={key:0,class:"more-line"},ne={key:1},oe={class:"option-group"},ie=["value"],re={class:"template-item-content"},ce={class:"label"},ue={key:0,class:"template-tag"},de={key:1,class:"template-tag muted"},ve={key:2,class:"template-tag custom"},pe={class:"desc"},_e={key:0,class:"empty-option"},fe={class:"option-group"},me={class:"radio-item active"},he={class:"desc"},ye={class:"run-row"},ge=["disabled"],be={class:"loading-msg"},we={class:"right-panel"},ke={class:"task-list-wrap"},Ce={class:"clean-result-summary"},xe={class:"summary-card"},Fe={class:"summary-card"},Pe={class:"summary-card"},Ee={class:"result-list-wrap"},Te={key:0,class:"empty-tasks"},Ie={key:1,class:"task-list clean-result-list"},Be={class:"left"},Ne=["title"],$e={key:0,class:"files"},De={key:1,class:"files"},Re={class:"task-right"},Se=["onClick"],Ue=["onClick"],Ve=A({__name:"BrandConvertTab",setup(He){const v=u([]),g=u(""),f=u([]),m=u(!1),b=u([]),h=u({total:0,successCount:0,failedCount:0,items:[]}),d=u([]),c=u(""),C=T(()=>v.value.slice(0,8)),I=T(()=>d.value.find(a=>a.id===c.value)||null);async function P(a){const e=k();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const l of a){const p=typeof l=="string"?l:l.absolutePath,V=typeof l=="string"?void 0:l.relativePath,y=await e.upload_file_to_java(p,V);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${p}`);t.push(y.data)}return t}async function B(a){const e=await J();d.value=e||[];const t=d.value.find(p=>p.id===c.value);if(t){c.value=t.id;return}const l=d.value.find(p=>p.isDefault);if(l){c.value=l.id;return}c.value=d.value[0]?.id||""}async function N(a,e){v.value=a,g.value="",f.value=await P(a),i.success(e)}async function $(){const a=k();if(!a?.select_brand_xlsx_files){i.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await a.select_brand_xlsx_files();if(!e?.length)return;await N(e,`已选择 ${e.length} 个待转换文件`)}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function D(){const a=k();if(!a?.select_brand_folder){i.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await a.select_brand_folder();if(!e)return;g.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await Y(e);if(t.success&&t.items?.length){v.value=t.items.map(l=>l.relativePath),f.value=await P(t.items),i.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}i.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){i.error(e instanceof Error?e.message:"选择失败")}}async function R(){if(!f.value.length){i.warning("请先选择待转换 Excel 文件或文件夹");return}if(!c.value){i.warning("请先选择模板");return}try{m.value=!0;const a=await L({files:f.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),templateId:c.value,archiveName:f.value.some(e=>!!e.relativePath)&&g.value?g.value:void 0});h.value=a,b.value=a.items||[],await x(),i.success("格式转换完成")}catch(a){i.error(a instanceof Error?a.message:"格式转换失败")}finally{m.value=!1}}async function x(){try{const a=await O();b.value=a.items||[],h.value={total:a.items?.length||0,successCount:a.items?.filter(e=>e.success).length||0,failedCount:a.items?.filter(e=>!e.success).length||0,items:a.items||[]}}catch{}}async function S(a){try{await G(a),await x(),i.success("已删除")}catch(e){i.error(e instanceof Error?e.message:"删除失败")}}async function U(a){const e=k();if(!a.downloadUrl){i.warning("当前结果没有下载地址");return}const t=a.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.txt`;if(e?.save_file_from_url_new){const l=await e.save_file_from_url_new(a.downloadUrl,t);l.success?i.success(`已保存:${l.path||t}`):l.error&&l.error!=="用户取消"&&i.error(l.error);return}}return H(()=>{B().catch(()=>{}),x().catch(()=>{})}),(a,e)=>(n(),o("div",Z,[z(K,{active:"convert"}),s("div",ee,[s("aside",se,[e[5]||(e[5]=s("div",{class:"section-title"},"选择文件",-1)),s("div",te,[e[1]||(e[1]=s("div",{class:"hint"},"选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:$},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:D},"选择文件夹")]),s("div",ae,[v.value.length?(n(),o(w,{key:0},[(n(!0),o(w,null,F(C.value,t=>(n(),o("span",{key:t},r(t),1))),128)),v.value.length>C.value.length?(n(),o("span",le," 还有 "+r(v.value.length-C.value.length)+" 个文件未展开显示 ",1)):_("",!0)],64)):(n(),o("span",ne,"暂未选择待转换文件"))])]),e[6]||(e[6]=s("div",{class:"section-title"},"模板选择",-1)),s("div",oe,[(n(!0),o(w,null,F(d.value,t=>(n(),o("label",{key:t.id,class:E(["radio-item",{active:c.value===t.id}])},[M(s("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>c.value=l),type:"radio",value:t.id,name:"convert-template"},null,8,ie),[[j,c.value]]),s("div",re,[s("div",null,[s("span",ce,[q(r(t.templateName)+" ",1),t.isDefault?(n(),o("span",ue,"默认")):t.builtIn?(n(),o("span",de,"内置")):(n(),o("span",ve,"自定义"))]),s("div",pe,"输出文件:"+r(t.outputFilename),1)])])],2))),128)),d.value.length?_("",!0):(n(),o("div",_e,"暂无可用模板"))]),e[7]||(e[7]=s("div",{class:"section-title"},"转换说明",-1)),s("div",fe,[s("label",me,[e[3]||(e[3]=s("input",{type:"checkbox",checked:"",disabled:""},null,-1)),s("div",null,[e[2]||(e[2]=s("span",{class:"label"},"按当前模板输出",-1)),s("div",he,"当前模板:"+r(I.value?.templateName||"未加载模板"),1)])]),e[4]||(e[4]=s("label",{class:"radio-item active"},[s("input",{type:"checkbox",checked:"",disabled:""}),s("div",null,[s("span",{class:"label"},"SKU 使用雪花ID-序号"),s("div",{class:"desc"},"例如 1773816146796-1")])],-1))]),s("div",ye,[s("button",{type:"button",class:"btn-run",disabled:m.value,onClick:R},r(m.value?"转换中...":"开始转换"),9,ge),s("span",be,r(m.value?"正在生成并上传结果,请稍候…":"选择文件后即可执行格式转换,结果会显示在右侧供下载"),1)])]),s("section",we,[e[12]||(e[12]=s("div",{class:"panel-header"},"转换结果",-1)),s("div",ke,[s("div",Ce,[s("div",xe,[e[8]||(e[8]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,r(h.value.total),1)]),s("div",Fe,[e[9]||(e[9]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,r(h.value.successCount),1)]),s("div",Pe,[e[10]||(e[10]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,r(h.value.failedCount),1)])]),s("div",Ee,[e[11]||(e[11]=s("div",{class:"result-list-header"},[s("span",null,"生成的结果压缩包列表")],-1)),b.value.length===0?(n(),o("div",Te," 暂无转换结果,完成格式转换后会在这里展示结果压缩包 ")):(n(),o("ul",Ie,[(n(!0),o(w,null,F(b.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Be,[s("span",{class:"id",title:t.sourceFilename},r(t.sourceFilename||"-"),9,Ne),t.outputFilename?(n(),o("div",$e,"压缩包文件:"+r(t.outputFilename),1)):_("",!0),t.error?(n(),o("div",De,"错误信息:"+r(t.error),1)):_("",!0)]),s("div",Re,[s("span",{class:E(["status",t.success?"success":"failed"])},r(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:l=>U(t)}," 下载压缩包 ",8,Se)):_("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:l=>S(t.resultId)}," 删除 ",8,Ue)):_("",!0)])]))),128))]))])])])])]))}}),Ae=Q(Ve,[["__scopeId","data-v-7c280b44"]]);W(Ae).use(X).mount("#app"); diff --git a/app/assets/dedupe.js b/app/assets/dedupe.js index f4c0cff..3574d23 100644 --- a/app/assets/dedupe.js +++ b/app/assets/dedupe.js @@ -1 +1 @@ -import{d as z,o as W,a as n,c as o,b as q,B as J,e as s,F as C,r as F,t as i,f as b,n as I,w as P,v as B,g as u,h as L,i as x,E as r,j as O,k as G,l as Q,m as X,_ as Y,p as Z,q as ee}from"./pywebview-D808cNhy.js";import{e as se}from"./brand-DRn3N4FA.js";const te={class:"page-shell module-page"},le={class:"main-content"},ae={class:"left-panel"},ne={class:"upload-zone"},oe={class:"selected-files clean-placeholder"},re={key:0,class:"more-line"},ie={key:1},ue={class:"option-group column-option-group"},ce={class:"column-toolbar"},de={class:"column-count"},ve={key:0,class:"column-grid"},pe=["value"],fe={key:1,class:"empty-column-state"},_e={class:"option-group"},me={class:"run-row"},he=["disabled"],ge={class:"loading-msg"},ye={class:"right-panel"},be={class:"task-list-wrap"},we={class:"clean-result-summary"},ke={class:"summary-card"},Ce={class:"summary-card"},Ie={class:"summary-card"},xe={class:"result-list-wrap"},Ee={key:0,class:"empty-tasks"},De={key:1,class:"task-list clean-result-list"},Fe={class:"left"},Pe=["title"],Be={key:0,class:"files"},Se={key:1,class:"files"},Ue={class:"task-right"},Ne=["onClick"],$e=["onClick"],Ae=z({__name:"BrandDedupeTab",setup(Ke){const p=u([]),c=u([]),f=u([]),w=u(""),d=u([]),S=u(!1),_=u(!0),m=u(!0),h=u(!1),k=u([]),g=u({total:0,successCount:0,failedCount:0,items:[]}),E=L(()=>f.value.slice(0,8));function $(){c.value=[...p.value]}function A(){c.value=[]}async function U(l){const e=x();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of l){const v=typeof a=="string"?a:a.absolutePath,j=typeof a=="string"?void 0:a.relativePath,y=await e.upload_file_to_java(v,j);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${v}`);t.push(y.data)}return t}async function N(l){const e=await X(l);if(!e.headers?.length){r.error("读取 Excel 表头失败"),p.value=[],c.value=[];return}const t=["id","ASIN","国家","价格","卖家名称"],a=[...t.filter(v=>e.headers?.includes(v)),...(e.headers||[]).filter(v=>!t.includes(v))];p.value=a,c.value=t.filter(v=>a.includes(v))}async function H(l,e){f.value=l,w.value="",d.value=await U(l),d.value.length>0&&await N(d.value[0].fileKey),r.success(e)}async function K(){const l=x();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await l.select_brand_xlsx_files();if(!e?.length)return;await H(e,`已选择 ${e.length} 个待清洗文件`)}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function R(){const l=x();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await l.select_brand_folder();if(!e)return;w.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await se(e);if(t.success&&t.items?.length){f.value=t.items.map(a=>a.relativePath),d.value=await U(t.items),d.value.length>0&&await N(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function V(){if(!d.value.length){r.warning("请先选择待清洗 Excel 文件或文件夹");return}if(!c.value.length){r.warning("请至少选择一列保留列");return}if(!S.value&&!_.value&&!m.value){r.warning("请至少选择一种 ID 保留规则");return}try{h.value=!0;const l=await O({files:d.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),selectedColumns:c.value,keepIntegerIds:S.value,keepUnderscoreIds:_.value,keepIntegerMainIdsWhenNoSubIds:m.value,archiveName:d.value.some(e=>!!e.relativePath)&&w.value?w.value:void 0});g.value=l,k.value=l.items||[],await D(),r.success("数据去重完成")}catch(l){r.error(l instanceof Error?l.message:"去重失败")}finally{h.value=!1}}async function D(){try{const l=await G();k.value=l.items||[],g.value={total:l.items?.length||0,successCount:l.items?.filter(e=>e.success).length||0,failedCount:l.items?.filter(e=>!e.success).length||0,items:l.items||[]}}catch{}}async function M(l){try{await Q(l),await D(),r.success("已删除")}catch(e){r.error(e instanceof Error?e.message:"删除失败")}}async function T(l){const e=x();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}_cleaned.xlsx`;if(e?.save_file_from_url_new){const a=await e.save_file_from_url_new(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}}return W(()=>{D().catch(()=>{})}),(l,e)=>(n(),o("div",te,[q(J,{active:"dedupe"}),s("div",le,[s("aside",ae,[e[7]||(e[7]=s("div",{class:"section-title"},"选择文件",-1)),s("div",ne,[e[3]||(e[3]=s("div",{class:"hint"},"选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:K},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:R},"选择文件夹")]),s("div",oe,[f.value.length?(n(),o(C,{key:0},[(n(!0),o(C,null,F(E.value,t=>(n(),o("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(n(),o("span",re," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):b("",!0)],64)):(n(),o("span",ie,"暂未选择待清洗文件"))])]),e[8]||(e[8]=s("div",{class:"section-title"},"保留列设置",-1)),s("div",ue,[s("div",ce,[s("span",de,"已选择 "+i(c.value.length)+" / "+i(p.value.length)+" 列",1),s("div",{class:"column-actions"},[s("button",{type:"button",class:"opt-btn small",onClick:$},"全选"),s("button",{type:"button",class:"opt-btn small",onClick:A},"清空")])]),p.value.length?(n(),o("div",ve,[(n(!0),o(C,null,F(p.value,t=>(n(),o("label",{key:t,class:I(["column-item",{active:c.value.includes(t)}])},[P(s("input",{"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),type:"checkbox",value:t},null,8,pe),[[B,c.value]]),s("span",null,i(t),1)],2))),128))])):(n(),o("div",fe,"请选择 Excel 文件后读取表头并填充可保留列")),e[4]||(e[4]=s("div",{class:"desc"},"读取首个 Excel 文件的第一行作为表头,用于动态选择需要保留的列。",-1))]),e[9]||(e[9]=s("div",{class:"section-title"},"ID 保留规则",-1)),s("div",_e,[s("label",{class:I(["radio-item",{active:_.value}])},[P(s("input",{"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),type:"checkbox"},null,512),[[B,_.value]]),e[5]||(e[5]=s("div",null,[s("span",{class:"label"},"保留子链接"),s("div",{class:"desc"},"例如 1_1、2_3 这种带下划线的子项 ID")],-1))],2),s("label",{class:I(["radio-item",{active:m.value}])},[P(s("input",{"onUpdate:modelValue":e[2]||(e[2]=t=>m.value=t),type:"checkbox"},null,512),[[B,m.value]]),e[6]||(e[6]=s("div",null,[s("span",{class:"label"},"仅剩主链接无子链接"),s("div",{class:"desc"},"当某个主链接只有 13 这类主 ID、没有 13_1 这类对应子 ID 时,自动保留该主 ID")],-1))],2)]),s("div",me,[s("button",{type:"button",class:"btn-run",disabled:h.value,onClick:V},i(h.value?"清洗中...":"开始清洗"),9,he),s("span",ge,i(h.value?"正在处理文件并上传结果,请稍候…":"选择文件、列和 ID 规则后即可执行清洗,结果会显示在右侧供下载"),1)])]),s("section",ye,[e[14]||(e[14]=s("div",{class:"panel-header"},"去重结果",-1)),s("div",be,[s("div",we,[s("div",ke,[e[10]||(e[10]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,i(g.value.total),1)]),s("div",Ce,[e[11]||(e[11]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,i(g.value.successCount),1)]),s("div",Ie,[e[12]||(e[12]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,i(g.value.failedCount),1)])]),s("div",xe,[e[13]||(e[13]=s("div",{class:"result-list-header"},[s("span",null,"处理后的 Excel 列表")],-1)),k.value.length===0?(n(),o("div",Ee," 暂无去重结果,完成数据去重后会在这里展示输出文件 ")):(n(),o("ul",De,[(n(!0),o(C,null,F(k.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Fe,[s("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Pe),t.outputFilename?(n(),o("div",Be,"输出文件:"+i(t.outputFilename),1)):b("",!0),t.error?(n(),o("div",Se,"错误信息:"+i(t.error),1)):b("",!0)]),s("div",Ue,[s("span",{class:I(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:a=>T(t)}," 下载文件 ",8,Ne)):b("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:a=>M(t.resultId)}," 删除 ",8,$e)):b("",!0)])]))),128))]))])])])])]))}}),He=Y(Ae,[["__scopeId","data-v-bdaefe1c"]]);Z(He).use(ee).mount("#app"); +import{d as z,o as W,a as n,c as o,b as q,B as J,e as s,F as C,r as F,t as i,f as b,n as I,w as P,v as B,g as u,h as L,i as x,E as r,j as O,k as G,l as Q,m as X,_ as Y,p as Z,q as ee}from"./pywebview-DiP0HdY6.js";import{e as se}from"./brand-BATjYfEL.js";const te={class:"page-shell module-page"},le={class:"main-content"},ae={class:"left-panel"},ne={class:"upload-zone"},oe={class:"selected-files clean-placeholder"},re={key:0,class:"more-line"},ie={key:1},ue={class:"option-group column-option-group"},ce={class:"column-toolbar"},de={class:"column-count"},ve={key:0,class:"column-grid"},pe=["value"],fe={key:1,class:"empty-column-state"},_e={class:"option-group"},me={class:"run-row"},he=["disabled"],ge={class:"loading-msg"},ye={class:"right-panel"},be={class:"task-list-wrap"},we={class:"clean-result-summary"},ke={class:"summary-card"},Ce={class:"summary-card"},Ie={class:"summary-card"},xe={class:"result-list-wrap"},Ee={key:0,class:"empty-tasks"},De={key:1,class:"task-list clean-result-list"},Fe={class:"left"},Pe=["title"],Be={key:0,class:"files"},Se={key:1,class:"files"},Ue={class:"task-right"},Ne=["onClick"],$e=["onClick"],Ae=z({__name:"BrandDedupeTab",setup(Ke){const p=u([]),c=u([]),f=u([]),w=u(""),d=u([]),S=u(!1),_=u(!0),m=u(!0),h=u(!1),k=u([]),g=u({total:0,successCount:0,failedCount:0,items:[]}),E=L(()=>f.value.slice(0,8));function $(){c.value=[...p.value]}function A(){c.value=[]}async function U(l){const e=x();if(!e?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const a of l){const v=typeof a=="string"?a:a.absolutePath,j=typeof a=="string"?void 0:a.relativePath,y=await e.upload_file_to_java(v,j);if(!y?.success||!y.data)throw new Error(y?.error||y?.message||`上传失败:${v}`);t.push(y.data)}return t}async function N(l){const e=await X(l);if(!e.headers?.length){r.error("读取 Excel 表头失败"),p.value=[],c.value=[];return}const t=["id","ASIN","国家","价格","卖家名称"],a=[...t.filter(v=>e.headers?.includes(v)),...(e.headers||[]).filter(v=>!t.includes(v))];p.value=a,c.value=t.filter(v=>a.includes(v))}async function H(l,e){f.value=l,w.value="",d.value=await U(l),d.value.length>0&&await N(d.value[0].fileKey),r.success(e)}async function K(){const l=x();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const e=await l.select_brand_xlsx_files();if(!e?.length)return;await H(e,`已选择 ${e.length} 个待清洗文件`)}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function R(){const l=x();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const e=await l.select_brand_folder();if(!e)return;w.value=e.split(/[/\\]/).filter(Boolean).pop()||"";const t=await se(e);if(t.success&&t.items?.length){f.value=t.items.map(a=>a.relativePath),d.value=await U(t.items),d.value.length>0&&await N(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(e){r.error(e instanceof Error?e.message:"选择失败")}}async function V(){if(!d.value.length){r.warning("请先选择待清洗 Excel 文件或文件夹");return}if(!c.value.length){r.warning("请至少选择一列保留列");return}if(!S.value&&!_.value&&!m.value){r.warning("请至少选择一种 ID 保留规则");return}try{h.value=!0;const l=await O({files:d.value.map(e=>({fileKey:e.fileKey,originalFilename:e.originalFilename,relativePath:e.relativePath})),selectedColumns:c.value,keepIntegerIds:S.value,keepUnderscoreIds:_.value,keepIntegerMainIdsWhenNoSubIds:m.value,archiveName:d.value.some(e=>!!e.relativePath)&&w.value?w.value:void 0});g.value=l,k.value=l.items||[],await D(),r.success("数据去重完成")}catch(l){r.error(l instanceof Error?l.message:"去重失败")}finally{h.value=!1}}async function D(){try{const l=await G();k.value=l.items||[],g.value={total:l.items?.length||0,successCount:l.items?.filter(e=>e.success).length||0,failedCount:l.items?.filter(e=>!e.success).length||0,items:l.items||[]}}catch{}}async function M(l){try{await Q(l),await D(),r.success("已删除")}catch(e){r.error(e instanceof Error?e.message:"删除失败")}}async function T(l){const e=x();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}_cleaned.xlsx`;if(e?.save_file_from_url_new){const a=await e.save_file_from_url_new(l.downloadUrl,t);a.success?r.success(`已保存:${a.path||t}`):a.error&&a.error!=="用户取消"&&r.error(a.error);return}}return W(()=>{D().catch(()=>{})}),(l,e)=>(n(),o("div",te,[q(J,{active:"dedupe"}),s("div",le,[s("aside",ae,[e[7]||(e[7]=s("div",{class:"section-title"},"选择文件",-1)),s("div",ne,[e[3]||(e[3]=s("div",{class:"hint"},"选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。",-1)),s("div",{class:"btns"},[s("button",{type:"button",class:"opt-btn",onClick:K},"选择 Excel 文件"),s("button",{type:"button",class:"opt-btn",onClick:R},"选择文件夹")]),s("div",oe,[f.value.length?(n(),o(C,{key:0},[(n(!0),o(C,null,F(E.value,t=>(n(),o("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(n(),o("span",re," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):b("",!0)],64)):(n(),o("span",ie,"暂未选择待清洗文件"))])]),e[8]||(e[8]=s("div",{class:"section-title"},"保留列设置",-1)),s("div",ue,[s("div",ce,[s("span",de,"已选择 "+i(c.value.length)+" / "+i(p.value.length)+" 列",1),s("div",{class:"column-actions"},[s("button",{type:"button",class:"opt-btn small",onClick:$},"全选"),s("button",{type:"button",class:"opt-btn small",onClick:A},"清空")])]),p.value.length?(n(),o("div",ve,[(n(!0),o(C,null,F(p.value,t=>(n(),o("label",{key:t,class:I(["column-item",{active:c.value.includes(t)}])},[P(s("input",{"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),type:"checkbox",value:t},null,8,pe),[[B,c.value]]),s("span",null,i(t),1)],2))),128))])):(n(),o("div",fe,"请选择 Excel 文件后读取表头并填充可保留列")),e[4]||(e[4]=s("div",{class:"desc"},"读取首个 Excel 文件的第一行作为表头,用于动态选择需要保留的列。",-1))]),e[9]||(e[9]=s("div",{class:"section-title"},"ID 保留规则",-1)),s("div",_e,[s("label",{class:I(["radio-item",{active:_.value}])},[P(s("input",{"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),type:"checkbox"},null,512),[[B,_.value]]),e[5]||(e[5]=s("div",null,[s("span",{class:"label"},"保留子链接"),s("div",{class:"desc"},"例如 1_1、2_3 这种带下划线的子项 ID")],-1))],2),s("label",{class:I(["radio-item",{active:m.value}])},[P(s("input",{"onUpdate:modelValue":e[2]||(e[2]=t=>m.value=t),type:"checkbox"},null,512),[[B,m.value]]),e[6]||(e[6]=s("div",null,[s("span",{class:"label"},"仅剩主链接无子链接"),s("div",{class:"desc"},"当某个主链接只有 13 这类主 ID、没有 13_1 这类对应子 ID 时,自动保留该主 ID")],-1))],2)]),s("div",me,[s("button",{type:"button",class:"btn-run",disabled:h.value,onClick:V},i(h.value?"清洗中...":"开始清洗"),9,he),s("span",ge,i(h.value?"正在处理文件并上传结果,请稍候…":"选择文件、列和 ID 规则后即可执行清洗,结果会显示在右侧供下载"),1)])]),s("section",ye,[e[14]||(e[14]=s("div",{class:"panel-header"},"去重结果",-1)),s("div",be,[s("div",we,[s("div",ke,[e[10]||(e[10]=s("span",{class:"summary-label"},"已处理文件",-1)),s("strong",null,i(g.value.total),1)]),s("div",Ce,[e[11]||(e[11]=s("span",{class:"summary-label"},"成功结果",-1)),s("strong",null,i(g.value.successCount),1)]),s("div",Ie,[e[12]||(e[12]=s("span",{class:"summary-label"},"失败文件",-1)),s("strong",null,i(g.value.failedCount),1)])]),s("div",xe,[e[13]||(e[13]=s("div",{class:"result-list-header"},[s("span",null,"处理后的 Excel 列表")],-1)),k.value.length===0?(n(),o("div",Ee," 暂无去重结果,完成数据去重后会在这里展示输出文件 ")):(n(),o("ul",De,[(n(!0),o(C,null,F(k.value,t=>(n(),o("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}`,class:"task-item"},[s("div",Fe,[s("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Pe),t.outputFilename?(n(),o("div",Be,"输出文件:"+i(t.outputFilename),1)):b("",!0),t.error?(n(),o("div",Se,"错误信息:"+i(t.error),1)):b("",!0)]),s("div",Ue,[s("span",{class:I(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(n(),o("button",{key:0,type:"button",class:"download",onClick:a=>T(t)}," 下载文件 ",8,Ne)):b("",!0),t.resultId?(n(),o("button",{key:1,type:"button",class:"btn-delete",onClick:a=>M(t.resultId)}," 删除 ",8,$e)):b("",!0)])]))),128))]))])])])])]))}}),He=Y(Ae,[["__scopeId","data-v-bdaefe1c"]]);Z(He).use(ee).mount("#app"); diff --git a/app/assets/delete-brand.js b/app/assets/delete-brand.js index 84bdd87..cebfc65 100644 --- a/app/assets/delete-brand.js +++ b/app/assets/delete-brand.js @@ -1 +1 @@ -import{d as We,o as Ye,I as Ze,a as d,c as f,b as es,B as ss,e as l,F as H,r as de,t as v,f as h,J as ts,K as Ae,n as De,g as y,h as J,L as ns,i as G,E as p,M as as,N as ls,O as rs,P as os,_ as us,p as is,q as cs}from"./pywebview-D808cNhy.js";import{e as ds}from"./brand-DRn3N4FA.js";const fs={class:"page-shell module-page"},vs={class:"main-content"},hs={class:"left-panel"},ps={class:"upload-zone"},_s={class:"selected-files clean-placeholder split-selected-files"},ys={key:0,class:"more-line"},gs={key:1},ms={class:"run-row"},ks=["disabled"],ws=["disabled"],Is={class:"loading-msg"},bs={key:0,class:"queue-debug-card"},Ss={key:0,class:"queue-debug-line"},Ts={key:1,class:"queue-debug-payload"},Cs={class:"right-panel"},Fs={class:"task-list-wrap"},Es={class:"clean-result-summary"},Ps={class:"summary-card"},Rs={class:"summary-card"},xs={class:"summary-card"},Ns={class:"result-list-wrap"},$s={key:0,class:"empty-tasks"},As={key:0,class:"result-subsection"},Ds={class:"task-list clean-result-list"},Ms={class:"left split-result-main"},Bs=["title"],qs={class:"files"},Us={class:"files"},Ls={key:0,class:"files"},Os={key:1,class:"files"},Ks={key:2,class:"files"},Hs={key:3,class:"time"},Js={key:4,class:"delete-brand-progress-block"},Gs={class:"delete-brand-progress-header"},js={class:"delete-brand-progress-bar"},zs={class:"files delete-brand-progress"},Vs={key:5,class:"files split-entry-list delete-brand-preview"},Qs={key:6,class:"files"},Xs={class:"task-right split-result-actions"},Ws=["onClick"],Ys=["onClick"],Zs={key:1,class:"result-subsection"},et={class:"task-list clean-result-list"},st={class:"left split-result-main"},tt=["title"],nt={class:"files"},at={class:"files"},lt={key:0,class:"files"},rt={key:1,class:"files"},ot={key:2,class:"time"},ut={key:3,class:"delete-brand-progress-block"},it={class:"delete-brand-progress-header"},ct={class:"delete-brand-progress-bar"},dt={class:"files delete-brand-progress"},ft={key:4,class:"files split-entry-list delete-brand-preview"},vt={key:5,class:"files"},ht={class:"task-right split-result-actions"},pt=["onClick"],_t=["onClick"],yt=We({__name:"BrandDeleteBrandTab",setup(mt){function N(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const $=y([]),j=y([]),B=y(!1),fe=y([]),i=y([]),q=y([]),z=y({total:0,successCount:0,failedCount:0,items:[]}),b=y(""),S=y(""),g=y({}),T=y(null),ee=y(!1),V=y(!1),A=y(!1),D=y(""),Q=y(!1),U=y(null),se=J(()=>$.value.slice(0,10)),F=J(()=>{const e=[];return i.value.forEach(s=>{e.push(...s.items)}),e});function Me(){try{const e=typeof window<"u"?window.localStorage.getItem(N()):null;if(e){if(i.value=JSON.parse(e),i.value.length>0){const s=i.value[i.value.length-1];b.value=s.queuePushResult||"",S.value=s.queuePayloadText||""}}else i.value=[]}catch{i.value=[]}}function te(e,s,t,n){if(!s?.length)return;const a=i.value.findIndex(c=>c.taskId===e),o=a>=0?i.value[a]:null,r=s.map(c=>{const _=o?.items.find(Xe=>M(Xe,c)),k=Array.isArray(c.countries)?c.countries:void 0,m=Array.isArray(_?.countries)?_?.countries:void 0,w=k&&k.length>0?k:m&&m.length>0?m:k??m,I=Array.isArray(c.previewRows)?c.previewRows:void 0,C=Array.isArray(_?.previewRows)?_?.previewRows:void 0,ce=I&&I.length>0?I:C&&C.length>0?C:I??C;return{...c,countries:w,previewRows:ce,_pushed:_?._pushed??c._pushed??!1,_completed:_?._completed??c._completed??!1}}),u={taskId:e,items:r,createdAt:o?.createdAt||Date.now(),queuePushResult:t??o?.queuePushResult,queuePayloadText:n??o?.queuePayloadText};a>=0?i.value[a]=u:i.value.push(u),typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function ve(e){const s=i.value.length;i.value=i.value.filter(t=>t.taskId!==e),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function he(e){return e==="SUCCESS"||e==="FAILED"||e==="COMPLETED"}function Be(e){if(!e?.length)return!1;const s=new Set;if(e.forEach(n=>{n.taskId&&he(n.taskStatus)&&s.add(n.taskId)}),!s.size)return!1;const t=i.value.length;return i.value=i.value.filter(n=>!s.has(n.taskId)),i.value.length!==t?(ne(),!0):!1}const X=J(()=>q.value.filter(e=>!F.value.some(s=>M(s,e)))),qe=J(()=>F.value.length>0||X.value.length>0),Ue=J(()=>F.value.filter(e=>Re(e)&&E(e)==="未入队"));function ne(){typeof window<"u"&&(i.value.length===0?window.localStorage.removeItem(N()):window.localStorage.setItem(N(),JSON.stringify(i.value)))}function P(e){return e?(i.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function ae(e){return e&&i.value.find(s=>s.taskId===e)||null}function M(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 R(e,s){const t=ae(e);return t&&t.items.find(n=>M(n,s))||null}function pe(e){if(!e)return!1;const s=ae(e);if(!s)return!1;let t=!1;const n=g.value[e]?.line_progress?.info,a=P(e);if(n?.file_name&&n.current_line!=null&&n.total_lines!=null&&n.total_lines>0&&n.current_line>=n.total_lines){const o=s.items.find(r=>r.sourceFilename===n.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!a){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const r=s.items[0];r&&!r._completed&&(r._completed=!0,t=!0)}}return t&&ne(),t}function _e(e){return e&&g.value[e]?.task?.status||""}function W(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&g.value[s]?.task?.errorMessage||""}function ye(e){const s=e.taskId;if(!s)return!1;const t=g.value[s]?.line_progress,n=_e(s),a=P(s),o=E(e);if(a){const r=R(s,e),u=K(e)===D.value,c=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return u||c||r?._pushed||(n==="RUNNING"||n==="PENDING"||!n)&&r?._completed?!0:{success:!1,retryable:!0}}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function ge(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 me(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 Le(){fe.value=[...F.value,...X.value]}function x(){Le(),Oe(fe.value)}function Oe(e){z.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function le(e){const s=e.taskId;return s&&(g.value[s]?.fileProgress||[]).find(a=>a.fileKey&&e.fileKey?a.fileKey===e.fileKey:a.sourceFilename&&e.sourceFilename?a.sourceFilename===e.sourceFilename:!1)||null}function ke(e){const s=e.taskId;if(!s)return"";const t=g.value[s],n=t?.line_progress?.info,a=le(e);if(P(s)){const u=R(s,e),c=t?.task?.status,_=!!(n?.file_name&&n.file_name===e.sourceFilename);let k=u?._completed?"COMPLETED":(u?._pushed,"PENDING"),m=0,w=Math.max(0,e.totalRows??a?.totalRows??0);c==="SUCCESS"||c==="FAILED"&&u?._completed?(k="COMPLETED",m=w):_?(k="RUNNING",m=Math.max(0,Math.min(w||Number.MAX_SAFE_INTEGER,n?.current_line??0)),!w&&n?.total_lines&&n.total_lines>0&&(w=n.total_lines)):u?._completed?(k="COMPLETED",m=w):u?._pushed&&(k="PENDING",m=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${m}/${w}`),n?.finished_files!=null){const C=n.file_total&&n.file_total>0?`/${n.file_total}`:"";I.push(`已完成文件:${n.finished_files}${C}`)}return n?.phase&&I.push(`阶段:${n.phase}`),I.join("|")}if(a){const u=[],c=a.processedRows??0,_=a.totalRows??0;if(a.status&&u.push(`文件状态:${a.status}`),u.push(`文件进度:${c}/${_}`),n?.finished_files!=null){const k=n.file_total&&n.file_total>0?`/${n.file_total}`:"";u.push(`已完成文件:${n.finished_files}${k}`)}return n?.phase&&u.push(`阶段:${n.phase}`),u.join("|")}if(!t?.line_progress?.has_progress||!n){const u=t?.task?.status;return u?`任务状态:${u}`:""}const r=[];if(n.phase&&r.push(`阶段:${n.phase}`),n.file_index&&n.file_total&&r.push(`文件:${n.file_index}/${n.file_total}`),n.file_name&&r.push(`当前文件:${n.file_name}`),n.current_line!=null&&n.total_lines!=null&&r.push(`${P(s)?"当前文件进度":"进度"}:${n.current_line}/${n.total_lines}`),n.current_country&&r.push(`国家:${n.current_country}`),n.current_asin&&r.push(`ASIN:${n.current_asin}`),n.finished_files!=null){const u=n.file_total&&n.file_total>0?`/${n.file_total}`:"";r.push(`已完成文件:${n.finished_files}${u}`)}return r.join("|")}function Y(e){const s=e.taskId;if(!s)return 0;const t=g.value[s]?.line_progress?.info;if(P(s)){const r=R(s,e);if(g.value[s]?.task?.status==="SUCCESS"||r?._completed)return 100;const c=Math.max(0,e.totalRows??le(e)?.totalRows??0);if(!!(t?.file_name&&t.file_name===e.sourceFilename)){if(t?.current_line!=null&&t?.total_lines&&t.total_lines>0)return Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100)));if(t?.current_line!=null&&c>0)return Math.max(0,Math.min(100,Math.round(t.current_line/c*100)))}return 0}const a=le(e);return a?Math.max(0,Math.min(100,a.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function we(e){const s=g.value[e]?.task?.status;return he(s)}function L(){const e=new Set;return i.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function E(e){const s=e.taskId;if(!s||!ae(s))return"";const n=R(s,e),a=_e(s),o=g.value[s]?.line_progress,r=P(s);if(!r&&(a==="SUCCESS"||a==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(n?._completed)return"本文件解析完毕";if(a==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(r&&!n?._pushed&&!n?._completed)return"未入队";if(r&&a==="SUCCESS")return"本文件解析完毕";if(!r){const u=g.value[s];if(u?.items&&u.items.find(_=>M(_,e))&&a==="SUCCESS")return"本文件解析完毕"}return n?._pushed?"已入队":"未入队"}function Ie(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?g.value[s]?.task?.status==="SUCCESS":{success:!1,retryable:!1}}function Ke(e){const s=e?.task?.id;if(!s)return!1;const t=i.value.find(r=>r.taskId===s);if(!t)return{success:!1,retryable:!1};const n=e?.items||[];let a=!1;const o=t.items.map(r=>{const u=n.find(ce=>M(ce,r));if(!u)return r;const c=Array.isArray(u.countries)?u.countries:void 0,_=Array.isArray(r.countries)?r.countries:void 0,k=c&&c.length>0?c:_&&_.length>0?_:c??_,m=Array.isArray(u.previewRows)?u.previewRows:void 0,w=Array.isArray(r.previewRows)?r.previewRows:void 0,I=m&&m.length>0?m:w&&w.length>0?w:m??w,C={...r,...u,countries:k,previewRows:I,_pushed:r._pushed,_completed:r._completed};return JSON.stringify(C)!==JSON.stringify(r)&&(a=!0),C});for(const r of n)o.some(u=>M(u,r))||(o.push({...r,_pushed:!1,_completed:!1}),a=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,a=!0),a&&ne(),a}async function re(e){const s=e||L();if(s.length)try{const t=await ns(s);let n=!1;for(const a of t.items||[]){const o=a?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=a,Ke(a)&&(n=!0),pe(o)&&(n=!0))}n&&x()}catch{}}function He(){return document.visibilityState==="visible"?4500:1e4}function oe(e=!1){if(T.value){if(!e)return;clearTimeout(T.value),T.value=null}const s=async()=>{if(T.value=null,ee.value){oe();return}const t=L();if(!t.length)return;ee.value=!0;let n=!1,a=!1;try{await re(t),await $e();for(const o of t)we(o)&&(ve(o),n=!0,a=!0)}finally{ee.value=!1}a?await O():n&&x(),L().length>0&&oe()};e?s():T.value=window.setTimeout(s,He())}function ue(e=!1){T.value&&!e||oe(e)}function Z(e){const s=e.taskId?g.value[e.taskId]?.task?.status:null;return s==="SUCCESS"?{className:"success",text:"已完成"}:s==="FAILED"?{className:"failed",text:"失败"}:s==="RUNNING"?{className:"running",text:"执行中"}:e.taskStatus==="SUCCESS"?{className:"success",text:"已完成"}:e.taskStatus==="FAILED"?{className:"failed",text:"失败"}:e.taskStatus==="RUNNING"?{className:"running",text:"执行中"}:e.success?{className:"success",text:"已完成"}:{className:"failed",text:"失败"}}function be(){T.value&&(window.clearTimeout(T.value),T.value=null),ie()}async function Se(e){const s=G();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const n of e){const a=typeof n=="string"?n:n.absolutePath,o=typeof n=="string"?void 0:n.relativePath,r=await s.upload_file_to_java(a,o);if(!r?.success||!r.data)throw new Error(r?.error||r?.message||`上传失败:${a}`);t.push(r.data)}return t}async function Je(){const e=G();if(!e?.select_brand_xlsx_files){p.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;$.value=s,j.value=await Se(s),p.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function Ge(){const e=G();if(!e?.select_brand_folder){p.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await ds(s);if(!t.success||!t.items?.length){p.warning(t.error||"该文件夹下没有 xlsx 文件");return}$.value=t.items.map(n=>n.relativePath||n.absolutePath),j.value=await Se(t.items),p.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function je(){if(!j.value.length){p.warning("请先选择待处理文件");return}try{B.value=!0;const e=await as({files:j.value.map(a=>({fileKey:a.fileKey,originalFilename:a.originalFilename,relativePath:a.relativePath}))}),s=ge(e.items||[]),t=s.some(a=>a.matchStatus==="MATCHED"),n=s.some(a=>a.matchStatus&&a.matchStatus!=="MATCHED");b.value=t?"解析完成,可在左侧点击“推送到 Python 队列”开始串行处理":"解析完成,当前没有可推送的已匹配文件",S.value="",s.length&&s[0].taskId&&te(s[0].taskId,s,b.value,S.value),x(),n?p.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?p.success("删除品牌解析完成,请在左侧推送到 Python 队列"):p.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await O()}catch(e){p.error(e instanceof Error?e.message:"执行失败")}finally{B.value=!1}}async function Te(e){const s=e.taskId;if(!s){p.warning("未找到任务ID");return}const t=G(),n=ls(s),a=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(n,a);o.success?p.success(`已保存:${o.path||a}`):o.error&&o.error!=="用户取消"&&p.error(o.error);return}}async function O(){try{const e=await rs();q.value=ge(e.items||[]),Be(q.value),x(),await re(),ue(!0)}catch(e){console.error("loadHistory error:",e)}}function Ce(e){i.value.forEach(t=>{t.items=t.items.filter(n=>n.resultId!==e)});const s=i.value.length;i.value=i.value.filter(t=>t.items.length>0),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value)),q.value=q.value.filter(t=>t.resultId!==e),x(),L().length===0&&be()}async function Fe(e){try{await os(e),Ce(e),await O(),p.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){Ce(e),p.success("已删除");return}p.error(t)}}function Ee(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 kt(e,s){}function ie(){U.value&&(window.clearTimeout(U.value),U.value=null)}function ze(e=3e3){ie(),U.value=window.setTimeout(()=>{U.value=null,$e().catch(()=>{})},e)}function Ve(e){return e.includes("当前店铺正在执行中")}function Pe(){for(const e of i.value)for(const s of e.items){const t=E(s);if(t==="已入队"||t==="处理中")return!0}return!1}function K(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Re(e){return!!(e.taskId&&(e.matchStatus==="MATCHED"||e.matched))}function xe(){return F.value.find(e=>!Re(e)||K(e)===D.value||R(e.taskId,e)?._completed?!1:E(e)==="未入队")}async function Ne(e,s){if(s?.auto&&Pe())return e.taskId,e.sourceFilename,{success:!1,retryable:!0};const t=G(),n=e.taskId;if(!n)return{success:!1,retryable:!1};const a=i.value.find(c=>c.taskId===n);if(!a)return{success:!1,retryable:!1};if(!t?.enqueue_json)return p.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),{success:!1,retryable:!1};const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:n,items:[e]}};S.value=JSON.stringify(o,null,2);const r=await t.enqueue_json(o);let u="";if(r?.success){u=`已推送文件 ${e.sourceFilename},当前队列长度:${r.queue_size??"-"}`;const c=R(n,e);return c&&(c._pushed=!0,c._completed=!1),D.value=K(e),te(n,a.items,u,S.value),ue(!0),b.value=u,{success:!0,retryable:!1}}else{const c=r?.error||"未知错误";if(u=`推送到 Python 队列失败:${c}`,b.value=u,te(n,a.items,u,S.value),s?.auto&&Ve(c))return{success:!1,retryable:!0}}return b.value=u,{success:!1,retryable:!1}}async function Qe(){const e=xe();if(!e){p.warning("当前没有可推送的已匹配文件");return}V.value=!0,A.value=!0,ie();const s=await Ne(e);if(V.value=!1,!s.success){A.value=!1,D.value="";return}p.success("已开始按顺序推送到 Python 队列")}async function $e(){if(!A.value||Q.value){A.value,Q.value;return}if(Pe())return;const e=D.value;if(e){const t=F.value.find(n=>K(n)===e);if(t){const n=t.taskId,a=P(n);a&&(pe(n),E(t),void 0);const o=E(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(a){const r=R(n,t);if(r&&!r._completed){t.sourceFilename,r._pushed,r._completed;return}}}}const s=xe();if(!s){D.value="",A.value=!1;return}Q.value=!0;try{s.taskId,s.sourceFilename,K(s);const t=await Ne(s,{auto:!0});if(!t.success){if(t.retryable){s.taskId,s.sourceFilename,ze();return}s.taskId,s.sourceFilename,A.value=!1}}finally{Q.value=!1}}return Ye(()=>{Me();const e=L();e.length>0?re(e).then(async()=>{let s=!1,t=!1;for(const n of e)we(n)&&(ve(n),s=!0,t=!0);t?await O():s&&x(),ue(!0)}):x(),O().catch(()=>{})}),Ze(()=>{be()}),(e,s)=>(d(),f("div",fs,[es(ss,{active:"delete-brand"}),l("div",vs,[l("aside",hs,[s[2]||(s[2]=l("div",{class:"section-title"},"选择文件",-1)),l("div",ps,[s[0]||(s[0]=l("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),l("div",{class:"btns"},[l("button",{type:"button",class:"opt-btn",onClick:Je},"选择 Excel 文件"),l("button",{type:"button",class:"opt-btn",onClick:Ge},"选择文件夹")]),l("div",_s,[$.value.length?(d(),f(H,{key:0},[(d(!0),f(H,null,de(se.value,t=>(d(),f("span",{key:t},v(t),1))),128)),$.value.length>se.value.length?(d(),f("span",ys," 还有 "+v($.value.length-se.value.length)+" 个文件未展开显示 ",1)):h("",!0)],64)):(d(),f("span",gs,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=ts('
执行说明
',2)),l("div",ms,[l("button",{type:"button",class:"btn-run",disabled:B.value,onClick:je},v(B.value?"解析中...":"开始解析"),9,ks),l("button",{type:"button",class:"btn-run btn-queue",disabled:V.value||!Ue.value.length,onClick:Qe},v(V.value?"推送中...":"推送到 Python 队列"),9,ws),l("span",Is,v(B.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),b.value||S.value?(d(),f("div",bs,[s[1]||(s[1]=l("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),b.value?(d(),f("div",Ss,v(b.value),1)):h("",!0),S.value?(d(),f("pre",Ts,v(S.value),1)):h("",!0)])):h("",!0)]),l("section",Cs,[s[12]||(s[12]=l("div",{class:"panel-header"},"删除品牌结果",-1)),l("div",Fs,[l("div",Es,[l("div",Ps,[s[4]||(s[4]=l("span",{class:"summary-label"},"已处理文件",-1)),l("strong",null,v(z.value.total),1)]),l("div",Rs,[s[5]||(s[5]=l("span",{class:"summary-label"},"成功结果",-1)),l("strong",null,v(z.value.successCount),1)]),l("div",xs,[s[6]||(s[6]=l("span",{class:"summary-label"},"失败文件",-1)),l("strong",null,v(z.value.failedCount),1)])]),l("div",Ns,[s[11]||(s[11]=l("div",{class:"result-list-header"},[l("span",null,"删除品牌结果列表")],-1)),qe.value?(d(),f(H,{key:1},[F.value.length?(d(),f("div",As,[s[8]||(s[8]=l("div",{class:"result-subsection-title"},"当前任务",-1)),l("ul",Ds,[(d(!0),f(H,null,de(F.value,t=>(d(),f("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",Ms,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,Bs),l("div",qs,"店铺名:"+v(t.shopName||"-"),1),l("div",Us,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",Ls,"平台:"+v(t.platform),1)):h("",!0),E(t)?(d(),f("div",Os,"队列状态:"+v(E(t)),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",Ks,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",Hs,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",Js,[l("div",Gs,[s[7]||(s[7]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",js,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",zs,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",Vs,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",Qs,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",Xs,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,Ws)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,Ys)):h("",!0)])]))),128))])])):h("",!0),X.value.length?(d(),f("div",Zs,[s[10]||(s[10]=l("div",{class:"result-subsection-title"},"历史记录",-1)),l("ul",et,[(d(!0),f(H,null,de(X.value,t=>(d(),f("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",st,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,tt),l("div",nt,"店铺名:"+v(t.shopName||"-"),1),l("div",at,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",lt,"平台:"+v(t.platform),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",rt,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",ot,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",ut,[l("div",it,[s[9]||(s[9]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",ct,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",dt,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",ft,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",vt,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",ht,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,pt)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,_t)):h("",!0)])]))),128))])])):h("",!0)],64)):(d(),f("div",$s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),gt=us(yt,[["__scopeId","data-v-04852f65"]]);is(gt).use(cs).mount("#app"); +import{d as We,o as Ye,I as Ze,a as d,c as f,b as es,B as ss,e as l,F as H,r as de,t as v,f as h,J as ts,K as Ae,n as De,g as y,h as J,L as ns,i as G,E as p,M as as,N as ls,O as rs,P as os,_ as us,p as is,q as cs}from"./pywebview-DiP0HdY6.js";import{e as ds}from"./brand-BATjYfEL.js";const fs={class:"page-shell module-page"},vs={class:"main-content"},hs={class:"left-panel"},ps={class:"upload-zone"},_s={class:"selected-files clean-placeholder split-selected-files"},ys={key:0,class:"more-line"},gs={key:1},ms={class:"run-row"},ks=["disabled"],ws=["disabled"],Is={class:"loading-msg"},bs={key:0,class:"queue-debug-card"},Ss={key:0,class:"queue-debug-line"},Ts={key:1,class:"queue-debug-payload"},Cs={class:"right-panel"},Fs={class:"task-list-wrap"},Es={class:"clean-result-summary"},Ps={class:"summary-card"},Rs={class:"summary-card"},xs={class:"summary-card"},Ns={class:"result-list-wrap"},$s={key:0,class:"empty-tasks"},As={key:0,class:"result-subsection"},Ds={class:"task-list clean-result-list"},Ms={class:"left split-result-main"},Bs=["title"],qs={class:"files"},Us={class:"files"},Ls={key:0,class:"files"},Os={key:1,class:"files"},Ks={key:2,class:"files"},Hs={key:3,class:"time"},Js={key:4,class:"delete-brand-progress-block"},Gs={class:"delete-brand-progress-header"},js={class:"delete-brand-progress-bar"},zs={class:"files delete-brand-progress"},Vs={key:5,class:"files split-entry-list delete-brand-preview"},Qs={key:6,class:"files"},Xs={class:"task-right split-result-actions"},Ws=["onClick"],Ys=["onClick"],Zs={key:1,class:"result-subsection"},et={class:"task-list clean-result-list"},st={class:"left split-result-main"},tt=["title"],nt={class:"files"},at={class:"files"},lt={key:0,class:"files"},rt={key:1,class:"files"},ot={key:2,class:"time"},ut={key:3,class:"delete-brand-progress-block"},it={class:"delete-brand-progress-header"},ct={class:"delete-brand-progress-bar"},dt={class:"files delete-brand-progress"},ft={key:4,class:"files split-entry-list delete-brand-preview"},vt={key:5,class:"files"},ht={class:"task-right split-result-actions"},pt=["onClick"],_t=["onClick"],yt=We({__name:"BrandDeleteBrandTab",setup(mt){function N(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const $=y([]),j=y([]),B=y(!1),fe=y([]),i=y([]),q=y([]),z=y({total:0,successCount:0,failedCount:0,items:[]}),b=y(""),S=y(""),g=y({}),T=y(null),ee=y(!1),V=y(!1),A=y(!1),D=y(""),Q=y(!1),U=y(null),se=J(()=>$.value.slice(0,10)),F=J(()=>{const e=[];return i.value.forEach(s=>{e.push(...s.items)}),e});function Me(){try{const e=typeof window<"u"?window.localStorage.getItem(N()):null;if(e){if(i.value=JSON.parse(e),i.value.length>0){const s=i.value[i.value.length-1];b.value=s.queuePushResult||"",S.value=s.queuePayloadText||""}}else i.value=[]}catch{i.value=[]}}function te(e,s,t,n){if(!s?.length)return;const a=i.value.findIndex(c=>c.taskId===e),o=a>=0?i.value[a]:null,r=s.map(c=>{const _=o?.items.find(Xe=>M(Xe,c)),k=Array.isArray(c.countries)?c.countries:void 0,m=Array.isArray(_?.countries)?_?.countries:void 0,w=k&&k.length>0?k:m&&m.length>0?m:k??m,I=Array.isArray(c.previewRows)?c.previewRows:void 0,C=Array.isArray(_?.previewRows)?_?.previewRows:void 0,ce=I&&I.length>0?I:C&&C.length>0?C:I??C;return{...c,countries:w,previewRows:ce,_pushed:_?._pushed??c._pushed??!1,_completed:_?._completed??c._completed??!1}}),u={taskId:e,items:r,createdAt:o?.createdAt||Date.now(),queuePushResult:t??o?.queuePushResult,queuePayloadText:n??o?.queuePayloadText};a>=0?i.value[a]=u:i.value.push(u),typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function ve(e){const s=i.value.length;i.value=i.value.filter(t=>t.taskId!==e),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function he(e){return e==="SUCCESS"||e==="FAILED"||e==="COMPLETED"}function Be(e){if(!e?.length)return!1;const s=new Set;if(e.forEach(n=>{n.taskId&&he(n.taskStatus)&&s.add(n.taskId)}),!s.size)return!1;const t=i.value.length;return i.value=i.value.filter(n=>!s.has(n.taskId)),i.value.length!==t?(ne(),!0):!1}const X=J(()=>q.value.filter(e=>!F.value.some(s=>M(s,e)))),qe=J(()=>F.value.length>0||X.value.length>0),Ue=J(()=>F.value.filter(e=>Re(e)&&E(e)==="未入队"));function ne(){typeof window<"u"&&(i.value.length===0?window.localStorage.removeItem(N()):window.localStorage.setItem(N(),JSON.stringify(i.value)))}function P(e){return e?(i.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function ae(e){return e&&i.value.find(s=>s.taskId===e)||null}function M(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 R(e,s){const t=ae(e);return t&&t.items.find(n=>M(n,s))||null}function pe(e){if(!e)return!1;const s=ae(e);if(!s)return!1;let t=!1;const n=g.value[e]?.line_progress?.info,a=P(e);if(n?.file_name&&n.current_line!=null&&n.total_lines!=null&&n.total_lines>0&&n.current_line>=n.total_lines){const o=s.items.find(r=>r.sourceFilename===n.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!a){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const r=s.items[0];r&&!r._completed&&(r._completed=!0,t=!0)}}return t&&ne(),t}function _e(e){return e&&g.value[e]?.task?.status||""}function W(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&g.value[s]?.task?.errorMessage||""}function ye(e){const s=e.taskId;if(!s)return!1;const t=g.value[s]?.line_progress,n=_e(s),a=P(s),o=E(e);if(a){const r=R(s,e),u=K(e)===D.value,c=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return u||c||r?._pushed||(n==="RUNNING"||n==="PENDING"||!n)&&r?._completed?!0:{success:!1,retryable:!0}}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function ge(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 me(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 Le(){fe.value=[...F.value,...X.value]}function x(){Le(),Oe(fe.value)}function Oe(e){z.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function le(e){const s=e.taskId;return s&&(g.value[s]?.fileProgress||[]).find(a=>a.fileKey&&e.fileKey?a.fileKey===e.fileKey:a.sourceFilename&&e.sourceFilename?a.sourceFilename===e.sourceFilename:!1)||null}function ke(e){const s=e.taskId;if(!s)return"";const t=g.value[s],n=t?.line_progress?.info,a=le(e);if(P(s)){const u=R(s,e),c=t?.task?.status,_=!!(n?.file_name&&n.file_name===e.sourceFilename);let k=u?._completed?"COMPLETED":(u?._pushed,"PENDING"),m=0,w=Math.max(0,e.totalRows??a?.totalRows??0);c==="SUCCESS"||c==="FAILED"&&u?._completed?(k="COMPLETED",m=w):_?(k="RUNNING",m=Math.max(0,Math.min(w||Number.MAX_SAFE_INTEGER,n?.current_line??0)),!w&&n?.total_lines&&n.total_lines>0&&(w=n.total_lines)):u?._completed?(k="COMPLETED",m=w):u?._pushed&&(k="PENDING",m=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${m}/${w}`),n?.finished_files!=null){const C=n.file_total&&n.file_total>0?`/${n.file_total}`:"";I.push(`已完成文件:${n.finished_files}${C}`)}return n?.phase&&I.push(`阶段:${n.phase}`),I.join("|")}if(a){const u=[],c=a.processedRows??0,_=a.totalRows??0;if(a.status&&u.push(`文件状态:${a.status}`),u.push(`文件进度:${c}/${_}`),n?.finished_files!=null){const k=n.file_total&&n.file_total>0?`/${n.file_total}`:"";u.push(`已完成文件:${n.finished_files}${k}`)}return n?.phase&&u.push(`阶段:${n.phase}`),u.join("|")}if(!t?.line_progress?.has_progress||!n){const u=t?.task?.status;return u?`任务状态:${u}`:""}const r=[];if(n.phase&&r.push(`阶段:${n.phase}`),n.file_index&&n.file_total&&r.push(`文件:${n.file_index}/${n.file_total}`),n.file_name&&r.push(`当前文件:${n.file_name}`),n.current_line!=null&&n.total_lines!=null&&r.push(`${P(s)?"当前文件进度":"进度"}:${n.current_line}/${n.total_lines}`),n.current_country&&r.push(`国家:${n.current_country}`),n.current_asin&&r.push(`ASIN:${n.current_asin}`),n.finished_files!=null){const u=n.file_total&&n.file_total>0?`/${n.file_total}`:"";r.push(`已完成文件:${n.finished_files}${u}`)}return r.join("|")}function Y(e){const s=e.taskId;if(!s)return 0;const t=g.value[s]?.line_progress?.info;if(P(s)){const r=R(s,e);if(g.value[s]?.task?.status==="SUCCESS"||r?._completed)return 100;const c=Math.max(0,e.totalRows??le(e)?.totalRows??0);if(!!(t?.file_name&&t.file_name===e.sourceFilename)){if(t?.current_line!=null&&t?.total_lines&&t.total_lines>0)return Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100)));if(t?.current_line!=null&&c>0)return Math.max(0,Math.min(100,Math.round(t.current_line/c*100)))}return 0}const a=le(e);return a?Math.max(0,Math.min(100,a.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function we(e){const s=g.value[e]?.task?.status;return he(s)}function L(){const e=new Set;return i.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function E(e){const s=e.taskId;if(!s||!ae(s))return"";const n=R(s,e),a=_e(s),o=g.value[s]?.line_progress,r=P(s);if(!r&&(a==="SUCCESS"||a==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(n?._completed)return"本文件解析完毕";if(a==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(r&&!n?._pushed&&!n?._completed)return"未入队";if(r&&a==="SUCCESS")return"本文件解析完毕";if(!r){const u=g.value[s];if(u?.items&&u.items.find(_=>M(_,e))&&a==="SUCCESS")return"本文件解析完毕"}return n?._pushed?"已入队":"未入队"}function Ie(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?g.value[s]?.task?.status==="SUCCESS":{success:!1,retryable:!1}}function Ke(e){const s=e?.task?.id;if(!s)return!1;const t=i.value.find(r=>r.taskId===s);if(!t)return{success:!1,retryable:!1};const n=e?.items||[];let a=!1;const o=t.items.map(r=>{const u=n.find(ce=>M(ce,r));if(!u)return r;const c=Array.isArray(u.countries)?u.countries:void 0,_=Array.isArray(r.countries)?r.countries:void 0,k=c&&c.length>0?c:_&&_.length>0?_:c??_,m=Array.isArray(u.previewRows)?u.previewRows:void 0,w=Array.isArray(r.previewRows)?r.previewRows:void 0,I=m&&m.length>0?m:w&&w.length>0?w:m??w,C={...r,...u,countries:k,previewRows:I,_pushed:r._pushed,_completed:r._completed};return JSON.stringify(C)!==JSON.stringify(r)&&(a=!0),C});for(const r of n)o.some(u=>M(u,r))||(o.push({...r,_pushed:!1,_completed:!1}),a=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,a=!0),a&&ne(),a}async function re(e){const s=e||L();if(s.length)try{const t=await ns(s);let n=!1;for(const a of t.items||[]){const o=a?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=a,Ke(a)&&(n=!0),pe(o)&&(n=!0))}n&&x()}catch{}}function He(){return document.visibilityState==="visible"?4500:1e4}function oe(e=!1){if(T.value){if(!e)return;clearTimeout(T.value),T.value=null}const s=async()=>{if(T.value=null,ee.value){oe();return}const t=L();if(!t.length)return;ee.value=!0;let n=!1,a=!1;try{await re(t),await $e();for(const o of t)we(o)&&(ve(o),n=!0,a=!0)}finally{ee.value=!1}a?await O():n&&x(),L().length>0&&oe()};e?s():T.value=window.setTimeout(s,He())}function ue(e=!1){T.value&&!e||oe(e)}function Z(e){const s=e.taskId?g.value[e.taskId]?.task?.status:null;return s==="SUCCESS"?{className:"success",text:"已完成"}:s==="FAILED"?{className:"failed",text:"失败"}:s==="RUNNING"?{className:"running",text:"执行中"}:e.taskStatus==="SUCCESS"?{className:"success",text:"已完成"}:e.taskStatus==="FAILED"?{className:"failed",text:"失败"}:e.taskStatus==="RUNNING"?{className:"running",text:"执行中"}:e.success?{className:"success",text:"已完成"}:{className:"failed",text:"失败"}}function be(){T.value&&(window.clearTimeout(T.value),T.value=null),ie()}async function Se(e){const s=G();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const n of e){const a=typeof n=="string"?n:n.absolutePath,o=typeof n=="string"?void 0:n.relativePath,r=await s.upload_file_to_java(a,o);if(!r?.success||!r.data)throw new Error(r?.error||r?.message||`上传失败:${a}`);t.push(r.data)}return t}async function Je(){const e=G();if(!e?.select_brand_xlsx_files){p.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;$.value=s,j.value=await Se(s),p.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function Ge(){const e=G();if(!e?.select_brand_folder){p.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await ds(s);if(!t.success||!t.items?.length){p.warning(t.error||"该文件夹下没有 xlsx 文件");return}$.value=t.items.map(n=>n.relativePath||n.absolutePath),j.value=await Se(t.items),p.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function je(){if(!j.value.length){p.warning("请先选择待处理文件");return}try{B.value=!0;const e=await as({files:j.value.map(a=>({fileKey:a.fileKey,originalFilename:a.originalFilename,relativePath:a.relativePath}))}),s=ge(e.items||[]),t=s.some(a=>a.matchStatus==="MATCHED"),n=s.some(a=>a.matchStatus&&a.matchStatus!=="MATCHED");b.value=t?"解析完成,可在左侧点击“推送到 Python 队列”开始串行处理":"解析完成,当前没有可推送的已匹配文件",S.value="",s.length&&s[0].taskId&&te(s[0].taskId,s,b.value,S.value),x(),n?p.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?p.success("删除品牌解析完成,请在左侧推送到 Python 队列"):p.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await O()}catch(e){p.error(e instanceof Error?e.message:"执行失败")}finally{B.value=!1}}async function Te(e){const s=e.taskId;if(!s){p.warning("未找到任务ID");return}const t=G(),n=ls(s),a=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(n,a);o.success?p.success(`已保存:${o.path||a}`):o.error&&o.error!=="用户取消"&&p.error(o.error);return}}async function O(){try{const e=await rs();q.value=ge(e.items||[]),Be(q.value),x(),await re(),ue(!0)}catch(e){console.error("loadHistory error:",e)}}function Ce(e){i.value.forEach(t=>{t.items=t.items.filter(n=>n.resultId!==e)});const s=i.value.length;i.value=i.value.filter(t=>t.items.length>0),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value)),q.value=q.value.filter(t=>t.resultId!==e),x(),L().length===0&&be()}async function Fe(e){try{await os(e),Ce(e),await O(),p.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){Ce(e),p.success("已删除");return}p.error(t)}}function Ee(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 kt(e,s){}function ie(){U.value&&(window.clearTimeout(U.value),U.value=null)}function ze(e=3e3){ie(),U.value=window.setTimeout(()=>{U.value=null,$e().catch(()=>{})},e)}function Ve(e){return e.includes("当前店铺正在执行中")}function Pe(){for(const e of i.value)for(const s of e.items){const t=E(s);if(t==="已入队"||t==="处理中")return!0}return!1}function K(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Re(e){return!!(e.taskId&&(e.matchStatus==="MATCHED"||e.matched))}function xe(){return F.value.find(e=>!Re(e)||K(e)===D.value||R(e.taskId,e)?._completed?!1:E(e)==="未入队")}async function Ne(e,s){if(s?.auto&&Pe())return e.taskId,e.sourceFilename,{success:!1,retryable:!0};const t=G(),n=e.taskId;if(!n)return{success:!1,retryable:!1};const a=i.value.find(c=>c.taskId===n);if(!a)return{success:!1,retryable:!1};if(!t?.enqueue_json)return p.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),{success:!1,retryable:!1};const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:n,items:[e]}};S.value=JSON.stringify(o,null,2);const r=await t.enqueue_json(o);let u="";if(r?.success){u=`已推送文件 ${e.sourceFilename},当前队列长度:${r.queue_size??"-"}`;const c=R(n,e);return c&&(c._pushed=!0,c._completed=!1),D.value=K(e),te(n,a.items,u,S.value),ue(!0),b.value=u,{success:!0,retryable:!1}}else{const c=r?.error||"未知错误";if(u=`推送到 Python 队列失败:${c}`,b.value=u,te(n,a.items,u,S.value),s?.auto&&Ve(c))return{success:!1,retryable:!0}}return b.value=u,{success:!1,retryable:!1}}async function Qe(){const e=xe();if(!e){p.warning("当前没有可推送的已匹配文件");return}V.value=!0,A.value=!0,ie();const s=await Ne(e);if(V.value=!1,!s.success){A.value=!1,D.value="";return}p.success("已开始按顺序推送到 Python 队列")}async function $e(){if(!A.value||Q.value){A.value,Q.value;return}if(Pe())return;const e=D.value;if(e){const t=F.value.find(n=>K(n)===e);if(t){const n=t.taskId,a=P(n);a&&(pe(n),E(t),void 0);const o=E(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(a){const r=R(n,t);if(r&&!r._completed){t.sourceFilename,r._pushed,r._completed;return}}}}const s=xe();if(!s){D.value="",A.value=!1;return}Q.value=!0;try{s.taskId,s.sourceFilename,K(s);const t=await Ne(s,{auto:!0});if(!t.success){if(t.retryable){s.taskId,s.sourceFilename,ze();return}s.taskId,s.sourceFilename,A.value=!1}}finally{Q.value=!1}}return Ye(()=>{Me();const e=L();e.length>0?re(e).then(async()=>{let s=!1,t=!1;for(const n of e)we(n)&&(ve(n),s=!0,t=!0);t?await O():s&&x(),ue(!0)}):x(),O().catch(()=>{})}),Ze(()=>{be()}),(e,s)=>(d(),f("div",fs,[es(ss,{active:"delete-brand"}),l("div",vs,[l("aside",hs,[s[2]||(s[2]=l("div",{class:"section-title"},"选择文件",-1)),l("div",ps,[s[0]||(s[0]=l("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),l("div",{class:"btns"},[l("button",{type:"button",class:"opt-btn",onClick:Je},"选择 Excel 文件"),l("button",{type:"button",class:"opt-btn",onClick:Ge},"选择文件夹")]),l("div",_s,[$.value.length?(d(),f(H,{key:0},[(d(!0),f(H,null,de(se.value,t=>(d(),f("span",{key:t},v(t),1))),128)),$.value.length>se.value.length?(d(),f("span",ys," 还有 "+v($.value.length-se.value.length)+" 个文件未展开显示 ",1)):h("",!0)],64)):(d(),f("span",gs,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=ts('
执行说明
',2)),l("div",ms,[l("button",{type:"button",class:"btn-run",disabled:B.value,onClick:je},v(B.value?"解析中...":"开始解析"),9,ks),l("button",{type:"button",class:"btn-run btn-queue",disabled:V.value||!Ue.value.length,onClick:Qe},v(V.value?"推送中...":"推送到 Python 队列"),9,ws),l("span",Is,v(B.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),b.value||S.value?(d(),f("div",bs,[s[1]||(s[1]=l("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),b.value?(d(),f("div",Ss,v(b.value),1)):h("",!0),S.value?(d(),f("pre",Ts,v(S.value),1)):h("",!0)])):h("",!0)]),l("section",Cs,[s[12]||(s[12]=l("div",{class:"panel-header"},"删除品牌结果",-1)),l("div",Fs,[l("div",Es,[l("div",Ps,[s[4]||(s[4]=l("span",{class:"summary-label"},"已处理文件",-1)),l("strong",null,v(z.value.total),1)]),l("div",Rs,[s[5]||(s[5]=l("span",{class:"summary-label"},"成功结果",-1)),l("strong",null,v(z.value.successCount),1)]),l("div",xs,[s[6]||(s[6]=l("span",{class:"summary-label"},"失败文件",-1)),l("strong",null,v(z.value.failedCount),1)])]),l("div",Ns,[s[11]||(s[11]=l("div",{class:"result-list-header"},[l("span",null,"删除品牌结果列表")],-1)),qe.value?(d(),f(H,{key:1},[F.value.length?(d(),f("div",As,[s[8]||(s[8]=l("div",{class:"result-subsection-title"},"当前任务",-1)),l("ul",Ds,[(d(!0),f(H,null,de(F.value,t=>(d(),f("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",Ms,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,Bs),l("div",qs,"店铺名:"+v(t.shopName||"-"),1),l("div",Us,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",Ls,"平台:"+v(t.platform),1)):h("",!0),E(t)?(d(),f("div",Os,"队列状态:"+v(E(t)),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",Ks,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",Hs,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",Js,[l("div",Gs,[s[7]||(s[7]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",js,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",zs,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",Vs,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",Qs,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",Xs,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,Ws)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,Ys)):h("",!0)])]))),128))])])):h("",!0),X.value.length?(d(),f("div",Zs,[s[10]||(s[10]=l("div",{class:"result-subsection-title"},"历史记录",-1)),l("ul",et,[(d(!0),f(H,null,de(X.value,t=>(d(),f("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",st,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,tt),l("div",nt,"店铺名:"+v(t.shopName||"-"),1),l("div",at,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",lt,"平台:"+v(t.platform),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",rt,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",ot,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",ut,[l("div",it,[s[9]||(s[9]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",ct,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",dt,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",ft,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",vt,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",ht,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,pt)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,_t)):h("",!0)])]))),128))])])):h("",!0)],64)):(d(),f("div",$s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),gt=us(yt,[["__scopeId","data-v-04852f65"]]);is(gt).use(cs).mount("#app"); diff --git a/app/assets/split.js b/app/assets/split.js index 61f6d5c..94ea5cf 100644 --- a/app/assets/split.js +++ b/app/assets/split.js @@ -1 +1 @@ -import{d as G,o as J,a,c as n,b as L,B as O,e,F as S,r as $,t as i,f as v,n as x,w as k,s as V,C as M,g as c,h as Q,i as F,E as r,D as W,G as X,m as Y,v as Z,H as ss,_ as es,p as ts,q as ls}from"./pywebview-D808cNhy.js";import{e as as}from"./brand-DRn3N4FA.js";const ns={class:"page-shell module-page"},os={class:"main-content"},is={class:"left-panel"},rs={class:"upload-zone"},us={class:"selected-files clean-placeholder split-selected-files"},cs={key:0,class:"more-line"},ds={key:1},ps={class:"option-group column-option-group"},vs={class:"column-toolbar"},fs={class:"column-count"},_s={class:"column-actions"},ms={key:0,class:"column-grid"},ys=["value"],gs={key:1,class:"empty-column-state"},hs={class:"option-group"},bs={class:"radio-item active"},ws={class:"desc"},ks={class:"option-group"},Cs={class:"option-group"},Ss={key:0,class:"split-input-card"},xs={key:1,class:"split-input-card"},Fs={class:"run-row"},Es=["disabled"],Ps={class:"loading-msg"},$s={class:"right-panel"},Bs={class:"task-list-wrap"},Rs={class:"clean-result-summary"},Is={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},Ds={key:1,class:"task-list clean-result-list"},Hs={class:"left split-result-main"},Ns=["title"],js={key:0,class:"files"},As={key:1,class:"time"},Ks={key:2,class:"files"},zs={key:3,class:"files split-entry-list"},qs={key:4,class:"files"},Gs={class:"task-right split-result-actions"},Js=["onClick"],Ls=["onClick"],Os=G({__name:"BrandSplitTab",setup(Ws){const f=c([]),C=c(""),d=c([]),_=c([]),p=c([]),B=c(0),u=c("rows_per_file"),m=c(2e3),y=c(5),g=c(!1),h=c([]),b=c({total:0,successCount:0,failedCount:0,items:[]}),E=Q(()=>f.value.slice(0,8));function T(l){b.value={total:l.length,successCount:l.filter(s=>s.success).length,failedCount:l.filter(s=>!s.success).length,items:l}}async function R(l){const s=F();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const o of l){const U=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(U,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${U}`);t.push(w.data)}return t}async function I(l){const s=await Y(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function D(l,s){f.value=l,C.value="",d.value=await R(l),d.value.length>0&&await I(d.value[0].fileKey),r.success(s)}async function H(){const l=F();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await l.select_brand_xlsx_files();if(!s?.length)return;await D(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function N(){const l=F();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await l.select_brand_folder();if(!s)return;C.value=s.split(/[/\\]/).filter(Boolean).pop()||"";const t=await as(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),d.value=await R(t.items),d.value.length>0&&await I(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function j(){if(!d.value.length){r.warning("请先选择待拆分 Excel 文件或文件夹");return}if(!p.value.length){r.warning("请至少选择一列保留列");return}if(u.value==="rows_per_file"&&(!m.value||m.value<=0)){r.warning("请输入有效的每份条数");return}if(u.value==="parts"&&(!y.value||y.value<=0)){r.warning("请输入有效的拆分份数");return}try{g.value=!0;const l=await W({files:d.value.map(s=>({fileKey:s.fileKey,originalFilename:s.originalFilename,relativePath:s.relativePath})),selectedColumns:p.value,splitMode:u.value,rowsPerFile:u.value==="rows_per_file"&&m.value||void 0,parts:u.value==="parts"&&y.value||void 0,archiveName:d.value.some(s=>!!s.relativePath)&&C.value?C.value:void 0});b.value=l,h.value=l.items||[],await P(),r.success("数据拆分完成")}catch(l){r.error(l instanceof Error?l.message:"数据拆分失败")}finally{g.value=!1}}async function P(){try{const l=await X();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await ss(l),await P(),r.success("已删除")}catch(s){r.error(s instanceof Error?s.message:"删除失败")}}function K(l){const s=l.slice(0,4).map(o=>o.rowCount!==void 0?`${o.filename}(${o.rowCount}条)`:o.filename);return l.length-s.length>0?`${s.join("、")} 等 ${l.length} 个文件`:s.join("、")}async function z(l){const s=F();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.zip`;if(s?.save_file_from_url_new){const o=await s.save_file_from_url_new(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}}return J(()=>{P().catch(()=>{})}),(l,s)=>(a(),n("div",ns,[L(O,{active:"split"}),e("div",os,[e("aside",is,[s[14]||(s[14]=e("div",{class:"section-title"},"选择文件",-1)),e("div",rs,[s[7]||(s[7]=e("div",{class:"hint"},"选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。",-1)),e("div",{class:"btns"},[e("button",{type:"button",class:"opt-btn",onClick:H},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:N},"选择文件夹")]),e("div",us,[f.value.length?(a(),n(S,{key:0},[(a(!0),n(S,null,$(E.value,t=>(a(),n("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(a(),n("span",cs," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",ds,"暂未选择待拆分文件"))])]),s[15]||(s[15]=e("div",{class:"section-title"},"保留列设置",-1)),e("div",ps,[e("div",vs,[e("span",fs,"已选择 "+i(p.value.length)+" / "+i(_.value.length)+" 列",1),e("div",_s,[e("button",{type:"button",class:"opt-btn small",onClick:s[0]||(s[0]=t=>p.value=[..._.value])},"全选"),e("button",{type:"button",class:"opt-btn small",onClick:s[1]||(s[1]=t=>p.value=[])},"清空")])]),_.value.length?(a(),n("div",ms,[(a(!0),n(S,null,$(_.value,t=>(a(),n("label",{key:t,class:x(["column-item",{active:p.value.includes(t)}])},[k(e("input",{"onUpdate:modelValue":s[2]||(s[2]=o=>p.value=o),type:"checkbox",value:t},null,8,ys),[[Z,p.value]]),e("span",null,i(t),1)],2))),128))])):(a(),n("div",gs,"请选择 Excel 文件后读取表头并填充可保留列"))]),s[16]||(s[16]=e("div",{class:"section-title"},"总条数",-1)),e("div",hs,[e("label",bs,[s[9]||(s[9]=e("input",{type:"checkbox",checked:"",disabled:""},null,-1)),e("div",null,[s[8]||(s[8]=e("span",{class:"label"},"当前数据总条数",-1)),e("div",ws,i(B.value)+" 条(不含表头)",1)])])]),s[17]||(s[17]=e("div",{class:"section-title"},"拆分模式",-1)),e("div",ks,[e("label",{class:x(["radio-item",{active:u.value==="rows_per_file"}])},[k(e("input",{"onUpdate:modelValue":s[3]||(s[3]=t=>u.value=t),type:"radio",value:"rows_per_file",name:"split-mode"},null,512),[[V,u.value]]),s[10]||(s[10]=e("div",null,[e("span",{class:"label"},"按每份条数"),e("div",{class:"desc"},"例如每份 2000 条,最后一份放剩余数据")],-1))],2),e("label",{class:x(["radio-item",{active:u.value==="parts"}])},[k(e("input",{"onUpdate:modelValue":s[4]||(s[4]=t=>u.value=t),type:"radio",value:"parts",name:"split-mode"},null,512),[[V,u.value]]),s[11]||(s[11]=e("div",null,[e("span",{class:"label"},"按份数平均拆分"),e("div",{class:"desc"},"例如拆 5 份,按总条数尽量平均分配")],-1))],2)]),s[18]||(s[18]=e("div",{class:"section-title"},"拆分参数",-1)),e("div",Cs,[u.value==="rows_per_file"?(a(),n("label",Ss,[s[12]||(s[12]=e("span",{class:"label"},"每份条数",-1)),k(e("input",{"onUpdate:modelValue":s[5]||(s[5]=t=>m.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 2000"},null,512),[[M,m.value,void 0,{number:!0}]])])):(a(),n("label",xs,[s[13]||(s[13]=e("span",{class:"label"},"拆分份数",-1)),k(e("input",{"onUpdate:modelValue":s[6]||(s[6]=t=>y.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 5"},null,512),[[M,y.value,void 0,{number:!0}]])]))]),e("div",Fs,[e("button",{type:"button",class:"btn-run",disabled:g.value,onClick:j},i(g.value?"拆分中...":"开始拆分"),9,Es),e("span",Ps,i(g.value?"正在拆分并上传结果,请稍候…":"选择文件、保留列和拆分规则后即可执行拆分,结果会显示在右侧供下载"),1)])]),e("section",$s,[s[23]||(s[23]=e("div",{class:"panel-header"},"拆分结果",-1)),e("div",Bs,[e("div",Rs,[e("div",Is,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Us,[s[20]||(s[20]=e("span",{class:"summary-label"},"成功结果",-1)),e("strong",null,i(b.value.successCount),1)]),e("div",Vs,[s[21]||(s[21]=e("span",{class:"summary-label"},"失败文件",-1)),e("strong",null,i(b.value.failedCount),1)])]),e("div",Ms,[s[22]||(s[22]=e("div",{class:"result-list-header"},[e("span",null,"拆分结果压缩包列表")],-1)),h.value.length===0?(a(),n("div",Ts," 暂无拆分结果,完成数据拆分后会在这里展示压缩包文件 ")):(a(),n("ul",Ds,[(a(!0),n(S,null,$(h.value,t=>(a(),n("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}-${t.rowCount||0}`,class:"task-item split-result-item"},[e("div",Hs,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Ns),t.outputFilename?(a(),n("div",js,"压缩包文件:"+i(t.outputFilename),1)):v("",!0),t.rowCount!==void 0?(a(),n("div",As,"压缩包共包含 "+i(t.rowCount)+" 条数据",1)):v("",!0),t.entryCount&&t.entryCount>0?(a(),n("div",Ks,"压缩包内共 "+i(t.entryCount)+" 个拆分文件 ",1)):v("",!0),t.entries&&t.entries.length?(a(),n("div",zs," 压缩包内容:"+i(K(t.entries)),1)):v("",!0),t.error?(a(),n("div",qs,"错误信息:"+i(t.error),1)):v("",!0)]),e("div",Gs,[e("span",{class:x(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(a(),n("button",{key:0,type:"button",class:"download",onClick:o=>z(t)}," 下载压缩包 ",8,Js)):v("",!0),t.resultId?(a(),n("button",{key:1,type:"button",class:"btn-delete",onClick:o=>A(t.resultId)}," 删除 ",8,Ls)):v("",!0)])]))),128))]))])])])])]))}}),Qs=es(Os,[["__scopeId","data-v-c5a98d6b"]]);ts(Qs).use(ls).mount("#app"); +import{d as G,o as J,a,c as n,b as L,B as O,e,F as S,r as $,t as i,f as v,n as x,w as k,s as V,C as M,g as c,h as Q,i as F,E as r,D as W,G as X,m as Y,v as Z,H as ss,_ as es,p as ts,q as ls}from"./pywebview-DiP0HdY6.js";import{e as as}from"./brand-BATjYfEL.js";const ns={class:"page-shell module-page"},os={class:"main-content"},is={class:"left-panel"},rs={class:"upload-zone"},us={class:"selected-files clean-placeholder split-selected-files"},cs={key:0,class:"more-line"},ds={key:1},ps={class:"option-group column-option-group"},vs={class:"column-toolbar"},fs={class:"column-count"},_s={class:"column-actions"},ms={key:0,class:"column-grid"},ys=["value"],gs={key:1,class:"empty-column-state"},hs={class:"option-group"},bs={class:"radio-item active"},ws={class:"desc"},ks={class:"option-group"},Cs={class:"option-group"},Ss={key:0,class:"split-input-card"},xs={key:1,class:"split-input-card"},Fs={class:"run-row"},Es=["disabled"],Ps={class:"loading-msg"},$s={class:"right-panel"},Bs={class:"task-list-wrap"},Rs={class:"clean-result-summary"},Is={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},Ds={key:1,class:"task-list clean-result-list"},Hs={class:"left split-result-main"},Ns=["title"],js={key:0,class:"files"},As={key:1,class:"time"},Ks={key:2,class:"files"},zs={key:3,class:"files split-entry-list"},qs={key:4,class:"files"},Gs={class:"task-right split-result-actions"},Js=["onClick"],Ls=["onClick"],Os=G({__name:"BrandSplitTab",setup(Ws){const f=c([]),C=c(""),d=c([]),_=c([]),p=c([]),B=c(0),u=c("rows_per_file"),m=c(2e3),y=c(5),g=c(!1),h=c([]),b=c({total:0,successCount:0,failedCount:0,items:[]}),E=Q(()=>f.value.slice(0,8));function T(l){b.value={total:l.length,successCount:l.filter(s=>s.success).length,failedCount:l.filter(s=>!s.success).length,items:l}}async function R(l){const s=F();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const o of l){const U=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(U,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${U}`);t.push(w.data)}return t}async function I(l){const s=await Y(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function D(l,s){f.value=l,C.value="",d.value=await R(l),d.value.length>0&&await I(d.value[0].fileKey),r.success(s)}async function H(){const l=F();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await l.select_brand_xlsx_files();if(!s?.length)return;await D(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function N(){const l=F();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await l.select_brand_folder();if(!s)return;C.value=s.split(/[/\\]/).filter(Boolean).pop()||"";const t=await as(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),d.value=await R(t.items),d.value.length>0&&await I(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function j(){if(!d.value.length){r.warning("请先选择待拆分 Excel 文件或文件夹");return}if(!p.value.length){r.warning("请至少选择一列保留列");return}if(u.value==="rows_per_file"&&(!m.value||m.value<=0)){r.warning("请输入有效的每份条数");return}if(u.value==="parts"&&(!y.value||y.value<=0)){r.warning("请输入有效的拆分份数");return}try{g.value=!0;const l=await W({files:d.value.map(s=>({fileKey:s.fileKey,originalFilename:s.originalFilename,relativePath:s.relativePath})),selectedColumns:p.value,splitMode:u.value,rowsPerFile:u.value==="rows_per_file"&&m.value||void 0,parts:u.value==="parts"&&y.value||void 0,archiveName:d.value.some(s=>!!s.relativePath)&&C.value?C.value:void 0});b.value=l,h.value=l.items||[],await P(),r.success("数据拆分完成")}catch(l){r.error(l instanceof Error?l.message:"数据拆分失败")}finally{g.value=!1}}async function P(){try{const l=await X();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await ss(l),await P(),r.success("已删除")}catch(s){r.error(s instanceof Error?s.message:"删除失败")}}function K(l){const s=l.slice(0,4).map(o=>o.rowCount!==void 0?`${o.filename}(${o.rowCount}条)`:o.filename);return l.length-s.length>0?`${s.join("、")} 等 ${l.length} 个文件`:s.join("、")}async function z(l){const s=F();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.zip`;if(s?.save_file_from_url_new){const o=await s.save_file_from_url_new(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}}return J(()=>{P().catch(()=>{})}),(l,s)=>(a(),n("div",ns,[L(O,{active:"split"}),e("div",os,[e("aside",is,[s[14]||(s[14]=e("div",{class:"section-title"},"选择文件",-1)),e("div",rs,[s[7]||(s[7]=e("div",{class:"hint"},"选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。",-1)),e("div",{class:"btns"},[e("button",{type:"button",class:"opt-btn",onClick:H},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:N},"选择文件夹")]),e("div",us,[f.value.length?(a(),n(S,{key:0},[(a(!0),n(S,null,$(E.value,t=>(a(),n("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(a(),n("span",cs," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",ds,"暂未选择待拆分文件"))])]),s[15]||(s[15]=e("div",{class:"section-title"},"保留列设置",-1)),e("div",ps,[e("div",vs,[e("span",fs,"已选择 "+i(p.value.length)+" / "+i(_.value.length)+" 列",1),e("div",_s,[e("button",{type:"button",class:"opt-btn small",onClick:s[0]||(s[0]=t=>p.value=[..._.value])},"全选"),e("button",{type:"button",class:"opt-btn small",onClick:s[1]||(s[1]=t=>p.value=[])},"清空")])]),_.value.length?(a(),n("div",ms,[(a(!0),n(S,null,$(_.value,t=>(a(),n("label",{key:t,class:x(["column-item",{active:p.value.includes(t)}])},[k(e("input",{"onUpdate:modelValue":s[2]||(s[2]=o=>p.value=o),type:"checkbox",value:t},null,8,ys),[[Z,p.value]]),e("span",null,i(t),1)],2))),128))])):(a(),n("div",gs,"请选择 Excel 文件后读取表头并填充可保留列"))]),s[16]||(s[16]=e("div",{class:"section-title"},"总条数",-1)),e("div",hs,[e("label",bs,[s[9]||(s[9]=e("input",{type:"checkbox",checked:"",disabled:""},null,-1)),e("div",null,[s[8]||(s[8]=e("span",{class:"label"},"当前数据总条数",-1)),e("div",ws,i(B.value)+" 条(不含表头)",1)])])]),s[17]||(s[17]=e("div",{class:"section-title"},"拆分模式",-1)),e("div",ks,[e("label",{class:x(["radio-item",{active:u.value==="rows_per_file"}])},[k(e("input",{"onUpdate:modelValue":s[3]||(s[3]=t=>u.value=t),type:"radio",value:"rows_per_file",name:"split-mode"},null,512),[[V,u.value]]),s[10]||(s[10]=e("div",null,[e("span",{class:"label"},"按每份条数"),e("div",{class:"desc"},"例如每份 2000 条,最后一份放剩余数据")],-1))],2),e("label",{class:x(["radio-item",{active:u.value==="parts"}])},[k(e("input",{"onUpdate:modelValue":s[4]||(s[4]=t=>u.value=t),type:"radio",value:"parts",name:"split-mode"},null,512),[[V,u.value]]),s[11]||(s[11]=e("div",null,[e("span",{class:"label"},"按份数平均拆分"),e("div",{class:"desc"},"例如拆 5 份,按总条数尽量平均分配")],-1))],2)]),s[18]||(s[18]=e("div",{class:"section-title"},"拆分参数",-1)),e("div",Cs,[u.value==="rows_per_file"?(a(),n("label",Ss,[s[12]||(s[12]=e("span",{class:"label"},"每份条数",-1)),k(e("input",{"onUpdate:modelValue":s[5]||(s[5]=t=>m.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 2000"},null,512),[[M,m.value,void 0,{number:!0}]])])):(a(),n("label",xs,[s[13]||(s[13]=e("span",{class:"label"},"拆分份数",-1)),k(e("input",{"onUpdate:modelValue":s[6]||(s[6]=t=>y.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 5"},null,512),[[M,y.value,void 0,{number:!0}]])]))]),e("div",Fs,[e("button",{type:"button",class:"btn-run",disabled:g.value,onClick:j},i(g.value?"拆分中...":"开始拆分"),9,Es),e("span",Ps,i(g.value?"正在拆分并上传结果,请稍候…":"选择文件、保留列和拆分规则后即可执行拆分,结果会显示在右侧供下载"),1)])]),e("section",$s,[s[23]||(s[23]=e("div",{class:"panel-header"},"拆分结果",-1)),e("div",Bs,[e("div",Rs,[e("div",Is,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Us,[s[20]||(s[20]=e("span",{class:"summary-label"},"成功结果",-1)),e("strong",null,i(b.value.successCount),1)]),e("div",Vs,[s[21]||(s[21]=e("span",{class:"summary-label"},"失败文件",-1)),e("strong",null,i(b.value.failedCount),1)])]),e("div",Ms,[s[22]||(s[22]=e("div",{class:"result-list-header"},[e("span",null,"拆分结果压缩包列表")],-1)),h.value.length===0?(a(),n("div",Ts," 暂无拆分结果,完成数据拆分后会在这里展示压缩包文件 ")):(a(),n("ul",Ds,[(a(!0),n(S,null,$(h.value,t=>(a(),n("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}-${t.rowCount||0}`,class:"task-item split-result-item"},[e("div",Hs,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Ns),t.outputFilename?(a(),n("div",js,"压缩包文件:"+i(t.outputFilename),1)):v("",!0),t.rowCount!==void 0?(a(),n("div",As,"压缩包共包含 "+i(t.rowCount)+" 条数据",1)):v("",!0),t.entryCount&&t.entryCount>0?(a(),n("div",Ks,"压缩包内共 "+i(t.entryCount)+" 个拆分文件 ",1)):v("",!0),t.entries&&t.entries.length?(a(),n("div",zs," 压缩包内容:"+i(K(t.entries)),1)):v("",!0),t.error?(a(),n("div",qs,"错误信息:"+i(t.error),1)):v("",!0)]),e("div",Gs,[e("span",{class:x(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(a(),n("button",{key:0,type:"button",class:"download",onClick:o=>z(t)}," 下载压缩包 ",8,Js)):v("",!0),t.resultId?(a(),n("button",{key:1,type:"button",class:"btn-delete",onClick:o=>A(t.resultId)}," 删除 ",8,Ls)):v("",!0)])]))),128))]))])])])])]))}}),Qs=es(Os,[["__scopeId","data-v-c5a98d6b"]]);ts(Qs).use(ls).mount("#app"); diff --git a/app/new_web_source/convert.html b/app/new_web_source/convert.html index 6eeb71d..dd3590c 100644 --- a/app/new_web_source/convert.html +++ b/app/new_web_source/convert.html @@ -5,9 +5,9 @@ 格式转换 - 数富AI - - - + + + diff --git a/app/new_web_source/dedupe.html b/app/new_web_source/dedupe.html index b272de0..419ddc9 100644 --- a/app/new_web_source/dedupe.html +++ b/app/new_web_source/dedupe.html @@ -5,9 +5,9 @@ 数据去重 - 数富AI - - - + + + diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html index e210015..a9f1ac1 100644 --- a/app/new_web_source/delete-brand.html +++ b/app/new_web_source/delete-brand.html @@ -5,9 +5,9 @@ 删除品牌 - 数富AI - - - + + + diff --git a/app/new_web_source/split.html b/app/new_web_source/split.html index c4bcbe5..6e0fdd4 100644 --- a/app/new_web_source/split.html +++ b/app/new_web_source/split.html @@ -5,9 +5,9 @@ 数据拆分 - 数富AI - - - + + + diff --git a/backend-java/aiimage-backend.log.2026-04-12.0.gz b/backend-java/aiimage-backend.log.2026-04-12.0.gz new file mode 100644 index 0000000..e5cb5c4 Binary files /dev/null and b/backend-java/aiimage-backend.log.2026-04-12.0.gz differ diff --git a/backend-java/aiimage-backend.log.2026-04-13.0.gz b/backend-java/aiimage-backend.log.2026-04-13.0.gz new file mode 100644 index 0000000..a6fe229 Binary files /dev/null and b/backend-java/aiimage-backend.log.2026-04-13.0.gz differ 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 f14c26b..b3500b0 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 @@ -21,6 +21,12 @@ public class DeleteBrandProgressProperties { private long productRiskStaleTimeoutMinutes = 10; private long productRiskInitialTimeoutMinutes = 10; + /** + * Price track RUNNING timeout auto-finalize/fail threshold in minutes. + */ + private long priceTrackStaleTimeoutMinutes = 10; + private long priceTrackInitialTimeoutMinutes = 10; + /** * Shop match RUNNING timeout auto-finalize/fail threshold in minutes. */ 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 1e26bab..f5ae7e8 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", "PRODUCT_RISK_RESOLVE")); + private List moduleTypes = new ArrayList<>(List.of("DEDUPE", "SPLIT", "CONVERT", "DELETE_BRAND", "PRODUCT_RISK_RESOLVE", "PRICE_TRACK")); } 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 0a8d949..703a2ce 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 @@ -6,6 +6,8 @@ import com.nanri.aiimage.common.service.DistributedJobLockService; import com.nanri.aiimage.config.DeleteBrandProgressProperties; import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskCacheService; import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskService; +import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskCacheService; +import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskService; import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskCacheService; import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskService; import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; @@ -28,6 +30,7 @@ public class DeleteBrandStaleTaskService { private static final String MODULE_TYPE_DELETE_BRAND = "DELETE_BRAND"; private static final String MODULE_TYPE_PRODUCT_RISK = "PRODUCT_RISK_RESOLVE"; + private static final String MODULE_TYPE_PRICE_TRACK = "PRICE_TRACK"; private static final String MODULE_TYPE_SHOP_MATCH = "SHOP_MATCH"; private static final Duration STALE_CHECK_LOCK_TTL = Duration.ofMinutes(10); private static final Duration FINALIZE_CHECK_LOCK_TTL = Duration.ofMinutes(10); @@ -37,6 +40,8 @@ public class DeleteBrandStaleTaskService { private final DeleteBrandRunService deleteBrandRunService; private final ProductRiskTaskService productRiskTaskService; private final ProductRiskTaskCacheService productRiskTaskCacheService; + private final PriceTrackTaskService priceTrackTaskService; + private final PriceTrackTaskCacheService priceTrackTaskCacheService; private final ShopMatchTaskService shopMatchTaskService; private final ShopMatchTaskCacheService shopMatchTaskCacheService; private final DeleteBrandProgressProperties deleteBrandProgressProperties; @@ -55,6 +60,7 @@ public class DeleteBrandStaleTaskService { log.info("[stale-check] scan started thread={}", Thread.currentThread().getName()); failStaleDeleteBrandTasks(); ProductRiskStaleCheckStats stats = failStaleProductRiskResolveTasks(); + PriceTrackStaleCheckStats priceTrackStats = failStalePriceTrackTasks(); ShopMatchStaleCheckStats shopMatchStats = failStaleShopMatchTasks(); log.info("[stale-check] product-risk summary scanned={} finalized={} failed={} skipped={} elapsedMs={} thread={}", stats.scannedTaskCount, @@ -63,6 +69,13 @@ public class DeleteBrandStaleTaskService { stats.skippedTaskCount, System.currentTimeMillis() - startedAt, Thread.currentThread().getName()); + log.info("[stale-check] price-track summary scanned={} finalized={} failed={} skipped={} elapsedMs={} thread={}", + priceTrackStats.scannedTaskCount, + priceTrackStats.finalizedTaskCount, + priceTrackStats.failedTaskCount, + priceTrackStats.skippedTaskCount, + System.currentTimeMillis() - startedAt, + Thread.currentThread().getName()); log.info("[stale-check] shop-match summary scanned={} finalized={} failed={} skipped={} elapsedMs={} thread={}", shopMatchStats.scannedTaskCount, shopMatchStats.finalizedTaskCount, @@ -196,6 +209,67 @@ public class DeleteBrandStaleTaskService { return stats; } + private PriceTrackStaleCheckStats failStalePriceTrackTasks() { + PriceTrackStaleCheckStats stats = new PriceTrackStaleCheckStats(); + long minutes = Math.max(1L, deleteBrandProgressProperties.getPriceTrackStaleTimeoutMinutes()); + long initialMinutes = Math.max(minutes, deleteBrandProgressProperties.getPriceTrackInitialTimeoutMinutes()); + long staleTimeoutMillis = Duration.ofMinutes(minutes).toMillis(); + long nowMillis = System.currentTimeMillis(); + LocalDateTime now = LocalDateTime.now(); + LocalDateTime threshold = now.minusMinutes(minutes); + LocalDateTime initialThreshold = now.minusMinutes(initialMinutes); + java.util.List runningTasks = fileTaskMapper.selectList(new LambdaQueryWrapper() + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRICE_TRACK) + .eq(FileTaskEntity::getStatus, "RUNNING") + .lt(FileTaskEntity::getUpdatedAt, threshold) + .last("limit 200")); + stats.scannedTaskCount = runningTasks.size(); + if (runningTasks.isEmpty()) { + return stats; + } + log.info("[stale-check] price-track candidates={} threshold={} timeoutMinutes={} initialThreshold={} initialTimeoutMinutes={}", + runningTasks.size(), threshold, minutes, initialThreshold, initialMinutes); + for (FileTaskEntity task : runningTasks) { + long lastHeartbeatMillis = priceTrackTaskCacheService.getTaskHeartbeatMillis(task.getId()); + boolean hasFinishedRows = (task.getSuccessFileCount() != null && task.getSuccessFileCount() > 0) + || (task.getFailedFileCount() != null && task.getFailedFileCount() > 0); + boolean hasStartedProgress = lastHeartbeatMillis > 0L || hasFinishedRows; + if (lastHeartbeatMillis > 0L && nowMillis - lastHeartbeatMillis < staleTimeoutMillis) { + stats.skippedTaskCount++; + continue; + } + if (!hasStartedProgress && task.getCreatedAt() != null && task.getCreatedAt().isAfter(initialThreshold)) { + stats.skippedTaskCount++; + continue; + } + try { + if (priceTrackTaskService.tryFinalizeTask(task.getId(), true)) { + stats.finalizedTaskCount++; + log.info("[stale-check] price-track finalized taskId={}", task.getId()); + continue; + } + } catch (Exception ex) { + log.warn("[stale-check] price-track finalize threw taskId={} msg={}", task.getId(), ex.getMessage()); + } + int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper() + .eq(FileTaskEntity::getId, task.getId()) + .eq(FileTaskEntity::getModuleType, MODULE_TYPE_PRICE_TRACK) + .eq(FileTaskEntity::getStatus, "RUNNING") + .set(FileTaskEntity::getStatus, "FAILED") + .set(FileTaskEntity::getErrorMessage, "长时间未收到 Python 结果回传,任务已自动失败") + .set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()) + .set(FileTaskEntity::getFinishedAt, LocalDateTime.now())); + if (updated > 0) { + stats.failedTaskCount++; + priceTrackTaskCacheService.deleteTaskCache(task.getId()); + log.warn("[stale-check] price-track failed taskId={} reason=timeout", task.getId()); + } else { + stats.skippedTaskCount++; + } + } + return stats; + } + private ShopMatchStaleCheckStats failStaleShopMatchTasks() { ShopMatchStaleCheckStats stats = new ShopMatchStaleCheckStats(); long minutes = Math.max(1L, deleteBrandProgressProperties.getShopMatchStaleTimeoutMinutes()); @@ -291,4 +365,11 @@ public class DeleteBrandStaleTaskService { private int failedTaskCount; private int skippedTaskCount; } + + private static final class PriceTrackStaleCheckStats { + private int scannedTaskCount; + private int finalizedTaskCount; + private int failedTaskCount; + private int skippedTaskCount; + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java index fbaf64d..cf1b812 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java @@ -2,16 +2,19 @@ package com.nanri.aiimage.modules.pricetrack.controller; import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCandidateAddRequest; +import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCountryPreferenceSaveRequest; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCreateTaskRequest; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackMatchShopsRequest; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest; -import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCountryPreferenceSaveRequest; +import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackTaskBatchRequest; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCandidateVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCountryPreferenceVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCreateTaskVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackDashboardVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackHistoryVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackPendingDeleteVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackTaskBatchVo; import com.nanri.aiimage.modules.pricetrack.service.PriceTrackService; import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskService; import io.swagger.v3.oas.annotations.Operation; @@ -20,127 +23,164 @@ import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.net.URLEncoder; 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/price-track") -@Tag(name = "跟价", description = "亚马逊跟价处理:备选店铺、紫鸟匹配、创建任务、Python队列与回传。") +@Tag( + name = "跟价", + description = "亚马逊跟价处理模块:包含备选店铺、紫鸟匹配、任务创建、Python 回传、任务轮询和结果下载接口。查询类接口需要携带 Query 参数 user_id。") public class PriceTrackController { private final PriceTrackService priceTrackService; private final PriceTrackTaskService priceTrackTaskService; @GetMapping("/candidates") - @Operation(summary = "查询备选店铺列表") - public ApiResponse> listCandidates( - @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY) + @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(priceTrackService.listCandidates(userId)); } @PostMapping("/candidates") - @Operation(summary = "新增备选店铺") + @Operation(summary = "新增备选店铺", description = "把店铺名称写入当前用户的备选店铺列表,供后续匹配和创建任务使用。") public ApiResponse addCandidate(@Valid @RequestBody PriceTrackCandidateAddRequest request) { return ApiResponse.success(priceTrackService.addCandidate(request)); } @DeleteMapping("/candidates/{id}") - @Operation(summary = "删除备选店铺") + @Operation(summary = "删除备选店铺", description = "删除一条备选店铺记录,id 必须属于当前 user_id。") public ApiResponse deleteCandidate( - @PathVariable Long id, - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @Parameter(description = "备选店铺记录主键", example = "10") @PathVariable Long id, + @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") + @RequestParam("user_id") Long userId) { priceTrackService.deleteCandidate(userId, id); return ApiResponse.success(null); } @GetMapping("/country-preference") - @Operation(summary = "查询国家处理顺序") + @Operation(summary = "查询国家处理顺序", description = "返回当前用户保存的国家代码列表,顺序即跟价任务处理顺序。") public ApiResponse getCountryPreference( - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") + @RequestParam("user_id") Long userId) { return ApiResponse.success(priceTrackService.getCountryPreference(userId)); } @PutMapping("/country-preference") - @Operation(summary = "保存国家处理顺序") + @Operation(summary = "保存国家处理顺序", description = "保存当前用户在跟价模块中的国家勾选和处理顺序。") public ApiResponse saveCountryPreference( @Valid @RequestBody PriceTrackCountryPreferenceSaveRequest request) { return ApiResponse.success(priceTrackService.saveCountryPreference(request)); } @PostMapping("/match-shops") - @Operation(summary = "批量匹配店铺") + @Operation(summary = "批量匹配店铺", description = "按店铺名查询紫鸟索引,返回 shopId、platform、companyName、matchStatus 等信息。") public ApiResponse matchShops(@Valid @RequestBody PriceTrackMatchShopsRequest request) { return ApiResponse.success(priceTrackService.matchShops(request)); } @GetMapping("/dashboard") - @Operation(summary = "统计看板") + @Operation(summary = "统计看板", description = "返回备选店铺数、已结束任务数、成功任务数和失败任务数。") public ApiResponse dashboard( - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") + @RequestParam("user_id") Long userId) { return ApiResponse.success(priceTrackTaskService.dashboard(userId)); } @GetMapping("/history") - @Operation(summary = "处理记录列表") + @Operation(summary = "处理记录列表", description = "返回当前用户跟价模块下各店铺结果行,包含运行中和历史记录。") public ApiResponse history( - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") + @RequestParam("user_id") Long userId) { return ApiResponse.success(priceTrackTaskService.listHistory(userId)); } @DeleteMapping("/history/{resultId}") - @Operation(summary = "删除单条结果记录") + @Operation(summary = "删除单条结果记录", description = "删除一条 biz_file_result,并同步重算父任务状态。") public ApiResponse deleteHistory( - @PathVariable Long resultId, - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @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) { priceTrackTaskService.deleteHistory(resultId, userId); return ApiResponse.success(null); } @PostMapping("/tasks") - @Operation(summary = "创建跟价处理任务") + @Operation(summary = "创建跟价任务", description = "落库 RUNNING 任务和各店铺占位结果,返回 taskId 和初始 items 快照。") public ApiResponse createTask(@Valid @RequestBody PriceTrackCreateTaskRequest request) { return ApiResponse.success(priceTrackTaskService.createTask(request)); } @DeleteMapping("/tasks/{taskId}") - @Operation(summary = "删除整条任务") + @Operation(summary = "删除整条任务", description = "删除该任务以及其下属全部结果行,RUNNING、SUCCESS、FAILED 均可。") public ApiResponse deleteTask( - @PathVariable Long taskId, - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId) { + @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) { priceTrackTaskService.deleteTask(taskId, userId); return ApiResponse.success(null); } + @DeleteMapping("/pending-shop-result") + @Operation(summary = "按店铺名删除运行中结果", description = "仅在 RUNNING 任务下按规范化店名删除一条 biz_file_result,并同步重算任务状态。") + 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 = "店铺名称", required = true, in = ParameterIn.QUERY, example = "某某店铺") + @RequestParam("shop_name") String shopName) { + return ApiResponse.success(priceTrackTaskService.deletePendingShopResult(userId, shopName)); + } + + @PostMapping("/tasks/batch") + @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概要和各店铺结果,供前端轮询使用。") + public ApiResponse tasksBatch(@Valid @RequestBody PriceTrackTaskBatchRequest request) { + return ApiResponse.success(priceTrackTaskService.getTaskDetailsBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") - @Operation(summary = "Python回传处理结果") - public ApiResponse submitResult(@PathVariable Long taskId, + @Operation(summary = "Python 回传处理结果", description = "同一 taskId 可多次回传。成功时按 countries 生成结果文件,所有店铺进入终态后任务会变为 SUCCESS 或 FAILED。") + public ApiResponse submitResult( + @Parameter(description = "任务主键,必须处于 RUNNING 状态", example = "200") @PathVariable Long taskId, @Valid @RequestBody PriceTrackSubmitResultRequest request) { priceTrackTaskService.submitResult(taskId, request); return ApiResponse.success(null); } @GetMapping("/results/{resultId}/download") - @Operation(summary = "下载结果文件") + @Operation(summary = "下载结果文件", description = "按结果记录下载后端生成的跟价 Excel 文件。") public void downloadResult( - @PathVariable Long resultId, - @Parameter(name = "user_id", required = true, in = ParameterIn.QUERY) @RequestParam("user_id") Long userId, + @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 = priceTrackTaskService.resolveResultDownloadUrl(resultId, userId); String filename = priceTrackTaskService.resolveResultDownloadFilename(resultId, userId); if (url == null || url.isBlank()) { - throw new ResponseStatusException(org.springframework.http.HttpStatus.NOT_FOUND, "暂无可下载结果"); + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "暂无可下载结果"); } try { String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"); response.setContentType("application/octet-stream"); - response.setHeader(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, + 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]; @@ -151,7 +191,7 @@ public class PriceTrackController { response.getOutputStream().flush(); } } catch (Exception ex) { - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, "下载失败"); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "下载失败"); } } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCandidateAddRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCandidateAddRequest.java index 52130b5..903cc95 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCandidateAddRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCandidateAddRequest.java @@ -1,14 +1,18 @@ package com.nanri.aiimage.modules.pricetrack.model.dto; +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 PriceTrackCandidateAddRequest { @NotNull(message = "user_id不能为空") + @Schema(description = "当前用户 ID,数据按用户隔离", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; - @NotBlank(message = "店铺名不能为空") + @NotBlank(message = "店铺名称不能为空") + @Schema(description = "店铺名称,入库前会先做规范化和去重", requiredMode = Schema.RequiredMode.REQUIRED, example = "测试店铺A") private String shopName; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCountryPreferenceSaveRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCountryPreferenceSaveRequest.java index 398bf35..e12acf0 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCountryPreferenceSaveRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCountryPreferenceSaveRequest.java @@ -1,15 +1,20 @@ package com.nanri.aiimage.modules.pricetrack.model.dto; +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 = "保存用户五国处理顺序:代码仅支持 DE、UK、FR、IT、ES,且不能重复") public class PriceTrackCountryPreferenceSaveRequest { @NotNull(message = "user_id不能为空") + @Schema(description = "当前用户 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; @NotEmpty(message = "国家列表不能为空") + @Schema(description = "国家代码列表,顺序即任务处理顺序", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"DE\",\"UK\",\"FR\"]") private List countryCodes; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCreateTaskRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCreateTaskRequest.java index b57fdf2..66d4e04 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCreateTaskRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackCreateTaskRequest.java @@ -1,35 +1,36 @@ package com.nanri.aiimage.modules.pricetrack.model.dto; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo; +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.List; -import java.util.Map; @Data +@Schema(description = "创建跟价任务请求体:在推送 Python 队列前调用,用于落库任务和店铺结果占位记录") public class PriceTrackCreateTaskRequest { @NotNull(message = "user_id不能为空") + @Schema(description = "任务所属用户 ID,会写入 biz_file_task.user_id", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; - /** 跟价模式:status_mode=按商品状态(全量), asin_mode=按指定ASIN(自定义) */ + @Schema(description = "是否启用按商品状态处理模式") private boolean statusMode; + + @Schema(description = "是否启用按指定 ASIN 文件处理模式") private boolean asinMode; - /** 匹配好的店铺队列项 */ @NotEmpty(message = "店铺列表不能为空") - private List> items; + @Valid + @Schema(description = "已匹配的店铺列表,每项都应为 matched=true;服务端会按规范化店名去重", requiredMode = Schema.RequiredMode.REQUIRED) + private List items; - /** ASIN文档路径(asinMode时使用) */ + @Schema(description = "ASIN 文件路径列表;asinMode=true 时由前端上传或选择后传入", example = "[\"/tmp/a.xlsx\",\"/tmp/b.csv\"]") private List asinFiles; - /** 国家代码列表 */ @NotEmpty(message = "国家列表不能为空") + @Schema(description = "国家代码列表,顺序即跟价处理顺序", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"DE\",\"UK\",\"FR\"]") private List countryCodes; - - /** 价格区间 */ - private Double minPrice; - private Double maxPrice; - - /** 价差比例(%) */ - private Double priceDiffPercent; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java index 56ff150..a743000 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java @@ -1,15 +1,20 @@ package com.nanri.aiimage.modules.pricetrack.model.dto; +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 PriceTrackMatchShopsRequest { @NotNull(message = "user_id不能为空") + @Schema(description = "当前用户 ID,用于审计和数据归属", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; @NotEmpty(message = "店铺列表不能为空") + @Schema(description = "待匹配的店铺名称列表,至少 1 个;返回体 items 与列表顺序对应", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"店铺甲\",\"店铺乙\"]") private List shopNames; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java index 4ea279b..5663628 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java @@ -1,27 +1,49 @@ package com.nanri.aiimage.modules.pricetrack.model.dto; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; + import java.util.List; import java.util.Map; @Data +@Schema(description = "Python 回传跟价结果请求体:按店铺提交各国家 ASIN 跟价结果或错误信息") public class PriceTrackSubmitResultRequest { + @Schema(description = "本次回传涉及的店铺列表,至少 1 个,店名需要能和任务结果行匹配", requiredMode = Schema.RequiredMode.REQUIRED) private List shops; @Data + @Schema(description = "单个店铺回传结果:成功时提供 countries,失败时可只提供 error") public static class ShopResult { + @Schema(description = "店铺名称,用于和任务内结果行匹配", example = "测试店铺A") private String shopName; + + @Schema(description = "按国家分组的结果行,key 为国家代码,例如 DE、UK、FR、IT、ES") private Map> countries; + + @Schema(description = "失败时的错误信息;非空则该店铺记为失败") private String error; + + @Schema(description = "是否成功;false 按失败处理,true 或 null 通常表示结合 countries 判定") private Boolean success; } @Data + @Schema(description = "单条 ASIN 跟价结果") public static class AsinResult { + @Schema(description = "ASIN", example = "B0ABCDE123") private String asin; + + @Schema(description = "当前店铺价格", example = "19.99") private String currentPrice; + + @Schema(description = "竞争对手价格", example = "18.50") private String competitorPrice; + + @Schema(description = "建议动作或跟价动作", example = "LOWER_PRICE") private String action; + + @Schema(description = "该行是否已处理完成") private Boolean done; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackTaskBatchRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackTaskBatchRequest.java new file mode 100644 index 0000000..c82a121 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackTaskBatchRequest.java @@ -0,0 +1,16 @@ +package com.nanri.aiimage.modules.pricetrack.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 PriceTrackTaskBatchRequest { + @NotEmpty(message = "taskIds不能为空") + @Schema(description = "待查询的任务主键列表,无效或非本模块 taskId 会出现在 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/pricetrack/model/vo/PriceTrackCandidateVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCandidateVo.java index df9da27..a6a13b0 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCandidateVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCandidateVo.java @@ -1,11 +1,16 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) +@Schema(description = "备选店铺列表单项") public class PriceTrackCandidateVo { + @Schema(description = "记录主键,删除备选店铺时作为路径参数", example = "10") private Long id; + + @Schema(description = "店铺名称", example = "测试店铺A") private String shopName; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCountryPreferenceVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCountryPreferenceVo.java index ebd9010..08f6457 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCountryPreferenceVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCountryPreferenceVo.java @@ -1,10 +1,16 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; + import java.util.List; @Data +@Schema(description = "用户五国处理偏好:按顺序返回国家代码列表,例如 DE、UK、FR、IT、ES") public class PriceTrackCountryPreferenceVo { + @Schema(description = "当前用户 ID", example = "1") private Long userId; + + @Schema(description = "已选国家代码列表;若用户未保存,则服务端返回默认顺序 DE、UK、FR、IT、ES") private List countryCodes; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java index 322031d..7acb2a7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java @@ -1,11 +1,16 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; + import java.util.List; -import java.util.Map; @Data +@Schema(description = "创建任务响应:包含任务 id 和各店铺的初始结果快照") public class PriceTrackCreateTaskVo { + @Schema(description = "新建任务主键 biz_file_task.id,前端推送队列时需要回传该值", example = "200") private Long taskId; - private List> items; + + @Schema(description = "各店铺一条初始结果快照,包含 resultId、taskId、店铺信息和初始任务状态") + private List items; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackDashboardVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackDashboardVo.java index 451d1e8..fb47093 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackDashboardVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackDashboardVo.java @@ -1,13 +1,22 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) +@Schema(description = "跟价模块统计看板,按当前用户维度汇总") public class PriceTrackDashboardVo { - private int candidateCount; - private int processedTaskCount; - private int successTaskCount; - private int failedTaskCount; + @Schema(description = "备选店铺数量") + private Long candidateCount; + + @Schema(description = "已结束任务数,状态为 SUCCESS 或 FAILED") + private Long processedTaskCount; + + @Schema(description = "成功结束的任务数") + private Long successTaskCount; + + @Schema(description = "失败结束的任务数") + private Long failedTaskCount; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackHistoryVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackHistoryVo.java index d56f5e5..8590dd3 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackHistoryVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackHistoryVo.java @@ -1,9 +1,13 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; + import java.util.List; @Data +@Schema(description = "跟价结果列表响应:items 中每项对应一个店铺结果行") public class PriceTrackHistoryVo { + @Schema(description = "结果列表,包含运行中和历史记录") private List items; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java index 37090bc..e039a29 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java @@ -1,20 +1,39 @@ package com.nanri.aiimage.modules.pricetrack.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 PriceTrackMatchShopsVo { - private List items; + @Schema(description = "逐店返回的匹配结果,顺序与请求 shopNames 对应") + private List items = new ArrayList<>(); @Data + @Schema(description = "单店匹配结果,同时也是创建任务时 items 的结构") public static class PriceTrackShopQueueItem { + @Schema(description = "店铺名称", example = "某某店铺") private String shopName; - private Long shopId; + + @Schema(description = "紫鸟店铺 ID,未命中时可能为空") + private Object shopId; + + @Schema(description = "平台,例如亚马逊", example = "亚马逊") private String platform; + + @Schema(description = "公司名称或主体标识") private String companyName; + + @Schema(description = "是否命中紫鸟索引;false 时不可用于创建任务") private Boolean matched; + + @Schema(description = "匹配状态码,例如 MATCHED、PENDING、CONFLICT、INDEX_STALE") private String matchStatus; + + @Schema(description = "人类可读说明,供前端展示") private String matchMessage; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackPendingDeleteVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackPendingDeleteVo.java new file mode 100644 index 0000000..892c29c --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackPendingDeleteVo.java @@ -0,0 +1,11 @@ +package com.nanri.aiimage.modules.pricetrack.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "按店铺名删除运行中结果的响应") +public class PriceTrackPendingDeleteVo { + @Schema(description = "是否实际删除到一条运行中的结果记录") + private boolean removed; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java index 9159012..4e91d6e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java @@ -1,23 +1,52 @@ package com.nanri.aiimage.modules.pricetrack.model.vo; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) +@Schema(description = "单店结果项:列表接口与任务详情共用,对应 biz_file_result 一行以及请求衍生字段") public class PriceTrackResultItemVo { + @Schema(description = "结果行主键 biz_file_result.id", example = "1001") private Long resultId; + + @Schema(description = "所属任务主键 biz_file_task.id", example = "200") private Long taskId; + + @Schema(description = "店铺名称,详情页会尽量恢复创建任务时的展示名") private String shopName; + + @Schema(description = "店铺 ID(紫鸟)") private Object shopId; + + @Schema(description = "平台") private String platform; + + @Schema(description = "公司名称") private String companyName; + + @Schema(description = "创建任务时是否已匹配") private Boolean matched; + + @Schema(description = "匹配状态码,含义同 PriceTrackShopQueueItem.matchStatus") private String matchStatus; + + @Schema(description = "匹配说明") private String matchMessage; + + @Schema(description = "所属任务当前状态:RUNNING、SUCCESS、FAILED") private String taskStatus; + + @Schema(description = "该店铺是否成功生成结果文件;null 或 false 可视为未完成或失败") private Boolean success; + + @Schema(description = "失败时的错误信息") private String error; + + @Schema(description = "生成的 xlsx 文件名") private String outputFilename; + + @Schema(description = "预签名下载 URL,列表可能带回,也可通过下载接口获取") private String downloadUrl; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskBatchVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskBatchVo.java new file mode 100644 index 0000000..5260fee --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskBatchVo.java @@ -0,0 +1,17 @@ +package com.nanri.aiimage.modules.pricetrack.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Schema(description = "批量任务查询响应:每个 taskId 返回一条详情;无效 id 放到 missingTaskIds") +public class PriceTrackTaskBatchVo { + @Schema(description = "存在且属于跟价模块的任务详情列表") + 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/pricetrack/model/vo/PriceTrackTaskDetailVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskDetailVo.java new file mode 100644 index 0000000..71a11d8 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskDetailVo.java @@ -0,0 +1,17 @@ +package com.nanri.aiimage.modules.pricetrack.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 PriceTrackTaskDetailVo { + @Schema(description = "任务级字段,例如状态、错误信息、时间等") + private PriceTrackTaskItemVo task = new PriceTrackTaskItemVo(); + + @Schema(description = "该任务下每个店铺对应一条结果记录") + private List items = new ArrayList<>(); +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskItemVo.java new file mode 100644 index 0000000..80c86c8 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackTaskItemVo.java @@ -0,0 +1,29 @@ +package com.nanri.aiimage.modules.pricetrack.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "跟价任务概要") +public class PriceTrackTaskItemVo { + @Schema(description = "任务主键", example = "200") + private Long id; + + @Schema(description = "任务编号") + private String taskNo; + + @Schema(description = "任务状态:RUNNING、SUCCESS、FAILED") + private String status; + + @Schema(description = "任务错误信息;部分成功或失败时可能有值") + private String errorMessage; + + @Schema(description = "创建时间") + private String createdAt; + + @Schema(description = "更新时间") + private String updatedAt; + + @Schema(description = "完成时间;未结束时为空") + private String finishedAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java new file mode 100644 index 0000000..9fc5029 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java @@ -0,0 +1,85 @@ +package com.nanri.aiimage.modules.pricetrack.service; + +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Service +@Slf4j +public class PriceTrackExcelAssemblyService { + + private static final String[] HEADER = {"ASIN", "当前店铺价格", "竞争对手价格", "建议动作", "是否完成"}; + + public void writeWorkbook(File outputXlsx, Map> countries) { + Map> safe = countries == null ? Map.of() : countries; + try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream fos = new FileOutputStream(outputXlsx)) { + for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) { + String sheetName = code.name(); + Sheet sheet = wb.createSheet(sheetName); + Row headerRow = sheet.createRow(0); + for (int i = 0; i < HEADER.length; i++) { + headerRow.createCell(i).setCellValue(HEADER[i]); + } + List rows = safe.getOrDefault(sheetName, List.of()); + int rowIdx = 1; + for (PriceTrackSubmitResultRequest.AsinResult item : rows) { + if (item == null) { + continue; + } + Row row = sheet.createRow(rowIdx++); + row.createCell(0).setCellValue(item.getAsin() == null ? "" : item.getAsin()); + row.createCell(1).setCellValue(item.getCurrentPrice() == null ? "" : item.getCurrentPrice()); + row.createCell(2).setCellValue(item.getCompetitorPrice() == null ? "" : item.getCompetitorPrice()); + row.createCell(3).setCellValue(item.getAction() == null ? "" : item.getAction()); + row.createCell(4).setCellValue(item.getDone() == null ? "" : String.valueOf(item.getDone())); + } + for (int i = 0; i < HEADER.length; i++) { + sheet.autoSizeColumn(i); + } + } + wb.write(fos); + } catch (Exception ex) { + log.warn("[price-track] write workbook failed: {}", ex.getMessage()); + throw new BusinessException("生成 Excel 失败: " + ex.getMessage()); + } + } + + public int countRows(Map> countries) { + if (countries == null || countries.isEmpty()) { + return 0; + } + int count = 0; + for (List rows : countries.values()) { + if (rows != null) { + count += rows.size(); + } + } + return count; + } + + public Map> normalizeCountriesMap( + Map> raw) { + if (raw == null || raw.isEmpty()) { + return new LinkedHashMap<>(); + } + Map> out = new LinkedHashMap<>(); + for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) { + List rows = raw.get(code.name()); + if (rows != null) { + out.put(code.name(), rows); + } + } + return out; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java index 730fca8..d9876b7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java @@ -14,7 +14,6 @@ import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackShopCandidate import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCandidateVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCountryPreferenceVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo; -import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackShopQueueItem; import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo; import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService; @@ -52,7 +51,9 @@ public class PriceTrackService { .orderByDesc(PriceTrackShopCandidateEntity::getId)); List list = new ArrayList<>(); for (PriceTrackShopCandidateEntity row : rows) { - if (row == null) continue; + if (row == null) { + continue; + } PriceTrackCandidateVo vo = new PriceTrackCandidateVo(); vo.setId(row.getId()); vo.setShopName(row.getShopName()); @@ -68,20 +69,22 @@ public class PriceTrackService { } String normalized = ziniaoShopSwitchService.normalizeShopName(request.getShopName()); if (normalized.isBlank()) { - throw new BusinessException("店铺名不能为空"); + throw new BusinessException("店铺名称不能为空"); } - // 店铺需在紫鸟索引中命中才能加入备选 + ZiniaoShopMatchResultVo indexHit = ziniaoShopSwitchService.findIndexedStoreByName(normalized, false); if (indexHit == null || !indexHit.isMatched()) { - String hint = (indexHit != null && indexHit.getMatchMessage() != null) - ? indexHit.getMatchMessage() : "店铺索引未命中,无法加入备选"; + String hint = indexHit != null && indexHit.getMatchMessage() != null + ? indexHit.getMatchMessage() + : "店铺未命中紫鸟索引,无法加入备选列表"; throw new BusinessException(hint); } if (ZiniaoShopIndexService.MATCH_STATUS_CONFLICT.equals(indexHit.getMatchStatus())) { throw new BusinessException(indexHit.getMatchMessage() != null - ? indexHit.getMatchMessage() : "存在多个同名店铺,请人工确认"); + ? indexHit.getMatchMessage() + : "存在多个同名店铺,请先人工确认"); } - // 查重 + PriceTrackShopCandidateEntity existing = candidateMapper.selectOne( new LambdaQueryWrapper() .eq(PriceTrackShopCandidateEntity::getUserId, request.getUserId()) @@ -93,11 +96,13 @@ public class PriceTrackService { vo.setShopName(existing.getShopName()); return vo; } + PriceTrackShopCandidateEntity entity = new PriceTrackShopCandidateEntity(); entity.setUserId(request.getUserId()); entity.setShopName(normalized); entity.setCreatedAt(LocalDateTime.now()); candidateMapper.insert(entity); + PriceTrackCandidateVo vo = new PriceTrackCandidateVo(); vo.setId(entity.getId()); vo.setShopName(entity.getShopName()); @@ -106,8 +111,12 @@ public class PriceTrackService { @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 不合法"); + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } + if (id == null || id <= 0) { + throw new BusinessException("id 不合法"); + } PriceTrackShopCandidateEntity row = candidateMapper.selectById(id); if (row == null || !userId.equals(row.getUserId())) { throw new BusinessException("记录不存在"); @@ -121,12 +130,15 @@ public class PriceTrackService { } LinkedHashSet ordered = new LinkedHashSet<>(); for (String raw : request.getShopNames()) { - String n = ziniaoShopSwitchService.normalizeShopName(raw); - if (!n.isBlank()) ordered.add(n); + String normalized = ziniaoShopSwitchService.normalizeShopName(raw); + if (!normalized.isBlank()) { + ordered.add(normalized); + } } if (ordered.isEmpty()) { - throw new BusinessException("shop_names 无有效店铺名"); + throw new BusinessException("shop_names 没有有效店铺名"); } + PriceTrackMatchShopsVo vo = new PriceTrackMatchShopsVo(); for (String shopName : ordered) { vo.getItems().add(matchOneShop(shopName)); @@ -135,7 +147,9 @@ public class PriceTrackService { } public PriceTrackCountryPreferenceVo getCountryPreference(Long userId) { - if (userId == null || userId <= 0) throw new BusinessException("user_id 不合法"); + if (userId == null || userId <= 0) { + throw new BusinessException("user_id 不合法"); + } PriceTrackCountryPrefEntity row = countryPrefMapper.selectById(userId); PriceTrackCountryPreferenceVo vo = new PriceTrackCountryPreferenceVo(); if (row == null || row.getCountryCodesJson() == null || row.getCountryCodesJson().isBlank()) { @@ -156,14 +170,17 @@ public class PriceTrackService { @Transactional public PriceTrackCountryPreferenceVo saveCountryPreference(PriceTrackCountryPreferenceSaveRequest request) { - if (request.getUserId() == null || request.getUserId() <= 0) throw new BusinessException("user_id 不合法"); + 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("保存偏好失败"); + throw new BusinessException("保存国家偏好失败"); } + PriceTrackCountryPrefEntity row = countryPrefMapper.selectById(request.getUserId()); if (row == null) { row = new PriceTrackCountryPrefEntity(); @@ -174,29 +191,30 @@ public class PriceTrackService { row.setCountryCodesJson(json); countryPrefMapper.updateById(row); } + PriceTrackCountryPreferenceVo vo = new PriceTrackCountryPreferenceVo(); vo.setUserId(request.getUserId()); vo.setCountryCodes(normalized); return vo; } - private PriceTrackShopQueueItem matchOneShop(String shopName) { - PriceTrackShopQueueItem item = new PriceTrackShopQueueItem(); + private PriceTrackMatchShopsVo.PriceTrackShopQueueItem matchOneShop(String shopName) { + PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem(); item.setShopName(shopName); try { - ZiniaoShopMatchResultVo m = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); - if (m == null) { + ZiniaoShopMatchResultVo match = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); + if (match == null) { item.setMatched(false); item.setMatchStatus("PENDING"); - item.setMatchMessage("匹配结果为空"); + item.setMatchMessage("未查询到匹配结果"); return item; } - item.setMatched(m.isMatched()); - item.setShopId(m.getShopId()); - item.setPlatform(m.getPlatform()); - item.setCompanyName(m.getCompanyName()); - item.setMatchStatus(m.getMatchStatus()); - item.setMatchMessage(m.getMatchMessage()); + item.setMatched(match.isMatched()); + item.setShopId(match.getShopId()); + item.setPlatform(match.getPlatform()); + item.setCompanyName(match.getCompanyName()); + item.setMatchStatus(match.getMatchStatus()); + item.setMatchMessage(match.getMatchMessage()); } catch (BusinessException ex) { item.setMatched(false); item.setMatchStatus("PENDING"); @@ -211,34 +229,54 @@ public class PriceTrackService { private static List sanitizeStoredCodes(List raw) { List parsed = parseValidCountryCodes(raw); - if (parsed.isEmpty()) return new ArrayList<>(DEFAULT_COUNTRY_PREFERENCE_ORDER); + 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 个国家"); + 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(); - if (!SUPPORTED_COUNTRIES.contains(u)) throw new BusinessException("非法国家代码: " + s); - if (!seen.add(u)) throw new BusinessException("country_codes 存在重复: " + u); - out.add(u); + for (String code : raw) { + if (code == null || code.isBlank()) { + throw new BusinessException("country_codes 不能包含空值"); + } + String normalized = code.trim().toUpperCase(); + if (!SUPPORTED_COUNTRIES.contains(normalized)) { + throw new BusinessException("非法国家代码: " + code); + } + if (!seen.add(normalized)) { + throw new BusinessException("country_codes 存在重复值: " + normalized); + } + out.add(normalized); + } + if (out.isEmpty()) { + throw new BusinessException("country_codes 至少选择 1 个国家"); } - if (out.isEmpty()) throw new BusinessException("country_codes 至少选择 1 个国家"); return out; } private static List parseValidCountryCodes(List raw) { - if (raw == null || raw.isEmpty()) return new ArrayList<>(); + 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(); - if (!SUPPORTED_COUNTRIES.contains(u)) continue; - if (seen.add(u)) out.add(u); + for (String code : raw) { + if (code == null || code.isBlank()) { + continue; + } + String normalized = code.trim().toUpperCase(); + if (!SUPPORTED_COUNTRIES.contains(normalized)) { + continue; + } + if (seen.add(normalized)) { + out.add(normalized); + } } return out; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java new file mode 100644 index 0000000..5116aea --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java @@ -0,0 +1,53 @@ +package com.nanri.aiimage.modules.pricetrack.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.Instant; + +@Service +@RequiredArgsConstructor +public class PriceTrackTaskCacheService { + + private static final long HEARTBEAT_TTL_HOURS = 24; + + private final StringRedisTemplate stringRedisTemplate; + + public void touchTaskHeartbeat(Long taskId) { + if (taskId == null || taskId <= 0) { + return; + } + stringRedisTemplate.opsForValue().set( + buildTaskHeartbeatKey(taskId), + String.valueOf(Instant.now().toEpochMilli()), + Duration.ofHours(HEARTBEAT_TTL_HOURS)); + } + + public long getTaskHeartbeatMillis(Long taskId) { + if (taskId == null || taskId <= 0) { + return 0L; + } + String raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId)); + if (raw == null || raw.isBlank()) { + return 0L; + } + try { + return Long.parseLong(raw); + } catch (NumberFormatException ignored) { + return 0L; + } + } + + public void deleteTaskCache(Long taskId) { + if (taskId == null || taskId <= 0) { + return; + } + stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId)); + } + + private String buildTaskHeartbeatKey(Long taskId) { + return "price-track:task:heartbeat:" + taskId; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java index a3a4e98..da04c7e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java @@ -1,6 +1,7 @@ package com.nanri.aiimage.modules.pricetrack.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.file.service.oss.OssStorageService; @@ -11,28 +12,28 @@ import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackShopCandidate import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCreateTaskVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackDashboardVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackHistoryVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackPendingDeleteVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackResultItemVo; -import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackShopQueueItem; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackTaskBatchVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackTaskDetailVo; +import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackTaskItemVo; import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; 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; @@ -42,7 +43,7 @@ import java.util.Objects; public class PriceTrackTaskService { private static final String MODULE_TYPE = "PRICE_TRACK"; - private static final String CONTENT_TYPE_ZIP = "application/zip"; + private static final String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; private final FileTaskMapper fileTaskMapper; private final FileResultMapper fileResultMapper; @@ -51,6 +52,8 @@ public class PriceTrackTaskService { private final OssStorageService ossStorageService; private final ObjectMapper objectMapper; private final SkipPriceAsinService skipPriceAsinService; + private final PriceTrackExcelAssemblyService excelAssemblyService; + private final PriceTrackTaskCacheService priceTrackTaskCacheService; public PriceTrackDashboardVo dashboard(Long userId) { if (userId == null || userId <= 0) throw new BusinessException("user_id 不合法"); @@ -129,6 +132,51 @@ public class PriceTrackTaskService { .eq(FileResultEntity::getTaskId, taskId) .eq(FileResultEntity::getModuleType, MODULE_TYPE)); fileTaskMapper.deleteById(taskId); + priceTrackTaskCacheService.deleteTaskCache(taskId); + } + + @Transactional + public PriceTrackPendingDeleteVo 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")); + + PriceTrackPendingDeleteVo vo = new PriceTrackPendingDeleteVo(); + vo.setRemoved(false); + for (FileResultEntity fr : candidates) { + if (fr.getTaskId() == null) continue; + FileTaskEntity task = fileTaskMapper.selectById(fr.getTaskId()); + if (task == null || !MODULE_TYPE.equals(task.getModuleType()) || !userId.equals(task.getUserId())) continue; + if (!"RUNNING".equals(task.getStatus())) continue; + fileResultMapper.deleteById(fr.getId()); + reconcileTaskAfterResultRemoval(fr.getTaskId()); + vo.setRemoved(true); + return vo; + } + return vo; + } + + public PriceTrackTaskBatchVo getTaskDetailsBatch(List taskIds) { + PriceTrackTaskBatchVo batch = new PriceTrackTaskBatchVo(); + 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; } @Transactional @@ -137,18 +185,18 @@ public class PriceTrackTaskService { if (request.getItems() == null || request.getItems().isEmpty()) throw new BusinessException("items 不能为空"); // 去重并校验匹配状态 - List uniqueItems = dedupeQueueItems(request.getItems()); + List uniqueItems = dedupeQueueItems(request.getItems()); if (uniqueItems.isEmpty()) throw new BusinessException("items 不能为空"); - for (PriceTrackShopQueueItem item : uniqueItems) { + for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : uniqueItems) { if (item == null || !Boolean.TRUE.equals(item.getMatched())) { String name = item == null ? "" : Objects.toString(item.getShopName(), ""); throw new BusinessException("存在未匹配店铺,无法创建任务: " + name); } } - // 收集店铺名,查询跳过ASIN + // 汇总店铺名并查询需要跳过的 ASIN List shopNames = uniqueItems.stream() - .map(PriceTrackShopQueueItem::getShopName) + .map(PriceTrackMatchShopsVo.PriceTrackShopQueueItem::getShopName) .filter(s -> s != null && !s.isBlank()) .distinct() .toList(); @@ -169,11 +217,12 @@ public class PriceTrackTaskService { task.setCreatedAt(LocalDateTime.now()); task.setUpdatedAt(LocalDateTime.now()); fileTaskMapper.insert(task); + priceTrackTaskCacheService.touchTaskHeartbeat(task.getId()); List snapshot = new ArrayList<>(); - for (PriceTrackShopQueueItem item : uniqueItems) { + for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : uniqueItems) { String norm = ziniaoShopSwitchService.normalizeShopName(item.getShopName()); - if (norm.isBlank()) throw new BusinessException("店铺名无效"); + if (norm.isBlank()) throw new BusinessException("店铺名称无效"); FileResultEntity fr = new FileResultEntity(); fr.setTaskId(task.getId()); fr.setModuleType(MODULE_TYPE); @@ -186,16 +235,13 @@ public class PriceTrackTaskService { snapshot.add(toSnapshotVo(fr, item, task.getStatus())); } - // 保存请求上下文(含skipASIN)用于Python后续查询 + // 保存请求上下文快照,供 Python 消费和前端轮询展示使用 try { Map ctx = new LinkedHashMap<>(); ctx.put("userId", request.getUserId()); ctx.put("statusMode", request.isStatusMode()); ctx.put("asinMode", request.isAsinMode()); ctx.put("countryCodes", request.getCountryCodes()); - ctx.put("minPrice", request.getMinPrice()); - ctx.put("maxPrice", request.getMaxPrice()); - ctx.put("priceDiffPercent", request.getPriceDiffPercent()); ctx.put("skipAsinsByShop", skipAsinsByShop); ctx.put("items", uniqueItems); task.setRequestJson(objectMapper.writeValueAsString(ctx)); @@ -205,8 +251,8 @@ public class PriceTrackTaskService { } fileTaskMapper.updateById(task); - // TODO: Python侧定时轮询 RUNNING 状态任务, pickup 后开始处理 - // Java侧通过 submitResult 接口接收Python回传结果 + // TODO: Python 侧轮询 RUNNING 任务,pickup 后开始处理 + // Java 侧通过 submitResult 接口接收 Python 回传结果 PriceTrackCreateTaskVo vo = new PriceTrackCreateTaskVo(); vo.setTaskId(task.getId()); @@ -229,6 +275,7 @@ public class PriceTrackTaskService { throw new BusinessException("任务已结束,拒绝重复提交"); } + priceTrackTaskCacheService.touchTaskHeartbeat(taskId); List resultRows = fileResultMapper.selectList( new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) @@ -242,38 +289,26 @@ public class PriceTrackTaskService { if (!key.isBlank()) payloadByShop.put(key, sr); } - int ok = 0, fail = 0; - List allErrors = new ArrayList<>(); - boolean allDone = true; - for (FileResultEntity fr : resultRows) { String shopKey = fr.getSourceFilename(); PriceTrackSubmitResultRequest.ShopResult payload = shopKey == null ? null : payloadByShop.get(shopKey); if (payload == null) { - // 未匹配到payload的店铺保持待处理 - allDone = false; + // 当前批次没有该店铺的 payload,保持待处理 continue; } if (payload.getError() != null && !payload.getError().isBlank()) { markResultFailed(fr, payload.getError()); - fail++; - allErrors.add(shopKey + ": " + payload.getError()); continue; } if (Boolean.FALSE.equals(payload.getSuccess())) { - markResultFailed(fr, "处理失败"); - fail++; - allErrors.add(shopKey + ": 处理失败"); + markResultFailed(fr, "店铺处理失败"); continue; } - // 成功 - fr.setSuccess(1); - fr.setErrorMessage(null); - fr.setResultFilename(shopKey + "-price-track.xlsx"); - fr.setResultFileSize(0L); - fr.setRowCount(countAsinResults(payload)); - fileResultMapper.updateById(fr); - ok++; + try { + assembleShopResult(fr, shopKey, payload); + } catch (Exception ex) { + markResultFailed(fr, ex.getMessage() == null ? "组装结果失败" : ex.getMessage()); + } } List latest = fileResultMapper.selectList( @@ -282,33 +317,57 @@ public class PriceTrackTaskService { .eq(FileResultEntity::getModuleType, MODULE_TYPE) .orderByAsc(FileResultEntity::getId)); - allDone = latest.stream().noneMatch(fr -> - fr.getSuccess() == null || fr.getSuccess() == 0); + updateTaskStatusFromLatestRows(task, latest); + } - task.setSuccessFileCount(ok); - task.setFailedFileCount(fail); - task.setUpdatedAt(LocalDateTime.now()); + @Transactional + public boolean tryFinalizeTask(Long taskId, boolean fromCompensation) { + if (taskId == null || taskId <= 0) return false; + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) return false; + if (!"RUNNING".equals(task.getStatus())) { + log.warn("[price-track] stale finalize skipped taskId={} status={} fromCompensation={}", + taskId, task.getStatus(), fromCompensation); + cleanupTaskCacheIfTerminal(taskId, task.getStatus()); + return false; + } - if (!allDone) { - task.setStatus("RUNNING"); - } else if (ok > 0 && fail == 0) { - task.setStatus("SUCCESS"); - task.setFinishedAt(LocalDateTime.now()); - } else if (ok > 0) { - task.setStatus("SUCCESS"); - task.setErrorMessage(String.join(";", allErrors)); - task.setFinishedAt(LocalDateTime.now()); - } else { + List latest = fileResultMapper.selectList( + new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + if (latest.isEmpty()) { task.setStatus("FAILED"); - task.setErrorMessage(String.join(";", allErrors)); + task.setErrorMessage("任务明细缺失,无法自动收尾"); + task.setUpdatedAt(LocalDateTime.now()); task.setFinishedAt(LocalDateTime.now()); + fileTaskMapper.updateById(task); + cleanupTaskCacheIfTerminal(taskId, task.getStatus()); + return true; } - try { - task.setResultJson(objectMapper.writeValueAsString(buildSnapshotFromDb(taskId, task.getStatus()))); - } catch (Exception ex) { - log.warn("[price-track] compact result json failed: {}", ex.getMessage()); + + boolean changed = false; + for (FileResultEntity fr : latest) { + boolean success = fr.getSuccess() != null && fr.getSuccess() == 1; + boolean failed = fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank(); + if (success || failed) continue; + markResultFailed(fr, "Python interrupted before this shop finished uploading results"); + changed = true; + log.warn("[price-track] stale finalize failed taskId={} shop={} fromCompensation={}", + taskId, fr.getSourceFilename(), fromCompensation); } - fileTaskMapper.updateById(task); + if (!changed) { + return false; + } + + List refreshed = fileResultMapper.selectList( + new LambdaQueryWrapper() + .eq(FileResultEntity::getTaskId, taskId) + .eq(FileResultEntity::getModuleType, MODULE_TYPE) + .orderByAsc(FileResultEntity::getId)); + updateTaskStatusFromLatestRows(task, refreshed); + return true; } public String resolveResultDownloadUrl(Long resultId, Long userId) { @@ -345,21 +404,10 @@ public class PriceTrackTaskService { .orderByAsc(FileResultEntity::getId)); if (latest.isEmpty()) { fileTaskMapper.deleteById(taskId); + cleanupTaskCacheIfTerminal(taskId, "DELETE_EMPTY"); return; } - int ok = 0, fail = 0; - for (FileResultEntity fr : latest) { - if (Boolean.TRUE.equals(fr.getSuccess())) ok++; - else if (fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank()) fail++; - } - task.setSuccessFileCount(ok); - task.setFailedFileCount(fail); - task.setUpdatedAt(LocalDateTime.now()); - boolean allDone = latest.stream().noneMatch(fr -> fr.getSuccess() == null || fr.getSuccess() == 0); - if (!allDone) return; - task.setStatus(ok > 0 ? "SUCCESS" : "FAILED"); - task.setFinishedAt(LocalDateTime.now()); - fileTaskMapper.updateById(task); + updateTaskStatusFromLatestRows(task, latest); } private void markResultFailed(FileResultEntity fr, String message) { @@ -369,12 +417,44 @@ public class PriceTrackTaskService { fr.setResultFileUrl(null); fr.setResultFileSize(0L); fr.setRowCount(0); + fr.setResultContentType(null); fileResultMapper.updateById(fr); } - private List dedupeQueueItems(List raw) { - Map byNorm = new LinkedHashMap<>(); - for (PriceTrackShopQueueItem item : raw) { + private void assembleShopResult(FileResultEntity result, + String shopKey, + PriceTrackSubmitResultRequest.ShopResult payload) { + Map> countries = + excelAssemblyService.normalizeCountriesMap(payload.getCountries()); + if (excelAssemblyService.countRows(countries) <= 0) { + throw new BusinessException("未收到可用结果数据"); + } + String displayName = payload.getShopName() != null && !payload.getShopName().isBlank() + ? payload.getShopName().trim() + : shopKey; + String stem = safeFileStem(displayName); + java.io.File workRoot = cn.hutool.core.io.FileUtil.mkdir( + cn.hutool.core.io.FileUtil.file(System.getProperty("java.io.tmpdir"), "price-track-result", String.valueOf(result.getTaskId()))); + java.io.File xlsx = cn.hutool.core.io.FileUtil.file(workRoot, stem + ".xlsx"); + try { + excelAssemblyService.writeWorkbook(xlsx, countries); + String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE); + result.setSuccess(1); + result.setErrorMessage(null); + result.setResultFilename(stem + ".xlsx"); + result.setResultFileUrl(objectKey); + result.setResultFileSize(xlsx.length()); + result.setResultContentType(CONTENT_TYPE_XLSX); + result.setRowCount(excelAssemblyService.countRows(countries)); + fileResultMapper.updateById(result); + } finally { + cn.hutool.core.io.FileUtil.del(xlsx); + } + } + + private List dedupeQueueItems(List raw) { + Map byNorm = new LinkedHashMap<>(); + for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : raw) { if (item == null) continue; String k = ziniaoShopSwitchService.normalizeShopName(item.getShopName()); if (k.isBlank()) continue; @@ -383,7 +463,7 @@ public class PriceTrackTaskService { return new ArrayList<>(byNorm.values()); } - private PriceTrackResultItemVo toSnapshotVo(FileResultEntity fr, PriceTrackShopQueueItem item, String taskStatus) { + private PriceTrackResultItemVo toSnapshotVo(FileResultEntity fr, PriceTrackMatchShopsVo.PriceTrackShopQueueItem item, String taskStatus) { PriceTrackResultItemVo vo = new PriceTrackResultItemVo(); vo.setResultId(fr.getId()); vo.setTaskId(fr.getTaskId()); @@ -416,9 +496,65 @@ public class PriceTrackTaskService { 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 PriceTrackTaskDetailVo buildTaskDetail(FileTaskEntity task) { + PriceTrackTaskDetailVo detail = new PriceTrackTaskDetailVo(); + 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 PriceTrackTaskItemVo toTaskItemVo(FileTaskEntity task) { + PriceTrackTaskItemVo vo = new PriceTrackTaskItemVo(); + 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 void mergeQueueFieldsFromRequest(PriceTrackResultItemVo vo, Long taskId) { + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || task.getRequestJson() == null || task.getRequestJson().isBlank()) return; + try { + Map payload = objectMapper.readValue(task.getRequestJson(), new TypeReference>() {}); + Object rawItems = payload.get("items"); + if (rawItems == null) return; + List items = objectMapper.convertValue( + rawItems, + new TypeReference>() {}); + String key = ziniaoShopSwitchService.normalizeShopName(vo.getShopName()); + for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : items) { + 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 List buildSnapshotFromDb(Long taskId, String taskStatus) { List rows = fileResultMapper.selectList( new LambdaQueryWrapper() @@ -430,17 +566,70 @@ public class PriceTrackTaskService { return list; } - private int countAsinResults(PriceTrackSubmitResultRequest.ShopResult payload) { - if (payload == null || payload.getCountries() == null) return 0; - return payload.getCountries().values().stream() - .filter(l -> l != null) - .mapToInt(List::size) - .sum(); - } - private static String safeFileStem(String shopName) { String s = shopName == null ? "shop" : shopName.trim(); if (s.isBlank()) s = "shop"; return s.replaceAll("[\\\\/:*?\"<>|]", "_"); } + + private static String fmt(LocalDateTime t) { + return t == null ? null : t.toString(); + } + + private void updateTaskStatusFromLatestRows(FileTaskEntity task, List latest) { + String oldStatus = task.getStatus(); + 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(task.getId(), task.getStatus()))); + } catch (Exception ex) { + log.warn("[price-track] compact result json failed: {}", ex.getMessage()); + } + fileTaskMapper.updateById(task); + log.warn("[price-track] status updated from latest rows taskId={} oldStatus={} newStatus={} ok={} fail={} allDone={} errorMessage={}", + task.getId(), oldStatus, task.getStatus(), ok, fail, allDone, task.getErrorMessage()); + cleanupTaskCacheIfTerminal(task.getId(), task.getStatus()); + } + + private void cleanupTaskCacheIfTerminal(Long taskId, String taskStatus) { + if (!"SUCCESS".equals(taskStatus) && !"FAILED".equals(taskStatus) && !"DELETE_EMPTY".equals(taskStatus)) { + return; + } + priceTrackTaskCacheService.deleteTaskCache(taskId); + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java index 136bde4..4d50b06 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java @@ -2,15 +2,15 @@ package com.nanri.aiimage.modules.shopkey.controller; import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest; -import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageUpdateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest; +import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageUpdateRequest; +import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo; +import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageGroupItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManagePageVo; -import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageGroupItemVo; -import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo; -import com.nanri.aiimage.modules.shopkey.service.ShopManageService; import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService; +import com.nanri.aiimage.modules.shopkey.service.ShopManageService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; @@ -34,7 +34,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor @RequestMapping("/api/admin/shop-manages") -@Tag(name = "店铺管理", description = "维护店铺信息,支持增删改查。") +@Tag(name = "店铺管理", description = "维护店铺信息,支持查询、新建、修改、删除") public class ShopManageController { @Value("${aiimage.security.internal-token:}") @@ -44,68 +44,89 @@ public class ShopManageController { private final ShopManageGroupService shopManageGroupService; @GetMapping - @Operation(summary = "分页查询店铺", description = "分页查询店铺列表。") + @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名称、创建人进行筛选") @ApiResponses({ - @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopManagePageVo.class))) + @io.swagger.v3.oas.annotations.responses.ApiResponse( + responseCode = "200", + description = "查询成功", + content = @Content(schema = @Schema(implementation = ShopManagePageVo.class))) }) public ApiResponse page( @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page, @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, - @Parameter(description = "分组ID") @RequestParam(required = false) Long groupId, - @Parameter(description = "店铺名") @RequestParam(required = false) String shopName) { - return ApiResponse.success(shopManageService.page(page, pageSize, groupId, shopName)); + @Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId, + @Parameter(description = "店铺名称") @RequestParam(required = false) String shopName, + @Parameter(description = "创建人用户 ID,普通管理员只传自己") @RequestParam(required = false) Long createdById) { + return ApiResponse.success(shopManageService.page(page, pageSize, groupId, shopName, createdById)); } @PostMapping - @Operation(summary = "新增店铺", description = "新增一条店铺记录。") - public ApiResponse create(@Valid @RequestBody ShopManageCreateRequest request) { - return ApiResponse.success("创建成功", shopManageService.create(request)); + @Operation(summary = "新增店铺", description = "创建店铺记录,并写入创建人") + public ApiResponse create( + @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, + @Valid @RequestBody ShopManageCreateRequest request) { + return ApiResponse.success("创建成功", + shopManageService.create(request, operatorId, Boolean.TRUE.equals(superAdmin))); } @PutMapping("/{id}") - @Operation(summary = "更新店铺", description = "按 ID 更新一条店铺记录。") + @Operation(summary = "更新店铺", description = "按 ID 更新店铺,普通管理员只能修改自己创建的数据") public ApiResponse update( - @Parameter(description = "主键ID", required = true) @PathVariable Long id, + @Parameter(description = "主键 ID", required = true) @PathVariable Long id, + @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageUpdateRequest request) { - return ApiResponse.success("更新成功", shopManageService.update(id, request)); + return ApiResponse.success("更新成功", + shopManageService.update(id, operatorId, Boolean.TRUE.equals(superAdmin), request)); } @DeleteMapping("/{id}") - @Operation(summary = "删除店铺", description = "按 ID 删除一条店铺记录。") - public ApiResponse delete(@Parameter(description = "主键ID", required = true) @PathVariable Long id) { - shopManageService.delete(id); + @Operation(summary = "删除店铺", description = "按 ID 删除店铺,普通管理员只能删除自己创建的数据") + public ApiResponse delete( + @Parameter(description = "主键 ID", required = true) @PathVariable Long id, + @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + shopManageService.delete(id, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); } @GetMapping("/groups") - @Operation(summary = "查询分组列表", description = "用于店铺管理下拉选择。") - public ApiResponse> listGroups() { - return ApiResponse.success(shopManageGroupService.list()); + @Operation(summary = "查询分组列表", description = "普通管理员只返回自己创建的分组,超级管理员返回全部") + public ApiResponse> listGroups( + @Parameter(description = "创建人用户 ID,普通管理员只传自己") @RequestParam(required = false) Long createdById) { + return ApiResponse.success(shopManageGroupService.list(createdById)); } @PostMapping("/groups") - @Operation(summary = "新增分组", description = "新增一条店铺分组。") + @Operation(summary = "新增分组", description = "创建分组并写入创建人") public ApiResponse createGroup(@Valid @RequestBody ShopManageGroupCreateRequest request) { return ApiResponse.success("创建成功", shopManageGroupService.create(request)); } @PutMapping("/groups/{id}") - @Operation(summary = "更新分组", description = "按 ID 更新分组名称。") + @Operation(summary = "更新分组", description = "普通管理员只能修改自己创建的分组") public ApiResponse updateGroup( - @Parameter(description = "主键ID", required = true) @PathVariable Long id, + @Parameter(description = "主键 ID", required = true) @PathVariable Long id, + @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageGroupUpdateRequest request) { - return ApiResponse.success("更新成功", shopManageGroupService.update(id, request)); + return ApiResponse.success("更新成功", + shopManageGroupService.update(id, operatorId, Boolean.TRUE.equals(superAdmin), request)); } @DeleteMapping("/groups/{id}") - @Operation(summary = "删除分组", description = "删除分组(分组下有店铺时不允许删除)。") - public ApiResponse deleteGroup(@Parameter(description = "主键ID", required = true) @PathVariable Long id) { - shopManageGroupService.delete(id); + @Operation(summary = "删除分组", description = "普通管理员只能删除自己创建的分组") + public ApiResponse deleteGroup( + @Parameter(description = "主键 ID", required = true) @PathVariable Long id, + @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + shopManageGroupService.delete(id, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); } @GetMapping("/credential") - @Operation(summary = "按店铺名获取明文凭据(内部)", description = "仅供 Python 自动化内部调用,需传 X-Internal-Token。") + @Operation(summary = "按店铺名获取明文凭据(内部)", description = "仅供 Python 自动化内部调用,需要传 X-Internal-Token") public ApiResponse getCredentialByShopName( @RequestParam("shopName") String shopName, @RequestHeader(value = "X-Internal-Token", required = false) String token) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java index fadfbe9..d840a87 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java @@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.shopkey.controller; import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCreateRequest; +import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCountryUpdateRequest; import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinPageVo; import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; @@ -14,6 +15,7 @@ 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; @@ -44,6 +46,15 @@ public class SkipPriceAsinController { return ApiResponse.success("保存成功", skipPriceAsinService.createOrUpdate(request)); } + @PutMapping("/{id}/countries/{country}") + @Operation(summary = "编辑指定国家的跳过跟价 ASIN") + public ApiResponse updateCountry( + @Parameter(description = "主键ID", required = true) @PathVariable Long id, + @Parameter(description = "国家编码", required = true) @PathVariable String country, + @Valid @RequestBody SkipPriceAsinCountryUpdateRequest request) { + return ApiResponse.success("保存成功", skipPriceAsinService.updateCountry(id, country, request.getAsin())); + } + @DeleteMapping("/{id}/countries/{country}") @Operation(summary = "删除指定国家的跳过跟价 ASIN") public ApiResponse deleteCountry( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageCreateRequest.java index b9148a0..607250c 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageCreateRequest.java @@ -1,5 +1,6 @@ package com.nanri.aiimage.modules.shopkey.model.dto; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotBlank; import lombok.Data; @@ -7,18 +8,27 @@ import lombok.Data; @Data public class ShopManageCreateRequest { + @Schema(description = "分组 ID", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull(message = "分组不能为空") private Long groupId; - @NotBlank(message = "店铺名不能为空") + @Schema(description = "店铺名称", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "店铺名称不能为空") private String shopName; - @NotBlank(message = "店铺商城名不能为空") + @Schema(description = "商城名称", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "商城名称不能为空") private String mallName; + @Schema(description = "登录账号", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "账号不能为空") private String account; + @Schema(description = "登录密码", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "密码不能为空") private String password; + + @Schema(description = "创建人用户 ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "创建人不能为空") + private Long createdById; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java index 705e1e1..62d2d5b 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java @@ -1,11 +1,18 @@ package com.nanri.aiimage.modules.shopkey.model.dto; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.Data; @Data public class ShopManageGroupCreateRequest { + @Schema(description = "分组名称", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "分组名称不能为空") private String groupName; + + @Schema(description = "创建人用户 ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "创建人不能为空") + private Long createdById; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java index 007b045..1469aca 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java @@ -1,11 +1,13 @@ package com.nanri.aiimage.modules.shopkey.model.dto; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data public class ShopManageGroupUpdateRequest { + @Schema(description = "分组名称", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "分组名称不能为空") private String groupName; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageUpdateRequest.java index 2f2fe5e..e31f957 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageUpdateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageUpdateRequest.java @@ -1,5 +1,6 @@ package com.nanri.aiimage.modules.shopkey.model.dto; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotBlank; import lombok.Data; @@ -7,18 +8,23 @@ import lombok.Data; @Data public class ShopManageUpdateRequest { + @Schema(description = "分组 ID", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull(message = "分组不能为空") private Long groupId; - @NotBlank(message = "店铺名不能为空") + @Schema(description = "店铺名称", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "店铺名称不能为空") private String shopName; - @NotBlank(message = "店铺商城名不能为空") + @Schema(description = "商城名称", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "商城名称不能为空") private String mallName; + @Schema(description = "登录账号", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "账号不能为空") private String account; + @Schema(description = "登录密码", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "密码不能为空") private String password; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCountryUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCountryUpdateRequest.java new file mode 100644 index 0000000..be37835 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCountryUpdateRequest.java @@ -0,0 +1,13 @@ +package com.nanri.aiimage.modules.shopkey.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +@Data +public class SkipPriceAsinCountryUpdateRequest { + + @Schema(description = "ASIN", requiredMode = Schema.RequiredMode.REQUIRED) + @NotBlank(message = "ASIN 不能为空") + private String asin; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageEntity.java index 502110c..918ff1d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageEntity.java @@ -17,6 +17,8 @@ public class ShopManageEntity { private Long groupId; private String groupName; private String shopName; + @TableField("created_by_id") + private Long createdById; @TableField("mall_name") private String mallName; private String account; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java index 3655103..623de76 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java @@ -1,6 +1,7 @@ package com.nanri.aiimage.modules.shopkey.model.entity; import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @@ -14,6 +15,8 @@ public class ShopManageGroupEntity { @TableId(type = IdType.AUTO) private Long id; private String groupName; + @TableField("created_by_id") + private Long createdById; private LocalDateTime createdAt; private LocalDateTime updatedAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java index 151ea57..95d2314 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java @@ -6,8 +6,8 @@ import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMapper; import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest; -import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity; import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity; +import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageGroupItemVo; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -23,7 +23,13 @@ public class ShopManageGroupService { private final ShopManageMapper shopManageMapper; public List list() { - return groupMapper.selectList(new LambdaQueryWrapper().orderByAsc(ShopManageGroupEntity::getId)) + return list(null); + } + + public List list(Long createdById) { + return groupMapper.selectList(new LambdaQueryWrapper() + .eq(createdById != null && createdById > 0, ShopManageGroupEntity::getCreatedById, createdById) + .orderByAsc(ShopManageGroupEntity::getId)) .stream() .map(this::toVo) .toList(); @@ -31,34 +37,45 @@ public class ShopManageGroupService { @Transactional public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request) { + Long createdById = normalizePositiveId(request.getCreatedById(), "创建人不能为空"); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, null); + ensureGroupNameUnique(groupName, null, createdById, false); ShopManageGroupEntity entity = new ShopManageGroupEntity(); entity.setGroupName(groupName); + entity.setCreatedById(createdById); groupMapper.insert(entity); return toVo(getById(entity.getId())); } @Transactional - public ShopManageGroupItemVo update(Long id, ShopManageGroupUpdateRequest request) { + public ShopManageGroupItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageGroupUpdateRequest request) { ShopManageGroupEntity entity = getById(id); + validateOwnership(entity, operatorId, superAdmin); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, id); + ensureGroupNameUnique(groupName, id, operatorId, superAdmin); entity.setGroupName(groupName); groupMapper.updateById(entity); return toVo(getById(id)); } @Transactional - public void delete(Long id) { + public void delete(Long id, Long operatorId, boolean superAdmin) { ShopManageGroupEntity entity = getById(id); - Long useCount = shopManageMapper.selectCount(new LambdaQueryWrapper().eq(ShopManageEntity::getGroupId, entity.getId())); + validateOwnership(entity, operatorId, superAdmin); + Long useCount = shopManageMapper.selectCount(new LambdaQueryWrapper() + .eq(ShopManageEntity::getGroupId, entity.getId())); if (useCount != null && useCount > 0) { throw new BusinessException("该分组下存在店铺,无法删除"); } groupMapper.deleteById(entity.getId()); } + public ShopManageGroupEntity getAccessibleById(Long id, Long operatorId, boolean superAdmin) { + ShopManageGroupEntity entity = getById(id); + validateOwnership(entity, operatorId, superAdmin); + return entity; + } + public ShopManageGroupEntity getById(Long id) { ShopManageGroupEntity entity = groupMapper.selectById(id); if (entity == null) { @@ -67,9 +84,12 @@ public class ShopManageGroupService { return entity; } - private void ensureGroupNameUnique(String groupName, Long excludeId) { + private void ensureGroupNameUnique(String groupName, Long excludeId, Long operatorId, boolean superAdmin) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(ShopManageGroupEntity::getGroupName, groupName); + if (!superAdmin) { + query.eq(ShopManageGroupEntity::getCreatedById, normalizePositiveId(operatorId, "操作人不能为空")); + } if (excludeId != null) { query.ne(ShopManageGroupEntity::getId, excludeId); } @@ -79,6 +99,16 @@ public class ShopManageGroupService { } } + private void validateOwnership(ShopManageGroupEntity entity, Long operatorId, boolean superAdmin) { + if (superAdmin) { + return; + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + if (entity.getCreatedById() == null || !entity.getCreatedById().equals(normalizedOperatorId)) { + throw new BusinessException("只能操作自己创建的分组数据"); + } + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty()) { @@ -87,6 +117,13 @@ public class ShopManageGroupService { return normalized; } + private Long normalizePositiveId(Long value, String message) { + if (value == null || value <= 0) { + throw new BusinessException(message); + } + return value; + } + private ShopManageGroupItemVo toVo(ShopManageGroupEntity entity) { ShopManageGroupItemVo vo = new ShopManageGroupItemVo(); vo.setId(entity.getId()); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java index 967a7ba..f6ab333 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java @@ -8,9 +8,9 @@ import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageUpdateRequest; import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity; import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity; +import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManagePageVo; -import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -28,16 +28,21 @@ public class ShopManageService { private final ShopCredentialCryptoService shopCredentialCryptoService; public ShopManagePageVo page(long page, long pageSize) { - return page(page, pageSize, null, null); + return page(page, pageSize, null, null, null); } public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName) { + return page(page, pageSize, groupId, shopName, null); + } + + public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long createdById) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = shopName == null ? "" : shopName.trim(); LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(groupId != null && groupId > 0, ShopManageEntity::getGroupId, groupId) + .eq(createdById != null && createdById > 0, ShopManageEntity::getCreatedById, createdById) .like(!safeShopName.isEmpty(), ShopManageEntity::getShopName, safeShopName) .orderByDesc(ShopManageEntity::getId); Long total = shopManageMapper.selectCount(query); @@ -62,16 +67,18 @@ public class ShopManageService { } @Transactional - public ShopManageItemVo create(ShopManageCreateRequest request) { - ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId()); - String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空"); - String mallName = normalizeRequired(request.getMallName(), "店铺商城名不能为空"); + public ShopManageItemVo create(ShopManageCreateRequest request, Long operatorId, boolean superAdmin) { + Long createdById = normalizePositiveId(request.getCreatedById(), "创建人不能为空"); + ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); + String shopName = normalizeRequired(request.getShopName(), "店铺名称不能为空"); + String mallName = normalizeRequired(request.getMallName(), "商城名称不能为空"); ensureShopNameUnique(shopName, null); ShopManageEntity entity = new ShopManageEntity(); entity.setGroupId(group.getId()); entity.setGroupName(group.getGroupName()); entity.setShopName(shopName); + entity.setCreatedById(createdById); entity.setMallName(mallName); entity.setAccount(normalizeRequired(request.getAccount(), "账号不能为空")); entity.setPassword(shopCredentialCryptoService.encrypt(normalizeRequired(request.getPassword(), "密码不能为空"))); @@ -81,11 +88,12 @@ public class ShopManageService { } @Transactional - public ShopManageItemVo update(Long id, ShopManageUpdateRequest request) { + public ShopManageItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageUpdateRequest request) { ShopManageEntity entity = getById(id); - ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId()); - String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空"); - String mallName = normalizeRequired(request.getMallName(), "店铺商城名不能为空"); + validateOwnership(entity, operatorId, superAdmin); + ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); + String shopName = normalizeRequired(request.getShopName(), "店铺名称不能为空"); + String mallName = normalizeRequired(request.getMallName(), "商城名称不能为空"); ensureShopNameUnique(shopName, id); entity.setGroupId(group.getId()); @@ -100,13 +108,14 @@ public class ShopManageService { } @Transactional - public void delete(Long id) { + public void delete(Long id, Long operatorId, boolean superAdmin) { ShopManageEntity entity = getById(id); + validateOwnership(entity, operatorId, superAdmin); shopManageMapper.deleteById(entity.getId()); } public ShopManageCredentialVo getCredentialByShopName(String shopName) { - String normalizedShopName = normalizeRequired(shopName, "店铺名不能为空"); + String normalizedShopName = normalizeRequired(shopName, "店铺名称不能为空"); ShopManageEntity entity = shopManageMapper.selectOne(new LambdaQueryWrapper() .eq(ShopManageEntity::getShopName, normalizedShopName) .last("limit 1")); @@ -137,6 +146,16 @@ public class ShopManageService { return entity; } + private void validateOwnership(ShopManageEntity entity, Long operatorId, boolean superAdmin) { + if (superAdmin) { + return; + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + if (entity.getCreatedById() == null || !entity.getCreatedById().equals(normalizedOperatorId)) { + throw new BusinessException("只能操作自己创建的店铺数据"); + } + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty()) { @@ -145,6 +164,13 @@ public class ShopManageService { return normalized; } + private Long normalizePositiveId(Long value, String message) { + if (value == null || value <= 0) { + throw new BusinessException(message); + } + return value; + } + private void ensureShopNameUnique(String shopName, Long excludeId) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(ShopManageEntity::getShopName, shopName); @@ -153,7 +179,7 @@ public class ShopManageService { } Long count = shopManageMapper.selectCount(query); if (count != null && count > 0) { - throw new BusinessException("店铺名已存在"); + throw new BusinessException("店铺名称已存在"); } } @@ -164,8 +190,8 @@ public class ShopManageService { LinkedHashMap map = new LinkedHashMap<>(); for (Long groupId : groupIds) { try { - ShopManageGroupEntity g = shopManageGroupService.getById(groupId); - map.put(groupId, g.getGroupName()); + ShopManageGroupEntity group = shopManageGroupService.getById(groupId); + map.put(groupId, group.getGroupName()); } catch (Exception ignored) { map.put(groupId, ""); } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java index 16c2438..8a95f2d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java @@ -105,6 +105,24 @@ public class SkipPriceAsinService { skipPriceAsinMapper.updateById(entity); } + @Transactional + public SkipPriceAsinItemVo updateCountry(Long id, String country, String asin) { + SkipPriceAsinEntity entity = getById(id); + String normalizedCountry = normalizeCountry(country); + String normalizedAsin = normalizeAsin(asin); + setCountryAsin(entity, normalizedCountry, normalizedAsin); + skipPriceAsinMapper.updateById(entity); + SkipPriceAsinEntity saved = getById(entity.getId()); + String groupName = ""; + try { + ShopManageGroupEntity group = shopManageGroupService.getById(saved.getGroupId()); + groupName = group.getGroupName(); + } catch (Exception ignored) { + groupName = ""; + } + return toItemVo(saved, groupName); + } + private SkipPriceAsinEntity getById(Long id) { SkipPriceAsinEntity entity = skipPriceAsinMapper.selectById(id); if (entity == null) { diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml index e92b5b7..066b61c 100644 --- a/backend-java/src/main/resources/application.yml +++ b/backend-java/src/main/resources/application.yml @@ -84,12 +84,14 @@ aiimage: finalize-check-cron: ${AIIMAGE_DELETE_BRAND_FINALIZE_CHECK_CRON:30 */2 * * * *} product-risk-stale-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_STALE_TIMEOUT_MINUTES:10} product-risk-initial-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_INITIAL_TIMEOUT_MINUTES:10} + price-track-stale-timeout-minutes: ${AIIMAGE_PRICE_TRACK_STALE_TIMEOUT_MINUTES:10} + price-track-initial-timeout-minutes: ${AIIMAGE_PRICE_TRACK_INITIAL_TIMEOUT_MINUTES:10} shop-match-stale-timeout-minutes: ${AIIMAGE_SHOP_MATCH_STALE_TIMEOUT_MINUTES:10} shop-match-initial-timeout-minutes: ${AIIMAGE_SHOP_MATCH_INITIAL_TIMEOUT_MINUTES:10} 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,PRODUCT_RISK_RESOLVE,SHOP_MATCH} + module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE,PRICE_TRACK,SHOP_MATCH} security: shop-credential-key: ${AIIMAGE_SHOP_CREDENTIAL_KEY:change-me-shop-credential-key} internal-token: ${AIIMAGE_INTERNAL_TOKEN:} diff --git a/backend-java/src/main/resources/db/V22__shop_manage_add_created_by_id.sql b/backend-java/src/main/resources/db/V22__shop_manage_add_created_by_id.sql new file mode 100644 index 0000000..e4aaa56 --- /dev/null +++ b/backend-java/src/main/resources/db/V22__shop_manage_add_created_by_id.sql @@ -0,0 +1,33 @@ +SET @db_name = DATABASE(); + +SET @created_by_id_col_exists := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage' + AND COLUMN_NAME = 'created_by_id' +); + +SET @sql_add_created_by_id_col := IF(@created_by_id_col_exists = 0, + 'ALTER TABLE biz_shop_manage ADD COLUMN created_by_id BIGINT NULL COMMENT ''创建人用户ID'' AFTER shop_name', + 'SELECT 1' +); +PREPARE stmt_add_created_by_id_col FROM @sql_add_created_by_id_col; +EXECUTE stmt_add_created_by_id_col; +DEALLOCATE PREPARE stmt_add_created_by_id_col; + +SET @created_by_id_idx_exists := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage' + AND INDEX_NAME = 'idx_created_by_id' +); + +SET @sql_add_created_by_id_idx := IF(@created_by_id_idx_exists = 0, + 'ALTER TABLE biz_shop_manage ADD INDEX idx_created_by_id (created_by_id)', + 'SELECT 1' +); +PREPARE stmt_add_created_by_id_idx FROM @sql_add_created_by_id_idx; +EXECUTE stmt_add_created_by_id_idx; +DEALLOCATE PREPARE stmt_add_created_by_id_idx; diff --git a/backend-java/src/main/resources/db/V23__shop_manage_group_add_created_by_id.sql b/backend-java/src/main/resources/db/V23__shop_manage_group_add_created_by_id.sql new file mode 100644 index 0000000..448656b --- /dev/null +++ b/backend-java/src/main/resources/db/V23__shop_manage_group_add_created_by_id.sql @@ -0,0 +1,33 @@ +SET @db_name = DATABASE(); + +SET @created_by_id_col_exists := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND COLUMN_NAME = 'created_by_id' +); + +SET @sql_add_created_by_id_col := IF(@created_by_id_col_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD COLUMN created_by_id BIGINT NULL COMMENT ''创建人用户ID'' AFTER group_name', + 'SELECT 1' +); +PREPARE stmt_add_created_by_id_col FROM @sql_add_created_by_id_col; +EXECUTE stmt_add_created_by_id_col; +DEALLOCATE PREPARE stmt_add_created_by_id_col; + +SET @created_by_id_idx_exists := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND INDEX_NAME = 'idx_created_by_id' +); + +SET @sql_add_created_by_id_idx := IF(@created_by_id_idx_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD INDEX idx_created_by_id (created_by_id)', + 'SELECT 1' +); +PREPARE stmt_add_created_by_id_idx FROM @sql_add_created_by_id_idx; +EXECUTE stmt_add_created_by_id_idx; +DEALLOCATE PREPARE stmt_add_created_by_id_idx; diff --git a/backend/__pycache__/config.cpython-312.pyc b/backend/__pycache__/config.cpython-312.pyc index 02e3b90..57fc226 100644 Binary files a/backend/__pycache__/config.cpython-312.pyc and b/backend/__pycache__/config.cpython-312.pyc differ diff --git a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc index df68f2e..268c8ae 100644 Binary files a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc and b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc differ diff --git a/backend/blueprints/admin_api.py b/backend/blueprints/admin_api.py index 2988c8e..c225db2 100644 --- a/backend/blueprints/admin_api.py +++ b/backend/blueprints/admin_api.py @@ -32,7 +32,7 @@ def _ensure_dedupe_total_data_access(): return _ensure_admin_menu_access('dedupe-total-data') role, current_row = get_current_admin_role() if not _can_access_dedupe_total_data(role, current_row): - return None, None, (jsonify({'success': False, 'error': '无权限访问数据去重总数据'}), 403) + return None, None, (jsonify({'success': False, 'error': '无权访问数据去重汇总数据'}), 403) return role, current_row, None from ali_oss import upload_file as oss_upload_file @@ -48,23 +48,23 @@ ADMIN_MENU_ACCESS_CONFIG = { 'dedupe-total-data': { 'column_key': 'admin_dedupe_total_data', 'route_path': 'dedupe-total-data', - 'error': '鏃犳潈闄愯闂暟鎹幓閲嶆€绘暟鎹?', + 'error': '无权访问数据去重汇总数据', }, 'shop-manage': { 'column_key': 'admin_shop_manage', 'route_path': 'shop-manage', - 'error': '鏃犳潈闄愯闂簵閾虹鐞嗘ā鍧?', + 'error': '无权访问店铺管理模块', }, 'skip-price-asin': { 'column_key': 'admin_skip_price_asin', 'route_path': 'skip-price-asin', - 'error': '鏃犳潈闄愯闂烦杩囪窡浠稟SIN 妯″潡', + 'error': '无权访问跳过跟价 ASIN 模块', }, } def _safe_version_key(version): - """将版本号转为安全的 OSS 对象名部分""" + """将版本号转换为安全的 OSS 对象名片段""" s = (version or '').strip() s = re.sub(r'[^\w.\-]', '_', s) return s or 'unknown' @@ -138,7 +138,7 @@ def _ensure_admin_menu_access(*menu_names): if role == 'super_admin': return role, current_row, None if role != 'admin' or not current_row: - return role, current_row, (jsonify({'success': False, 'error': '闇€瑕佺鐞嗗憳鏉冮檺'}), 403) + return role, current_row, (jsonify({'success': False, 'error': '需要管理员权限'}), 403) key_set, route_set = _get_current_admin_permission_sets() for menu_name in menu_names: config = ADMIN_MENU_ACCESS_CONFIG.get(menu_name) or {} @@ -148,7 +148,7 @@ def _ensure_admin_menu_access(*menu_names): return role, current_row, None fallback_menu = menu_names[0] if menu_names else '' fallback_config = ADMIN_MENU_ACCESS_CONFIG.get(fallback_menu) or {} - error_message = fallback_config.get('error') or '鏃犳潈闄愯闂綋鍓嶆ā鍧?' + error_message = fallback_config.get('error') or '无权访问当前模块' return role, current_row, (jsonify({'success': False, 'error': error_message}), 403) @@ -157,7 +157,7 @@ def _ensure_admin_menu_access(*menu_names): @admin_api.route('/users') @admin_required def list_users(): - """分页获取用户列表;支持用户名模糊搜索、指定管理员所属普通用户筛选""" + """分页获取用户列表,支持用户名模糊搜索和按管理员归属筛选普通用户""" role, current_row = get_current_admin_role() if not role: return jsonify({'success': False, 'error': '需要管理员权限'}), 403 @@ -998,7 +998,7 @@ def delete_dedupe_total_data(item_id): @admin_api.route('/shop-manages') @admin_required def list_shop_manages(): - _, _, denied = _ensure_admin_menu_access('shop-manage') + role, current_row, denied = _ensure_admin_menu_access('shop-manage') if denied: return denied page = max(1, int(request.args.get('page', 1))) @@ -1007,6 +1007,8 @@ def list_shop_manages(): shop_name = (request.args.get('shop_name') or '').strip() params = {'page': page, 'pageSize': page_size} + if role != 'super_admin' and current_row and current_row.get('id'): + params['createdById'] = current_row.get('id') if group_id_raw: try: group_id = int(group_id_raw) @@ -1051,7 +1053,7 @@ def list_shop_manages(): @admin_api.route('/shop-manage', methods=['POST']) @admin_required def create_shop_manage(): - _, _, denied = _ensure_admin_menu_access('shop-manage') + role, current_row, denied = _ensure_admin_menu_access('shop-manage') if denied: return denied data = request.get_json() or {} @@ -1061,10 +1063,15 @@ def create_shop_manage(): 'mallName': (data.get('mall_name') or '').strip(), 'account': (data.get('account') or '').strip(), 'password': (data.get('password') or '').strip(), + 'createdById': current_row.get('id') if current_row else None, } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/shop-manages', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: @@ -1090,7 +1097,7 @@ def create_shop_manage(): @admin_api.route('/shop-manage/', methods=['PUT']) @admin_required def update_shop_manage(item_id): - _, _, denied = _ensure_admin_menu_access('shop-manage') + role, current_row, denied = _ensure_admin_menu_access('shop-manage') if denied: return denied data = request.get_json() or {} @@ -1104,6 +1111,10 @@ def update_shop_manage(item_id): result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/shop-manages/{item_id}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: @@ -1128,12 +1139,16 @@ def update_shop_manage(item_id): @admin_api.route('/shop-manage/', methods=['DELETE']) @admin_required def delete_shop_manage(item_id): - _, _, denied = _ensure_admin_menu_access('shop-manage') + role, current_row, denied = _ensure_admin_menu_access('shop-manage') if denied: return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-manages/{item_id}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, ) if error_response is not None: return error_response, status @@ -1146,12 +1161,13 @@ def delete_shop_manage(item_id): @admin_api.route('/shop-manage-groups') @admin_required def list_shop_manage_groups(): - _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied result, error_response, status = _proxy_backend_java( 'GET', '/api/admin/shop-manages/groups', + params={'createdById': current_row.get('id')} if role != 'super_admin' and current_row and current_row.get('id') else None, ) if error_response is not None: return error_response, status @@ -1170,11 +1186,14 @@ def list_shop_manage_groups(): @admin_api.route('/shop-manage-group', methods=['POST']) @admin_required def create_shop_manage_group(): - _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + _, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied data = request.get_json() or {} - payload = {'groupName': (data.get('group_name') or '').strip()} + payload = { + 'groupName': (data.get('group_name') or '').strip(), + 'createdById': current_row.get('id') if current_row else None, + } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/shop-manages/groups', @@ -1198,7 +1217,7 @@ def create_shop_manage_group(): @admin_api.route('/shop-manage-group/', methods=['PUT']) @admin_required def update_shop_manage_group(item_id): - _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied data = request.get_json() or {} @@ -1206,6 +1225,10 @@ def update_shop_manage_group(item_id): result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/shop-manages/groups/{item_id}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: @@ -1302,7 +1325,7 @@ def create_skip_price_asin(): item = result.get('data') or {} return jsonify({ 'success': True, - 'msg': result.get('message') or '淇濆瓨鎴愬姛', + 'msg': result.get('message') or '保存成功', 'item': { 'id': item.get('id'), 'group_id': item.get('groupId'), @@ -1331,19 +1354,58 @@ def delete_skip_price_asin_country(item_id, country): ) if error_response is not None: return error_response, status - return jsonify({'success': True, 'msg': result.get('message') or '鍒犻櫎鎴愬姛'}) + return jsonify({'success': True, 'msg': result.get('message') or '删除成功'}) @admin_api.route('/shop-manage-group/', methods=['DELETE']) @admin_required def delete_shop_manage_group(item_id): - _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-manages/groups/{item_id}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, ) if error_response is not None: return error_response, status return jsonify({'success': True, 'msg': result.get('message') or '删除成功'}) + + +@admin_api.route('/skip-price-asin//country/', methods=['PUT']) +@admin_required +def update_skip_price_asin_country(item_id, country): + _, _, denied = _ensure_admin_menu_access('skip-price-asin') + if denied: + return denied + data = request.get_json() or {} + payload = {'asin': (data.get('asin') or '').strip()} + result, error_response, status = _proxy_backend_java( + 'PUT', + f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + json_data=payload, + ) + if error_response is not None: + return error_response, status + item = result.get('data') or {} + return jsonify({ + 'success': True, + 'msg': result.get('message') or '保存成功', + 'item': { + 'id': item.get('id'), + 'group_id': item.get('groupId'), + 'group_name': item.get('groupName') or '', + 'shop_name': item.get('shopName') or '', + 'asin_de': item.get('asinDe') or '', + 'asin_uk': item.get('asinUk') or '', + 'asin_fr': item.get('asinFr') or '', + 'asin_it': item.get('asinIt') or '', + 'asin_es': item.get('asinEs') or '', + 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], + 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], + }, + }) diff --git a/backend/config.py b/backend/config.py index 6692838..97a3eb7 100644 --- a/backend/config.py +++ b/backend/config.py @@ -23,8 +23,8 @@ bucket_path = "nanri-image/" file_url_pre = f"https://{bucket}.oss-cn-hangzhou.aliyuncs.com/" import os -# backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://127.0.0.1:18080').rstrip('/') -backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://8.136.19.173:18080').rstrip('/') +backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://127.0.0.1:18080').rstrip('/') +# backend_java_base_url = os.environ.get('BACKEND_JAVA_BASE_URL', 'http://8.136.19.173:18080').rstrip('/') os.environ['OSS_ACCESS_KEY_ID'] = accessKeyId os.environ['OSS_ACCESS_KEY_SECRET'] = accessKeySecret os.environ['SECRET_KEY'] = "ddffc7c1d02121d9554d7b080b2511b6" diff --git a/backend/web_source/admin.html b/backend/web_source/admin.html index d450729..1fc9406 100644 --- a/backend/web_source/admin.html +++ b/backend/web_source/admin.html @@ -1995,10 +1995,35 @@ if (!value) return '-'; return '
' + '' + value + '' + + '' + '' + '
'; } function bindSkipPriceAsinActions() { + document.querySelectorAll('[data-skip-price-asin-edit]').forEach(function(btn) { + btn.onclick = function() { + var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); + var countryCode = btn.dataset.country || ''; + var currentAsin = (btn.dataset.asin || '').replace(/"/g, '"'); + var nextAsin = prompt('请输入店铺“' + shopName + '”在 ' + countryCode + ' 的 ASIN', currentAsin); + if (nextAsin === null) return; + nextAsin = (nextAsin || '').trim(); + if (!nextAsin) { + alert('ASIN 不能为空'); + return; + } + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinEdit + '/country/' + countryCode, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ asin: nextAsin }) + }) + .then(function(r) { return r.json(); }) + .then(function(res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '保存失败'); + }); + }; + }); document.querySelectorAll('[data-skip-price-asin-delete]').forEach(function(btn) { btn.onclick = function() { var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); diff --git a/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue b/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue index 2cb4e75..3b4f9a8 100644 --- a/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue @@ -90,26 +90,6 @@
保存中…
- -
价格监控设置
-
-
- 最低价 - - EUR -
-
- 最高价 - - EUR -
-
- 价差比例 - - % -
-
-
@@ -257,6 +237,7 @@ import { getPriceTrackDashboard, getPriceTrackHistory, getPriceTrackResultDownloadUrl, + getPriceTrackTasksBatch, listPriceTrackCandidates, matchPriceTrackShops, putPriceTrackCountryPreference, @@ -264,6 +245,7 @@ import { type PriceTrackDashboardVo, type PriceTrackHistoryItem, type PriceTrackShopQueueItem, + type PriceTrackTaskDetailVo, } from '@/shared/api/java-modules' // ========== 类型定义 ========== @@ -293,11 +275,6 @@ const asinModeEnabled = ref(false) // 按指定ASIN文档(自定义) // 上传文件 const asinFiles = ref([]) // ASIN文档 -// 价格监控 -const minPrice = ref(undefined) -const maxPrice = ref(undefined) -const priceDiffPercent = ref(undefined) - // 是否有有效模式 const hasValidMode = computed(() => statusModeEnabled.value || asinModeEnabled.value) @@ -317,10 +294,113 @@ const dashboard = ref({ const historyItems = ref([]) const pollingTaskIds = ref([]) const taskDetails = ref>({}) -const taskSnapshots = ref>({}) +const taskSnapshots = ref>({}) const pollTimer = ref(null) const pollingInFlight = ref(false) +function uidForStorage() { + return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0' +} + +function sessionKey() { + return `price-track:tasks:${uidForStorage()}` +} + +function taskStatusStorageKey() { + return `price-track:task-status:${uidForStorage()}` +} + +function taskSnapshotsStorageKey() { + return `price-track:tasks-batch-snapshot:${uidForStorage()}` +} + +function matchedItemsStorageKey() { + return `price-track:matched-items:${uidForStorage()}` +} + +function setStorageJson(key: string, value: unknown, shouldRemove: boolean) { + if (typeof window === 'undefined') return + try { + if (shouldRemove) window.localStorage.removeItem(key) + else window.localStorage.setItem(key, JSON.stringify(value)) + } catch { + /* quota */ + } +} + +function loadPollingIdsFromStorage() { + try { + const raw = typeof window !== 'undefined' ? window.localStorage.getItem(sessionKey()) : null + if (!raw) { + pollingTaskIds.value = [] + return + } + const parsed = JSON.parse(raw) as unknown + pollingTaskIds.value = Array.isArray(parsed) ? parsed.filter((n): n is number => typeof n === 'number' && n > 0) : [] + } catch { + pollingTaskIds.value = [] + } +} + +function savePollingIds() { + setStorageJson(sessionKey(), pollingTaskIds.value, pollingTaskIds.value.length === 0) +} + +function loadTaskDetailsFromStorage() { + try { + const raw = typeof window !== 'undefined' ? window.localStorage.getItem(taskStatusStorageKey()) : null + if (!raw) return + const parsed = JSON.parse(raw) as Record + const out: Record = {} + for (const [k, v] of Object.entries(parsed)) { + const id = Number(k) + if (id > 0 && typeof v === 'string') out[id] = v + } + taskDetails.value = out + } catch { + /* ignore */ + } +} + +function saveTaskDetailsToStorage() { + setStorageJson(taskStatusStorageKey(), taskDetails.value, Object.keys(taskDetails.value).length === 0) +} + +function loadTaskSnapshotsFromStorage() { + try { + const raw = typeof window !== 'undefined' ? window.localStorage.getItem(taskSnapshotsStorageKey()) : null + if (!raw) return + const parsed = JSON.parse(raw) as Record + const out: Record = {} + for (const [k, v] of Object.entries(parsed)) { + const id = Number(k) + if (id > 0 && v && typeof v === 'object') out[id] = v as PriceTrackTaskDetailVo + } + taskSnapshots.value = out + } catch { + /* ignore */ + } +} + +function saveTaskSnapshotsToStorage() { + setStorageJson(taskSnapshotsStorageKey(), taskSnapshots.value, Object.keys(taskSnapshots.value).length === 0) +} + +function loadMatchedItemsFromStorage() { + try { + const raw = typeof window !== 'undefined' ? window.localStorage.getItem(matchedItemsStorageKey()) : null + if (!raw) return + const parsed = JSON.parse(raw) as unknown + if (Array.isArray(parsed)) matchedItems.value = parsed as PriceTrackShopQueueItem[] + } catch { + /* ignore */ + } +} + +function saveMatchedItemsToStorage() { + setStorageJson(matchedItemsStorageKey(), matchedItems.value, matchedItems.value.length === 0) +} + // ========== 文件上传 ========== async function selectAsinFile() { const api = getPywebviewApi() @@ -463,6 +543,15 @@ async function loadHistory() { } } +function syncPollingIdsWithHistory() { + for (const taskId of [...pollingTaskIds.value]) { + const any = historyItems.value.some((r) => r.taskId === taskId) + if (!any && !taskSnapshots.value[taskId]) { + removePollingTask(taskId) + } + } +} + function onSelectionChange(rows: PriceTrackCandidateVo[]) { selectedCandidates.value = rows || [] } @@ -491,6 +580,7 @@ async function removeCandidate(row: PriceTrackCandidateVo) { await deletePriceTrackCandidate(row.id) await loadCandidates() matchedItems.value = [] + saveMatchedItemsToStorage() ElMessage.success('已删除') } catch (e) { ElMessage.error(e instanceof Error ? e.message : '删除失败') @@ -519,6 +609,7 @@ async function runMatch() { const res = await matchPriceTrackShops(names) const batch = res.items || [] matchedItems.value = [...matchedItems.value, ...batch.filter((n) => !matchedItems.value.some((e) => e.shopName === n.shopName))] + saveMatchedItemsToStorage() ElMessage.success(`匹配 ${batch.length} 个店铺`) } catch (e) { ElMessage.error(e instanceof Error ? e.message : '匹配失败') @@ -549,11 +640,32 @@ function removeMatchedRowsLocally(rows: Array<{ shopName?: string; shopId?: numb if (!rows.length) return const keys = new Set(rows.map((row) => rowKeyForMatch(row))) matchedItems.value = matchedItems.value.filter((row) => !keys.has(rowKeyForMatch(row))) + saveMatchedItemsToStorage() } async function removeMatchedRow(row: PriceTrackShopQueueItem) { - removeMatchedRowsLocally([row]) - ElMessage.success('已从匹配结果中移除') + const key = rowKeyForMatch(row) + const backup = [...matchedItems.value] + matchedItems.value = matchedItems.value.filter((r) => rowKeyForMatch(r) !== key) + saveMatchedItemsToStorage() + const name = (row.shopName || '').trim() + if (!name) { + ElMessage.success('已从匹配结果中移除') + return + } + try { + const res = await deletePendingPriceTrackShopResult(name) + if (res?.removed) { + await loadHistory() + await loadDashboard() + syncPollingIdsWithHistory() + } + ElMessage.success('已从匹配结果中移除') + } catch (e) { + matchedItems.value = backup + saveMatchedItemsToStorage() + ElMessage.error(e instanceof Error ? e.message : '同步后端失败') + } } async function pushToPythonQueue() { @@ -582,11 +694,21 @@ async function pushToPythonQueue() { items: matchedRows as unknown as Record[], asinFiles: asinFiles.value, countryCodes: [...orderedCountryCodes.value], - minPrice: minPrice.value, - maxPrice: maxPrice.value, - priceDiffPercent: priceDiffPercent.value, } const taskVo = await createPriceTrackTask(taskReq) + taskSnapshots.value = { + ...taskSnapshots.value, + [taskVo.taskId]: { + task: { id: taskVo.taskId, status: 'RUNNING' }, + items: taskVo.items, + }, + } + taskDetails.value = { + ...taskDetails.value, + [taskVo.taskId]: 'RUNNING', + } + saveTaskSnapshotsToStorage() + saveTaskDetailsToStorage() // 2. 推送 taskId 给 Python,Python 会从 Java 拉取完整任务上下文 const queuePayload = { @@ -605,6 +727,7 @@ async function pushToPythonQueue() { if (pushResult?.success) { queuePushResult.value = `任务 ${taskVo.taskId} 已入队,等待执行完成...` addPollingTask(taskVo.taskId) + scheduleNextPoll(true) ElMessage.success('已推送到 Python 队列') } else { queuePushResult.value = `推送失败:${pushResult?.error || '未知错误'}` @@ -627,24 +750,37 @@ async function refreshTaskBatch() { const ids = pollingTaskIds.value.filter((id) => id > 0) if (!ids.length) return try { - await loadHistory() - // 检查是否有任务结束,停止轮询 - const terminalIds = ids.filter((id) => isTaskTerminal(id)) - for (const id of terminalIds) { - removePollingTask(id) + const batch = await getPriceTrackTasksBatch(ids) + let changed = false + const nextSnapshots = { ...taskSnapshots.value } + for (const missingId of batch.missingTaskIds || []) { + removePollingTask(missingId) + delete nextSnapshots[missingId] } + for (const detail of batch.items || []) { + const taskId = detail.task?.id + const status = detail.task?.status + if (typeof taskId !== 'number' || taskId <= 0) continue + nextSnapshots[taskId] = detail + if (status) { + taskDetails.value[taskId] = status + if (status === 'SUCCESS' || status === 'FAILED') { + removePollingTask(taskId) + changed = true + } + } + } + taskSnapshots.value = nextSnapshots + saveTaskSnapshotsToStorage() + saveTaskDetailsToStorage() + await loadHistory() + syncPollingIdsWithHistory() + if (changed) await loadDashboard() } catch { /* polling noise */ } } -function isTaskTerminal(taskId: number) { - const rows = historyItems.value.filter((r) => r.taskId === taskId) - if (!rows.length) return false - // 全部行都有终态才停止 - return rows.every((r) => r.taskStatus === 'SUCCESS' || r.taskStatus === 'FAILED') -} - function scheduleNextPoll(immediate = false) { if (pollTimer.value) { if (!immediate) return @@ -670,17 +806,33 @@ function stopPolling() { function addPollingTask(taskId: number) { if (!pollingTaskIds.value.includes(taskId)) { pollingTaskIds.value = [...pollingTaskIds.value, taskId] + savePollingIds() } } function removePollingTask(taskId: number) { pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId) + savePollingIds() delete taskDetails.value[taskId] + saveTaskDetailsToStorage() + if (taskSnapshots.value[taskId]) { + const next = { ...taskSnapshots.value } + delete next[taskId] + taskSnapshots.value = next + saveTaskSnapshotsToStorage() + } } -const currentSectionItems = computed(() => - historyItems.value.filter((row) => row.taskId && pollingTaskIds.value.includes(row.taskId) && !isTaskTerminalById(row.taskId)) -) +const currentSectionItems = computed(() => { + const out = historyItems.value.filter((row) => row.taskId && pollingTaskIds.value.includes(row.taskId) && !isTaskTerminalById(row.taskId)) + const existingTaskIds = new Set(out.map((row) => row.taskId).filter((id): id is number => typeof id === 'number')) + for (const taskId of pollingTaskIds.value) { + if (existingTaskIds.has(taskId)) continue + const first = taskSnapshots.value[taskId]?.items?.[0] + if (first) out.push(first) + } + return out +}) const historySectionItems = computed(() => historyItems.value.filter((row) => !row.taskId || !pollingTaskIds.value.includes(row.taskId) || isTaskTerminalById(row.taskId)) @@ -690,7 +842,7 @@ const hasVisibleList = computed(() => currentSectionItems.value.length > 0 || hi function taskStatusOf(taskId?: number) { if (!taskId) return '' - return taskDetails.value[taskId] || '' + return taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status || '' } function isTaskTerminalById(taskId?: number) { @@ -729,7 +881,7 @@ function canDownload(item: PriceTrackHistoryItem) { async function downloadResult(item: PriceTrackHistoryItem) { if (!item.resultId) return const api = getPywebviewApi() - const filename = item.outputFilename || `${item.shopName || 'result'}.zip` + const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx` if (!api?.save_file_from_url_new) { ElMessage.error('当前客户端未提供 save_file_from_url_new,无法下载文件') return @@ -747,10 +899,14 @@ async function deleteTaskRecord(item: PriceTrackHistoryItem) { try { if (item.resultId != null) { await deletePriceTrackHistory(item.resultId) - if (item.taskId != null) removePollingTask(item.taskId) + } else if (item.taskId != null) { + await deletePriceTrackTask(item.taskId) } + if (item.taskId != null) removePollingTask(item.taskId) + removeMatchedRowsLocally([item]) await loadHistory() await loadDashboard() + syncPollingIdsWithHistory() ElMessage.success('已删除') } catch (e) { ElMessage.error(e instanceof Error ? e.message : '删除失败') @@ -759,6 +915,10 @@ async function deleteTaskRecord(item: PriceTrackHistoryItem) { // ========== 生命周期 ========== onMounted(() => { + loadPollingIdsFromStorage() + loadTaskDetailsFromStorage() + loadTaskSnapshotsFromStorage() + loadMatchedItemsFromStorage() loadCandidates().catch(() => undefined) loadCountryPreference().catch(() => undefined) loadHistory().catch(() => undefined) @@ -1085,49 +1245,12 @@ onUnmounted(() => { color: #ccc; } -.price-filter-zone { - border: 1px dashed #3a3a3a; - border-radius: 10px; - padding: 14px; - background: #252525; - margin-bottom: 16px; - display: flex; - flex-direction: column; - gap: 10px; -} -.price-input-row { - display: flex; - align-items: center; - gap: 10px; -} -.price-label { - font-size: 12px; - color: #aaa; - width: 60px; - flex-shrink: 0; -} -.price-input { - flex: 1; -} -.price-unit { - font-size: 12px; - color: #888; - width: 30px; - flex-shrink: 0; -} -.price-input-row :deep(.el-input__wrapper) { - background-color: #2a2a2a; - box-shadow: 0 0 0 1px #3a3a3a inset; -} -.price-input-row :deep(.el-input__inner) { - color: #ccc; -} .empty-candidates { color: #666; diff --git a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue index 9df24a1..ec6f4bb 100644 --- a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue @@ -215,6 +215,7 @@ async function loadCandidates() { candidates.value = await listShopMatchCandidat async function loadDashboard() { dashboard.value = await getShopMatchDashboard() } async function loadHistory() { const data = await getShopMatchHistory(); historyItems.value = data.items || [] } async function loadCountryPreference() { try { const data = await getShopMatchCountryPreference(); if (countryPrefUserTouched.value) return; const codes = (data.country_codes || []).filter((item) => COUNTRY_OPTIONS.some((option) => option.code === item)); if (codes.length) orderedCountryCodes.value = codes } catch {} } +async function refreshTaskViewsBestEffort() { await Promise.allSettled([loadHistory(), loadDashboard()]) } function scheduleSaveCountryPreference() { if (countryPrefSaveTimer) clearTimeout(countryPrefSaveTimer); countryPrefSaveTimer = setTimeout(() => { countryPrefSaveTimer = null; void saveCountryPreference() }, 450) } async function saveCountryPreference() { if (!orderedCountryCodes.value.length) return; countryPrefSaving.value = true; try { await putShopMatchCountryPreference(orderedCountryCodes.value) } catch (error) { ElMessage.error(error instanceof Error ? error.message : '保存国家配置失败') } finally { countryPrefSaving.value = false } } function onSelectionChange(rows: ShopMatchCandidateVo[]) { selectedCandidates.value = rows } @@ -252,7 +253,7 @@ function getPollIntervalMs() { return document.visibilityState === 'visible' ? 4 function scheduleNextPoll(immediate = false) { if (pollTimer.value) { if (!immediate) return; window.clearTimeout(pollTimer.value); pollTimer.value = null } const run = async () => { pollTimer.value = null; if (pollingInFlight.value || !pollingTaskIds.value.length) { if (pollingTaskIds.value.length) scheduleNextPoll(); return } pollingInFlight.value = true; try { const { settledTaskIds } = await refreshTaskBatch(); if (settledTaskIds.length) await Promise.allSettled([loadHistory(), loadDashboard()]) } finally { pollingInFlight.value = false } if (pollingTaskIds.value.length) pollTimer.value = window.setTimeout(run, getPollIntervalMs()) }; if (immediate) void run(); else pollTimer.value = window.setTimeout(run, getPollIntervalMs()) } function ensurePolling(immediate = false) { scheduleNextPoll(immediate) } function stopPolling() { if (pollTimer.value) { window.clearTimeout(pollTimer.value); pollTimer.value = null } } -async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); if ((batch.missingTaskIds || []).includes(taskId)) { removeTaskLocally(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return 'FAILED' } const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } } +async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); if ((batch.missingTaskIds || []).includes(taskId)) { removeTaskLocally(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return 'FAILED' } const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } } function resolvedTaskStatus(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); if (!taskId) return item.taskStatus || ''; return taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status || item.taskStatus || '' } function taskSnapshotOf(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); return taskId ? taskSnapshots.value[taskId] : undefined } function currentTaskStageText(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (!stages.length) return ''; const total = stages.length; const activeIndex = typeof task?.activeStageIndex === 'number' ? task.activeStageIndex : undefined; const currentIndex = typeof task?.currentStageIndex === 'number' ? task.currentStageIndex : undefined; if (typeof activeIndex === 'number') return `执行进度: 第 ${activeIndex + 1}/${total} 次执行中`; if (typeof currentIndex === 'number') return `执行进度: 等待第 ${currentIndex + 1}/${total} 次`; return `执行进度: 共 ${total} 次`} diff --git a/frontend-vue/src/pages/brand/components/listingFilters.ts b/frontend-vue/src/pages/brand/components/listingFilters.ts index 34e4f84..5bfff80 100644 --- a/frontend-vue/src/pages/brand/components/listingFilters.ts +++ b/frontend-vue/src/pages/brand/components/listingFilters.ts @@ -2,6 +2,7 @@ export const LISTING_FILTER_OPTIONS = [ { value: 'SearchSuppressed', label: '在搜索结果中禁止显示' }, { value: 'ApprovalRequired', label: '需要批准' }, { value: 'Active', label: '在售' }, + { value: 'DetailPageRemoved', label: '详情页面已删除' }, ] as const export type ListingFilterValue = (typeof LISTING_FILTER_OPTIONS)[number]['value'] diff --git a/frontend-vue/src/shared/api/java-modules.ts b/frontend-vue/src/shared/api/java-modules.ts index 24973cf..9d1bc8a 100644 --- a/frontend-vue/src/shared/api/java-modules.ts +++ b/frontend-vue/src/shared/api/java-modules.ts @@ -972,9 +972,38 @@ export interface PriceTrackHistoryVo { export interface PriceTrackCreateTaskVo { taskId: number; - items: PriceTrackShopQueueItem[]; + items: PriceTrackHistoryItem[]; } +export interface PriceTrackTaskSummary { + id?: number; + taskNo?: string; + status?: string; + errorMessage?: string; + createdAt?: string; + updatedAt?: string; + finishedAt?: string; +} + +export interface PriceTrackTaskDetailVo { + task?: PriceTrackTaskSummary; + items?: PriceTrackHistoryItem[]; +} + +export interface PriceTrackTaskBatchVo { + items: PriceTrackTaskDetailVo[]; + missingTaskIds?: number[]; +} + +export interface PriceTrackPendingDeleteVo { + removed: boolean; +} + +export type PriceTrackCreateTaskPayload = Omit< + PriceTrackCreateTaskRequest, + "userId" +>; + export function listPriceTrackCandidates() { return unwrapJavaResponse( get>( @@ -985,9 +1014,9 @@ export function listPriceTrackCandidates() { export function addPriceTrackCandidate(shopName: string) { return unwrapJavaResponse( - post, { user_id: number; shopName: string }>( + post, { userId: number; shopName: string }>( `${JAVA_API_PREFIX}/price-track/candidates`, - { user_id: getCurrentUserId(), shopName }, + { userId: getCurrentUserId(), shopName }, ), ); } @@ -1010,18 +1039,18 @@ export function getPriceTrackCountryPreference() { export function putPriceTrackCountryPreference(countryCodes: string[]) { return unwrapJavaResponse( - put, { user_id: number; countryCodes: string[] }>( + put, { userId: number; countryCodes: string[] }>( `${JAVA_API_PREFIX}/price-track/country-preference`, - { user_id: getCurrentUserId(), countryCodes }, + { userId: getCurrentUserId(), countryCodes }, ), ); } export function matchPriceTrackShops(shopNames: string[]) { return unwrapJavaResponse( - post, { user_id: number; shopNames: string[] }>( + post, { userId: number; shopNames: string[] }>( `${JAVA_API_PREFIX}/price-track/match-shops`, - { user_id: getCurrentUserId(), shopNames }, + { userId: getCurrentUserId(), shopNames }, ), ); } @@ -1057,16 +1086,15 @@ export interface PriceTrackCreateTaskRequest { items: PriceTrackShopQueueItem[]; asinFiles: string[]; countryCodes: string[]; - minPrice?: number; - maxPrice?: number; - priceDiffPercent?: number; } -export function createPriceTrackTask(request: PriceTrackCreateTaskRequest) { +export function createPriceTrackTask( + request: PriceTrackCreateTaskPayload | PriceTrackCreateTaskRequest, +) { return unwrapJavaResponse( post, PriceTrackCreateTaskRequest>( `${JAVA_API_PREFIX}/price-track/tasks`, - { ...request, user_id: getCurrentUserId() }, + { ...request, userId: getCurrentUserId() }, ), ); } @@ -1079,13 +1107,22 @@ export function deletePriceTrackTask(taskId: number) { ); } +export function getPriceTrackTasksBatch(taskIds: number[]) { + return unwrapJavaResponse( + post, { taskIds: number[] }>( + `${JAVA_API_PREFIX}/price-track/tasks/batch`, + { taskIds }, + ), + ); +} + export function getPriceTrackResultDownloadUrl(resultId: number) { return getJavaDownloadUrl(`/price-track/results/${resultId}/download`); } export function deletePendingPriceTrackShopResult(shopName: string) { return unwrapJavaResponse( - del>( + del>( `${JAVA_API_PREFIX}/price-track/pending-shop-result?user_id=${encodeURIComponent(String(getCurrentUserId()))}&shop_name=${encodeURIComponent(shopName)}`, ), ); diff --git a/frontend-vue/src/shared/bridges/pywebview.ts b/frontend-vue/src/shared/bridges/pywebview.ts index 4bc2ffe..d642612 100644 --- a/frontend-vue/src/shared/bridges/pywebview.ts +++ b/frontend-vue/src/shared/bridges/pywebview.ts @@ -11,6 +11,15 @@ export interface PywebviewApi { minimize?: () => Promise; maximize?: () => Promise; toggle_maximize?: () => Promise; + select_files?: (options?: { + filters?: Array<{ + name?: string; + extensions?: string; + }>; + multiple?: boolean; + }) => Promise<{ + paths?: string[]; + } | null>; save_image?: ( urlOrData: string, filename?: string, diff --git a/new_web_source/convert.html b/new_web_source/convert.html new file mode 100644 index 0000000..dd3590c --- /dev/null +++ b/new_web_source/convert.html @@ -0,0 +1,16 @@ + + + + + + 格式转换 - 数富AI + + + + + + + +
+ + diff --git a/new_web_source/dedupe.html b/new_web_source/dedupe.html new file mode 100644 index 0000000..419ddc9 --- /dev/null +++ b/new_web_source/dedupe.html @@ -0,0 +1,16 @@ + + + + + + 数据去重 - 数富AI + + + + + + + +
+ + diff --git a/new_web_source/delete-brand.html b/new_web_source/delete-brand.html new file mode 100644 index 0000000..a9f1ac1 --- /dev/null +++ b/new_web_source/delete-brand.html @@ -0,0 +1,16 @@ + + + + + + 删除品牌 - 数富AI + + + + + + + +
+ + diff --git a/new_web_source/price-track.html b/new_web_source/price-track.html new file mode 100644 index 0000000..6a65d34 --- /dev/null +++ b/new_web_source/price-track.html @@ -0,0 +1,16 @@ + + + + + + 跟价 - 数富AI + + + + + + + +
+ + diff --git a/new_web_source/product-risk.html b/new_web_source/product-risk.html new file mode 100644 index 0000000..05698af --- /dev/null +++ b/new_web_source/product-risk.html @@ -0,0 +1,18 @@ + + + + + + 商品风险解决 - 数富AI + + + + + + + + + +
+ + diff --git a/new_web_source/shop-match.html b/new_web_source/shop-match.html new file mode 100644 index 0000000..a085585 --- /dev/null +++ b/new_web_source/shop-match.html @@ -0,0 +1,18 @@ + + + + + + 匹配店铺 - 数富AI + + + + + + + + + +
+ + diff --git a/new_web_source/split.html b/new_web_source/split.html new file mode 100644 index 0000000..6e0fdd4 --- /dev/null +++ b/new_web_source/split.html @@ -0,0 +1,16 @@ + + + + + + 数据拆分 - 数富AI + + + + + + + +
+ +