diff --git a/app/assets/convert.js b/app/assets/convert.js index 5785fc1..94e0332 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-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"); +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-D4gpiFjY.js";import{e as Y}from"./brand-CXHemZwJ.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 3574d23..2f4ccf9 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-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"); +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-D4gpiFjY.js";import{e as se}from"./brand-CXHemZwJ.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 cebfc65..4aae9ce 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-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"); +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 as,i as G,E as p,M as ns,N as ls,O as rs,P as os,_ as us,p as is,q as cs}from"./pywebview-D4gpiFjY.js";import{e as ds}from"./brand-CXHemZwJ.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"],at={class:"files"},nt={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,a){if(!s?.length)return;const n=i.value.findIndex(c=>c.taskId===e),o=n>=0?i.value[n]: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:a??o?.queuePayloadText};n>=0?i.value[n]=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(a=>{a.taskId&&he(a.taskStatus)&&s.add(a.taskId)}),!s.size)return!1;const t=i.value.length;return i.value=i.value.filter(a=>!s.has(a.taskId)),i.value.length!==t?(ae(),!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 ae(){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 ne(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=ne(e);return t&&t.items.find(a=>M(a,s))||null}function pe(e){if(!e)return!1;const s=ne(e);if(!s)return!1;let t=!1;const a=g.value[e]?.line_progress?.info,n=P(e);if(a?.file_name&&a.current_line!=null&&a.total_lines!=null&&a.total_lines>0&&a.current_line>=a.total_lines){const o=s.items.find(r=>r.sourceFilename===a.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!n){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const r=s.items[0];r&&!r._completed&&(r._completed=!0,t=!0)}}return t&&ae(),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,a=_e(s),n=P(s),o=E(e);if(n){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||(a==="RUNNING"||a==="PENDING"||!a)&&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(n=>n.fileKey&&e.fileKey?n.fileKey===e.fileKey:n.sourceFilename&&e.sourceFilename?n.sourceFilename===e.sourceFilename:!1)||null}function ke(e){const s=e.taskId;if(!s)return"";const t=g.value[s],a=t?.line_progress?.info,n=le(e);if(P(s)){const u=R(s,e),c=t?.task?.status,_=!!(a?.file_name&&a.file_name===e.sourceFilename);let k=u?._completed?"COMPLETED":(u?._pushed,"PENDING"),m=0,w=Math.max(0,e.totalRows??n?.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,a?.current_line??0)),!w&&a?.total_lines&&a.total_lines>0&&(w=a.total_lines)):u?._completed?(k="COMPLETED",m=w):u?._pushed&&(k="PENDING",m=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${m}/${w}`),a?.finished_files!=null){const C=a.file_total&&a.file_total>0?`/${a.file_total}`:"";I.push(`已完成文件:${a.finished_files}${C}`)}return a?.phase&&I.push(`阶段:${a.phase}`),I.join("|")}if(n){const u=[],c=n.processedRows??0,_=n.totalRows??0;if(n.status&&u.push(`文件状态:${n.status}`),u.push(`文件进度:${c}/${_}`),a?.finished_files!=null){const k=a.file_total&&a.file_total>0?`/${a.file_total}`:"";u.push(`已完成文件:${a.finished_files}${k}`)}return a?.phase&&u.push(`阶段:${a.phase}`),u.join("|")}if(!t?.line_progress?.has_progress||!a){const u=t?.task?.status;return u?`任务状态:${u}`:""}const r=[];if(a.phase&&r.push(`阶段:${a.phase}`),a.file_index&&a.file_total&&r.push(`文件:${a.file_index}/${a.file_total}`),a.file_name&&r.push(`当前文件:${a.file_name}`),a.current_line!=null&&a.total_lines!=null&&r.push(`${P(s)?"当前文件进度":"进度"}:${a.current_line}/${a.total_lines}`),a.current_country&&r.push(`国家:${a.current_country}`),a.current_asin&&r.push(`ASIN:${a.current_asin}`),a.finished_files!=null){const u=a.file_total&&a.file_total>0?`/${a.file_total}`:"";r.push(`已完成文件:${a.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 n=le(e);return n?Math.max(0,Math.min(100,n.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function 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||!ne(s))return"";const a=R(s,e),n=_e(s),o=g.value[s]?.line_progress,r=P(s);if(!r&&(n==="SUCCESS"||n==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(a?._completed)return"本文件解析完毕";if(n==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(r&&!a?._pushed&&!a?._completed)return"未入队";if(r&&n==="SUCCESS")return"本文件解析完毕";if(!r){const u=g.value[s];if(u?.items&&u.items.find(_=>M(_,e))&&n==="SUCCESS")return"本文件解析完毕"}return a?._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 a=e?.items||[];let n=!1;const o=t.items.map(r=>{const u=a.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)&&(n=!0),C});for(const r of a)o.some(u=>M(u,r))||(o.push({...r,_pushed:!1,_completed:!1}),n=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,n=!0),n&&ae(),n}async function re(e){const s=e||L();if(s.length)try{const t=await as(s);let a=!1;for(const n of t.items||[]){const o=n?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=n,Ke(n)&&(a=!0),pe(o)&&(a=!0))}a&&x()}catch{}}function He(){return document.visibilityState==="visible"?6e3:2e4}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 a=!1,n=!1;try{await re(t),await $e();for(const o of t)we(o)&&(ve(o),a=!0,n=!0)}finally{ee.value=!1}n?await O():a&&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 a of e){const n=typeof a=="string"?a:a.absolutePath,o=typeof a=="string"?void 0:a.relativePath,r=await s.upload_file_to_java(n,o);if(!r?.success||!r.data)throw new Error(r?.error||r?.message||`上传失败:${n}`);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(a=>a.relativePath||a.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 ns({files:j.value.map(n=>({fileKey:n.fileKey,originalFilename:n.originalFilename,relativePath:n.relativePath}))}),s=ge(e.items||[]),t=s.some(n=>n.matchStatus==="MATCHED"),a=s.some(n=>n.matchStatus&&n.matchStatus!=="MATCHED");b.value=t?"解析完成,可在左侧点击“推送到 Python 队列”开始串行处理":"解析完成,当前没有可推送的已匹配文件",S.value="",s.length&&s[0].taskId&&te(s[0].taskId,s,b.value,S.value),x(),a?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(),a=ls(s),n=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(a,n);o.success?p.success(`已保存:${o.path||n}`):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(a=>a.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(a=>`${a.country}:${a.asin}${a.status?`(${a.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(),a=e.taskId;if(!a)return{success:!1,retryable:!1};const n=i.value.find(c=>c.taskId===a);if(!n)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:a,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(a,e);return c&&(c._pushed=!0,c._completed=!1),D.value=K(e),te(a,n.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(a,n.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(a=>K(a)===e);if(t){const a=t.taskId,n=P(a);n&&(pe(a),E(t),void 0);const o=E(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(n){const r=R(a,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 a of e)we(a)&&(ve(a),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:a=>Te(t)}," 下载 ",8,Ws)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:a=>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",at,"店铺名:"+v(t.shopName||"-"),1),l("div",nt,"匹配结果:"+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:a=>Te(t)}," 下载 ",8,pt)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:a=>Fe(t.resultId)}," 删除 ",8,_t)):h("",!0)])]))),128))])])):h("",!0)],64)):(d(),f("div",$s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),gt=us(yt,[["__scopeId","data-v-4a6c870e"]]);is(gt).use(cs).mount("#app"); diff --git a/app/assets/split.js b/app/assets/split.js index 94ea5cf..493db88 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-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"); +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-D4gpiFjY.js";import{e as as}from"./brand-CXHemZwJ.js";const ns={class:"page-shell module-page"},os={class:"main-content"},is={class:"left-panel"},rs={class:"upload-zone"},us={class:"selected-files clean-placeholder split-selected-files"},cs={key:0,class:"more-line"},ds={key:1},ps={class:"option-group column-option-group"},vs={class:"column-toolbar"},fs={class:"column-count"},_s={class:"column-actions"},ms={key:0,class:"column-grid"},ys=["value"],gs={key:1,class:"empty-column-state"},hs={class:"option-group"},bs={class:"radio-item active"},ws={class:"desc"},ks={class:"option-group"},Cs={class:"option-group"},Ss={key:0,class:"split-input-card"},xs={key:1,class:"split-input-card"},Fs={class:"run-row"},Es=["disabled"],Ps={class:"loading-msg"},$s={class:"right-panel"},Bs={class:"task-list-wrap"},Rs={class:"clean-result-summary"},Is={class:"summary-card"},Us={class:"summary-card"},Vs={class:"summary-card"},Ms={class:"result-list-wrap"},Ts={key:0,class:"empty-tasks"},Ds={key:1,class:"task-list clean-result-list"},Hs={class:"left split-result-main"},Ns=["title"],js={key:0,class:"files"},As={key:1,class:"time"},Ks={key:2,class:"files"},zs={key:3,class:"files split-entry-list"},qs={key:4,class:"files"},Gs={class:"task-right split-result-actions"},Js=["onClick"],Ls=["onClick"],Os=G({__name:"BrandSplitTab",setup(Ws){const f=c([]),C=c(""),d=c([]),_=c([]),p=c([]),B=c(0),u=c("rows_per_file"),m=c(2e3),y=c(5),g=c(!1),h=c([]),b=c({total:0,successCount:0,failedCount:0,items:[]}),E=Q(()=>f.value.slice(0,8));function T(l){b.value={total:l.length,successCount:l.filter(s=>s.success).length,failedCount:l.filter(s=>!s.success).length,items:l}}async function R(l){const s=F();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const o of l){const U=typeof o=="string"?o:o.absolutePath,q=typeof o=="string"?void 0:o.relativePath,w=await s.upload_file_to_java(U,q);if(!w?.success||!w.data)throw new Error(w?.error||w?.message||`上传失败:${U}`);t.push(w.data)}return t}async function I(l){const s=await Y(l);_.value=s.headers||[],p.value=[...s.headers||[]],B.value=s.totalRows||0}async function D(l,s){f.value=l,C.value="",d.value=await R(l),d.value.length>0&&await I(d.value[0].fileKey),r.success(s)}async function H(){const l=F();if(!l?.select_brand_xlsx_files){r.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await l.select_brand_xlsx_files();if(!s?.length)return;await D(s,`已选择 ${s.length} 个待拆分文件`)}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function N(){const l=F();if(!l?.select_brand_folder){r.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await l.select_brand_folder();if(!s)return;C.value=s.split(/[/\\]/).filter(Boolean).pop()||"";const t=await as(s);if(t.success&&t.items?.length){f.value=t.items.map(o=>o.relativePath),d.value=await R(t.items),d.value.length>0&&await I(d.value[0].fileKey),r.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`);return}r.warning(t.error||"该文件夹下没有 xlsx 文件")}catch(s){r.error(s instanceof Error?s.message:"选择失败")}}async function j(){if(!d.value.length){r.warning("请先选择待拆分 Excel 文件或文件夹");return}if(!p.value.length){r.warning("请至少选择一列保留列");return}if(u.value==="rows_per_file"&&(!m.value||m.value<=0)){r.warning("请输入有效的每份条数");return}if(u.value==="parts"&&(!y.value||y.value<=0)){r.warning("请输入有效的拆分份数");return}try{g.value=!0;const l=await W({files:d.value.map(s=>({fileKey:s.fileKey,originalFilename:s.originalFilename,relativePath:s.relativePath})),selectedColumns:p.value,splitMode:u.value,rowsPerFile:u.value==="rows_per_file"&&m.value||void 0,parts:u.value==="parts"&&y.value||void 0,archiveName:d.value.some(s=>!!s.relativePath)&&C.value?C.value:void 0});b.value=l,h.value=l.items||[],await P(),r.success("数据拆分完成")}catch(l){r.error(l instanceof Error?l.message:"数据拆分失败")}finally{g.value=!1}}async function P(){try{const l=await X();h.value=l.items||[],T(h.value)}catch{}}async function A(l){try{await ss(l),await P(),r.success("已删除")}catch(s){r.error(s instanceof Error?s.message:"删除失败")}}function K(l){const s=l.slice(0,4).map(o=>o.rowCount!==void 0?`${o.filename}(${o.rowCount}条)`:o.filename);return l.length-s.length>0?`${s.join("、")} 等 ${l.length} 个文件`:s.join("、")}async function z(l){const s=F();if(!l.downloadUrl){r.warning("当前结果没有下载地址");return}const t=l.outputFilename||`${new Date().toISOString().slice(0,10).replace(/-/g,"")}.zip`;if(s?.save_file_from_url_new){const o=await s.save_file_from_url_new(l.downloadUrl,t);o.success?r.success(`已保存:${o.path||t}`):o.error&&o.error!=="用户取消"&&r.error(o.error);return}}return J(()=>{P().catch(()=>{})}),(l,s)=>(a(),n("div",ns,[L(O,{active:"split"}),e("div",os,[e("aside",is,[s[14]||(s[14]=e("div",{class:"section-title"},"选择文件",-1)),e("div",rs,[s[7]||(s[7]=e("div",{class:"hint"},"选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。",-1)),e("div",{class:"btns"},[e("button",{type:"button",class:"opt-btn",onClick:H},"选择 Excel 文件"),e("button",{type:"button",class:"opt-btn",onClick:N},"选择文件夹")]),e("div",us,[f.value.length?(a(),n(S,{key:0},[(a(!0),n(S,null,$(E.value,t=>(a(),n("span",{key:t},i(t),1))),128)),f.value.length>E.value.length?(a(),n("span",cs," 还有 "+i(f.value.length-E.value.length)+" 个文件未展开显示 ",1)):v("",!0)],64)):(a(),n("span",ds,"暂未选择待拆分文件"))])]),s[15]||(s[15]=e("div",{class:"section-title"},"保留列设置",-1)),e("div",ps,[e("div",vs,[e("span",fs,"已选择 "+i(p.value.length)+" / "+i(_.value.length)+" 列",1),e("div",_s,[e("button",{type:"button",class:"opt-btn small",onClick:s[0]||(s[0]=t=>p.value=[..._.value])},"全选"),e("button",{type:"button",class:"opt-btn small",onClick:s[1]||(s[1]=t=>p.value=[])},"清空")])]),_.value.length?(a(),n("div",ms,[(a(!0),n(S,null,$(_.value,t=>(a(),n("label",{key:t,class:x(["column-item",{active:p.value.includes(t)}])},[k(e("input",{"onUpdate:modelValue":s[2]||(s[2]=o=>p.value=o),type:"checkbox",value:t},null,8,ys),[[Z,p.value]]),e("span",null,i(t),1)],2))),128))])):(a(),n("div",gs,"请选择 Excel 文件后读取表头并填充可保留列"))]),s[16]||(s[16]=e("div",{class:"section-title"},"总条数",-1)),e("div",hs,[e("label",bs,[s[9]||(s[9]=e("input",{type:"checkbox",checked:"",disabled:""},null,-1)),e("div",null,[s[8]||(s[8]=e("span",{class:"label"},"当前数据总条数",-1)),e("div",ws,i(B.value)+" 条(不含表头)",1)])])]),s[17]||(s[17]=e("div",{class:"section-title"},"拆分模式",-1)),e("div",ks,[e("label",{class:x(["radio-item",{active:u.value==="rows_per_file"}])},[k(e("input",{"onUpdate:modelValue":s[3]||(s[3]=t=>u.value=t),type:"radio",value:"rows_per_file",name:"split-mode"},null,512),[[V,u.value]]),s[10]||(s[10]=e("div",null,[e("span",{class:"label"},"按每份条数"),e("div",{class:"desc"},"例如每份 2000 条,最后一份放剩余数据")],-1))],2),e("label",{class:x(["radio-item",{active:u.value==="parts"}])},[k(e("input",{"onUpdate:modelValue":s[4]||(s[4]=t=>u.value=t),type:"radio",value:"parts",name:"split-mode"},null,512),[[V,u.value]]),s[11]||(s[11]=e("div",null,[e("span",{class:"label"},"按份数平均拆分"),e("div",{class:"desc"},"例如拆 5 份,按总条数尽量平均分配")],-1))],2)]),s[18]||(s[18]=e("div",{class:"section-title"},"拆分参数",-1)),e("div",Cs,[u.value==="rows_per_file"?(a(),n("label",Ss,[s[12]||(s[12]=e("span",{class:"label"},"每份条数",-1)),k(e("input",{"onUpdate:modelValue":s[5]||(s[5]=t=>m.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 2000"},null,512),[[M,m.value,void 0,{number:!0}]])])):(a(),n("label",xs,[s[13]||(s[13]=e("span",{class:"label"},"拆分份数",-1)),k(e("input",{"onUpdate:modelValue":s[6]||(s[6]=t=>y.value=t),class:"split-number-input",type:"number",min:"1",placeholder:"例如 5"},null,512),[[M,y.value,void 0,{number:!0}]])]))]),e("div",Fs,[e("button",{type:"button",class:"btn-run",disabled:g.value,onClick:j},i(g.value?"拆分中...":"开始拆分"),9,Es),e("span",Ps,i(g.value?"正在拆分并上传结果,请稍候…":"选择文件、保留列和拆分规则后即可执行拆分,结果会显示在右侧供下载"),1)])]),e("section",$s,[s[23]||(s[23]=e("div",{class:"panel-header"},"拆分结果",-1)),e("div",Bs,[e("div",Rs,[e("div",Is,[s[19]||(s[19]=e("span",{class:"summary-label"},"已处理文件",-1)),e("strong",null,i(b.value.total),1)]),e("div",Us,[s[20]||(s[20]=e("span",{class:"summary-label"},"成功结果",-1)),e("strong",null,i(b.value.successCount),1)]),e("div",Vs,[s[21]||(s[21]=e("span",{class:"summary-label"},"失败文件",-1)),e("strong",null,i(b.value.failedCount),1)])]),e("div",Ms,[s[22]||(s[22]=e("div",{class:"result-list-header"},[e("span",null,"拆分结果压缩包列表")],-1)),h.value.length===0?(a(),n("div",Ts," 暂无拆分结果,完成数据拆分后会在这里展示压缩包文件 ")):(a(),n("ul",Ds,[(a(!0),n(S,null,$(h.value,t=>(a(),n("li",{key:`${t.resultId||t.outputFilename||t.sourceFilename}-${t.rowCount||0}`,class:"task-item split-result-item"},[e("div",Hs,[e("span",{class:"id",title:t.sourceFilename},i(t.sourceFilename||"-"),9,Ns),t.outputFilename?(a(),n("div",js,"压缩包文件:"+i(t.outputFilename),1)):v("",!0),t.rowCount!==void 0?(a(),n("div",As,"压缩包共包含 "+i(t.rowCount)+" 条数据",1)):v("",!0),t.entryCount&&t.entryCount>0?(a(),n("div",Ks,"压缩包内共 "+i(t.entryCount)+" 个拆分文件 ",1)):v("",!0),t.entries&&t.entries.length?(a(),n("div",zs," 压缩包内容:"+i(K(t.entries)),1)):v("",!0),t.error?(a(),n("div",qs,"错误信息:"+i(t.error),1)):v("",!0)]),e("div",Gs,[e("span",{class:x(["status",t.success?"success":"failed"])},i(t.success?"已完成":"失败"),3),t.success&&t.downloadUrl?(a(),n("button",{key:0,type:"button",class:"download",onClick:o=>z(t)}," 下载压缩包 ",8,Js)):v("",!0),t.resultId?(a(),n("button",{key:1,type:"button",class:"btn-delete",onClick:o=>A(t.resultId)}," 删除 ",8,Ls)):v("",!0)])]))),128))]))])])])])]))}}),Qs=es(Os,[["__scopeId","data-v-c5a98d6b"]]);ts(Qs).use(ls).mount("#app"); diff --git a/app/blueprints/__pycache__/brand.cpython-312.pyc b/app/blueprints/__pycache__/brand.cpython-312.pyc index 2fef1f4..406fa56 100644 Binary files a/app/blueprints/__pycache__/brand.cpython-312.pyc and b/app/blueprints/__pycache__/brand.cpython-312.pyc differ diff --git a/app/new_web_source/convert.html b/app/new_web_source/convert.html index dd3590c..6907a43 100644 --- a/app/new_web_source/convert.html +++ b/app/new_web_source/convert.html @@ -5,8 +5,8 @@ 格式转换 - 数富AI - - + + diff --git a/app/new_web_source/dedupe.html b/app/new_web_source/dedupe.html index 419ddc9..57060f5 100644 --- a/app/new_web_source/dedupe.html +++ b/app/new_web_source/dedupe.html @@ -5,8 +5,8 @@ 数据去重 - 数富AI - - + + diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html index a9f1ac1..481cfec 100644 --- a/app/new_web_source/delete-brand.html +++ b/app/new_web_source/delete-brand.html @@ -5,10 +5,10 @@ 删除品牌 - 数富AI - - + + - +
diff --git a/app/new_web_source/split.html b/app/new_web_source/split.html index 6e0fdd4..c053338 100644 --- a/app/new_web_source/split.html +++ b/app/new_web_source/split.html @@ -5,8 +5,8 @@ 数据拆分 - 数富AI - - + + diff --git a/backend-java/aiimage-backend.log.2026-04-11.0.gz b/backend-java/aiimage-backend.log.2026-04-11.0.gz deleted file mode 100644 index 7617170..0000000 Binary files a/backend-java/aiimage-backend.log.2026-04-11.0.gz and /dev/null differ diff --git a/backend-java/aiimage-backend.log.2026-04-12.0.gz b/backend-java/aiimage-backend.log.2026-04-12.0.gz deleted file mode 100644 index e5cb5c4..0000000 Binary files a/backend-java/aiimage-backend.log.2026-04-12.0.gz and /dev/null 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 deleted file mode 100644 index a6fe229..0000000 Binary files a/backend-java/aiimage-backend.log.2026-04-13.0.gz and /dev/null differ diff --git a/backend-java/aiimage-backend.log.2026-04-16.0.gz b/backend-java/aiimage-backend.log.2026-04-16.0.gz new file mode 100644 index 0000000..029fbc5 Binary files /dev/null and b/backend-java/aiimage-backend.log.2026-04-16.0.gz differ diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java b/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java index a2db9aa..81bd4a7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java @@ -1,13 +1,11 @@ package com.nanri.aiimage.common.api; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor -@AllArgsConstructor @Schema(description = "统一响应体") public class ApiResponse { @@ -20,6 +18,20 @@ public class ApiResponse { @Schema(description = "响应数据") private T data; + @Schema(description = "业务错误码,成功时可为空") + private Integer code; + + public ApiResponse(boolean success, String message, T data) { + this(success, message, data, null); + } + + public ApiResponse(boolean success, String message, T data, Integer code) { + this.success = success; + this.message = message; + this.data = data; + this.code = code; + } + public static ApiResponse success(T data) { return new ApiResponse<>(true, "操作成功", data); } @@ -31,4 +43,8 @@ public class ApiResponse { public static ApiResponse fail(String message) { return new ApiResponse<>(false, message, null); } + + public static ApiResponse fail(Integer code, String message) { + return new ApiResponse<>(false, message, null, code); + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java b/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java index 0240697..a4d039a 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java @@ -2,7 +2,18 @@ package com.nanri.aiimage.common.exception; public class BusinessException extends RuntimeException { + private final Integer code; + public BusinessException(String message) { + this(null, message); + } + + public BusinessException(Integer code, String message) { super(message); + this.code = code; + } + + public Integer getCode() { + return code; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java index 3512bc8..73d65c6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java @@ -13,7 +13,9 @@ public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public ApiResponse handleBusinessException(BusinessException ex) { - return ApiResponse.fail(ex.getMessage()); + return ex.getCode() == null + ? ApiResponse.fail(ex.getMessage()) + : ApiResponse.fail(ex.getCode(), ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java b/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java new file mode 100644 index 0000000..77725f9 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java @@ -0,0 +1,126 @@ +package com.nanri.aiimage.common.util; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; + +public final class ExcelStreamReader { + + private ExcelStreamReader() { + } + + public static void readFirstSheet(File file, SheetRowHandler handler) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + readFirstSheet(inputStream, handler); + } + } + + public static void readFirstSheet(InputStream inputStream, SheetRowHandler handler) throws IOException { + runRead(inputStream, false, handler); + } + + public static void readAllSheets(File file, SheetRowHandler handler) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + readAllSheets(inputStream, handler); + } + } + + public static void readAllSheets(InputStream inputStream, SheetRowHandler handler) throws IOException { + runRead(inputStream, true, handler); + } + + private static void runRead(InputStream inputStream, boolean readAllSheets, SheetRowHandler handler) throws IOException { + StreamingListener listener = new StreamingListener(handler); + try { + if (readAllSheets) { + EasyExcel.read(inputStream, listener).headRowNumber(1).doReadAll(); + } else { + EasyExcel.read(inputStream, listener).sheet(0).headRowNumber(1).doRead(); + } + } catch (WrappedRuntimeException ex) { + if (ex.getCause() instanceof IOException ioException) { + throw ioException; + } + throw ex; + } + } + + public interface SheetRowHandler { + default void onHeader(String sheetName, Integer sheetNo, Map headerMap) throws Exception { + } + + void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) throws Exception; + } + + private static final class StreamingListener extends AnalysisEventListener> { + + private final SheetRowHandler handler; + private Map currentHeaderMap = Map.of(); + + private StreamingListener(SheetRowHandler handler) { + this.handler = handler; + } + + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + Map normalizedHeadMap = new LinkedHashMap<>(); + for (Map.Entry entry : headMap.entrySet()) { + normalizedHeadMap.put(entry.getKey(), entry.getValue()); + } + currentHeaderMap = normalizedHeadMap; + try { + handler.onHeader(sheetName(context), sheetNo(context), currentHeaderMap); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new WrappedRuntimeException(ex); + } + } + + @Override + public void invoke(Map data, AnalysisContext context) { + Map normalizedRow = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + normalizedRow.put(entry.getKey(), entry.getValue()); + } + try { + handler.onRow( + sheetName(context), + sheetNo(context), + context.readRowHolder().getRowIndex(), + currentHeaderMap, + normalizedRow + ); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new WrappedRuntimeException(ex); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + } + + private String sheetName(AnalysisContext context) { + return context.readSheetHolder() == null ? "" : context.readSheetHolder().getSheetName(); + } + + private Integer sheetNo(AnalysisContext context) { + return context.readSheetHolder() == null ? null : context.readSheetHolder().getSheetNo(); + } + } + + private static final class WrappedRuntimeException extends RuntimeException { + private WrappedRuntimeException(Throwable cause) { + super(cause); + } + } +} 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 b3500b0..b7e4a78 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 @@ -18,18 +18,18 @@ public class DeleteBrandProgressProperties { * 商品风险(PRODUCT_RISK_RESOLVE)RUNNING 超时自动收尾/失败,按分钟计算; * 与删除品牌共用同一定时调度。 */ - private long productRiskStaleTimeoutMinutes = 10; - private long productRiskInitialTimeoutMinutes = 10; + private long productRiskStaleTimeoutMinutes = 20; + private long productRiskInitialTimeoutMinutes = 20; /** * Price track RUNNING timeout auto-finalize/fail threshold in minutes. */ - private long priceTrackStaleTimeoutMinutes = 10; - private long priceTrackInitialTimeoutMinutes = 10; + private long priceTrackStaleTimeoutMinutes = 20; + private long priceTrackInitialTimeoutMinutes = 20; /** * Shop match RUNNING timeout auto-finalize/fail threshold in minutes. */ - private long shopMatchStaleTimeoutMinutes = 10; - private long shopMatchInitialTimeoutMinutes = 10; + private long shopMatchStaleTimeoutMinutes = 20; + private long shopMatchInitialTimeoutMinutes = 20; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java index b5bdd07..b7d0612 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java @@ -9,7 +9,11 @@ import com.nanri.aiimage.modules.brand.model.dto.BrandFileAggregateCacheDto; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.time.Duration; import java.time.Instant; @@ -94,21 +98,28 @@ public class BrandTaskProgressCacheService { public void saveParsedPayload(Long taskId, Object payload) { try { - stringRedisTemplate.opsForValue().set(buildPayloadKey(taskId), objectMapper.writeValueAsString(payload), ttl()); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildPayloadFile(taskId), + objectMapper.writeValueAsString(payload), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); } catch (Exception ex) { - throw new BusinessException("暂存品牌原始数据失败"); + throw new BusinessException("鏆傚瓨鍝佺墝鍘熷鏁版嵁澶辫触"); } } public T getParsedPayload(Long taskId, TypeReference typeReference) { - String raw = stringRedisTemplate.opsForValue().get(buildPayloadKey(taskId)); - if (raw == null || raw.isBlank()) { + Path payloadFile = buildPayloadFile(taskId); + if (!Files.isRegularFile(payloadFile)) { return null; } try { - return objectMapper.readValue(raw, typeReference); + return objectMapper.readValue(Files.readString(payloadFile), typeReference); } catch (Exception ex) { - throw new BusinessException("读取品牌原始数据失败"); + throw new BusinessException("璇诲彇鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -126,7 +137,7 @@ public class BrandTaskProgressCacheService { int finishedFiles = countCompletedFiles(taskId); return new ChunkStoreResult(false, false, finishedFiles, aggregate); } - throw new BusinessException("同一分片重复提交但内容不一致: " + fileUrl + "#" + file.getChunkIndex()); + throw new BusinessException("鍚屼竴鍒嗙墖閲嶅鎻愪氦浣嗗唴瀹逛笉涓€鑷? " + fileUrl + "#" + file.getChunkIndex()); } BrandFileAggregateCacheDto aggregate = getFileAggregate(taskId, fileUrl); @@ -174,7 +185,7 @@ public class BrandTaskProgressCacheService { try { return objectMapper.readValue(json, BrandFileAggregateCacheDto.class); } catch (Exception ex) { - throw new BusinessException("读取品牌文件聚合缓存失败"); + throw new BusinessException("璇诲彇鍝佺墝鏂囦欢鑱氬悎缂撳瓨澶辫触"); } } @@ -209,11 +220,11 @@ public class BrandTaskProgressCacheService { public void delete(Long taskId) { stringRedisTemplate.delete(buildKey(taskId)); - stringRedisTemplate.delete(buildPayloadKey(taskId)); stringRedisTemplate.delete(buildFileAggregateKey(taskId)); stringRedisTemplate.delete(buildCompletedFilesKey(taskId)); stringRedisTemplate.delete(buildFinalizeLockKey(taskId)); stringRedisTemplate.delete(buildLegacyResultKey(taskId)); + deleteTaskDirQuietly(taskId); } public void deleteFileState(Long taskId, String fileUrl) { @@ -236,19 +247,19 @@ public class BrandTaskProgressCacheService { stringRedisTemplate.opsForHash().put(buildFileAggregateKey(taskId), normalizeFileUrl(aggregate.getFileUrl()), objectMapper.writeValueAsString(aggregate)); refreshTaskKey(buildFileAggregateKey(taskId)); } catch (Exception ex) { - throw new BusinessException("暂存品牌文件聚合结果失败"); + throw new BusinessException("鏆傚瓨鍝佺墝鏂囦欢鑱氬悎缁撴灉澶辫触"); } } private void validateChunk(BrandCrawlResultFileDto file) { if (file == null) { - throw new BusinessException("分片不能为空"); + throw new BusinessException("鍒嗙墖涓嶈兘涓虹┖"); } if (file.getChunkIndex() == null || file.getChunkTotal() == null || file.getChunkIndex() <= 0 || file.getChunkTotal() <= 0 || file.getChunkIndex() > file.getChunkTotal()) { - throw new BusinessException("分片参数不合法"); + throw new BusinessException("鍒嗙墖鍙傛暟涓嶅悎娉?"); } if (file.getFileUrl() == null || file.getFileUrl().isBlank()) { - throw new BusinessException("fileUrl 不能为空"); + throw new BusinessException("fileUrl 涓嶈兘涓虹┖"); } } @@ -270,7 +281,7 @@ public class BrandTaskProgressCacheService { private void ensureChunkConsistency(BrandFileAggregateCacheDto aggregate, BrandCrawlResultFileDto file) { if (aggregate.getChunkTotal() != null && file.getChunkTotal() != null && !aggregate.getChunkTotal().equals(file.getChunkTotal())) { - throw new BusinessException("同一文件的 chunkTotal 不一致: " + aggregate.getFileUrl()); + throw new BusinessException("鍚屼竴鏂囦欢鐨?chunkTotal 涓嶄竴鑷? " + aggregate.getFileUrl()); } if (aggregate.getChunkTotal() == null) { aggregate.setChunkTotal(file.getChunkTotal()); @@ -322,7 +333,7 @@ public class BrandTaskProgressCacheService { } return sb.toString(); } catch (Exception ex) { - throw new BusinessException("计算品牌结果分片摘要失败"); + throw new BusinessException("璁$畻鍝佺墝缁撴灉鍒嗙墖鎽樿澶辫触"); } } @@ -340,8 +351,28 @@ public class BrandTaskProgressCacheService { return Duration.ofHours(brandProgressProperties.getTtlHours()); } - private String buildPayloadKey(Long taskId) { - return "brand:task:parsed-payload:" + taskId; + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "brand-task-cache", String.valueOf(taskId)); + } + + private Path buildPayloadFile(Long taskId) { + return buildTaskDir(taskId).resolve("parsed-payload.json"); + } + + private void deleteTaskDirQuietly(Long taskId) { + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + } + }); + } catch (IOException ignored) { + } } private String buildFileAggregateKey(Long taskId) { @@ -383,7 +414,7 @@ public class BrandTaskProgressCacheService { } return sb.toString(); } catch (Exception ex) { - throw new BusinessException("生成文件缓存键失败"); + throw new BusinessException("鐢熸垚鏂囦欢缂撳瓨閿け璐?"); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java index 8b8dbc1..f9e7067 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java @@ -327,6 +327,7 @@ public class BrandTaskService { if (deleted == 0) { throw new BusinessException("任务不存在或正在执行中无法删除"); } + brandTaskProgressCacheService.delete(taskId); } public String resolveDownloadUrl(Long taskId) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java index b524dde..65a01e6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java @@ -7,6 +7,7 @@ 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.common.util.ExcelStreamReader; import com.nanri.aiimage.config.StorageProperties; import com.nanri.aiimage.modules.convert.model.dto.ConvertRunRequest; import com.nanri.aiimage.modules.convert.model.dto.UploadedSourceFileDto; @@ -19,15 +20,10 @@ 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 lombok.RequiredArgsConstructor; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; import org.springframework.stereotype.Service; +import java.io.BufferedWriter; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -242,14 +238,30 @@ public class ConvertRunService { private List generateOutputFiles(File inputFile, ConvertTemplateEntity templateEntity) throws IOException { List outputFilenames = resolveOutputFilenames(templateEntity); - List rows = buildTxtRows(inputFile, templateEntity); File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "convert-result")); - List generatedFiles = new ArrayList<>(); + Map writers = new LinkedHashMap<>(); for (String outputFilename : outputFilenames) { File outputFile = buildNamedOutputFile(outputDir, outputFilename); - FileUtil.writeLines(rows, outputFile, StandardCharsets.UTF_8); generatedFiles.add(new GeneratedConvertFile(outputFilename, outputFile)); + writers.put(outputFilename, Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)); + } + try { + streamTxtRowsToOutputs(inputFile, templateEntity, writers); + } finally { + IOException closeException = null; + for (BufferedWriter writer : writers.values()) { + try { + writer.close(); + } catch (IOException ex) { + if (closeException == null) { + closeException = ex; + } + } + } + if (closeException != null) { + throw closeException; + } } return generatedFiles; } @@ -266,7 +278,9 @@ public class ConvertRunService { return List.of(outputFilename); } - private List buildTxtRows(File inputFile, ConvertTemplateEntity templateEntity) throws IOException { + private void streamTxtRowsToOutputs(File inputFile, + ConvertTemplateEntity templateEntity, + Map writers) throws IOException { List requiredColumns = readStringList(templateEntity.getRequiredSourceColumnsJson()); List headerColumns = readStringList(templateEntity.getHeaderColumnsJson()); Map fieldMapping = readStringMap(templateEntity.getFieldMappingJson()); @@ -275,65 +289,60 @@ public class ConvertRunService { int blankHeaderRowsAfterSchema = templateEntity.getBlankHeaderRowsAfterSchema() == null ? 0 : templateEntity.getBlankHeaderRowsAfterSchema(); + long batchId = System.currentTimeMillis(); + int[] rowIndex = new int[]{1}; + boolean[] headerRead = new boolean[]{false}; + Map[] headerMapHolder = new Map[]{null}; - DataFormatter formatter = new DataFormatter(); - try (FileInputStream fis = new FileInputStream(inputFile); - Workbook workbook = WorkbookFactory.create(fis)) { - Sheet sheet = workbook.getSheetAt(0); - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - throw new BusinessException("Excel header row is empty."); - } - - Map headerMap = new LinkedHashMap<>(); - for (int i = 0; i < headerRow.getLastCellNum(); i++) { - String value = normalizeCellText(formatter.formatCellValue(headerRow.getCell(i))); - if (!value.isBlank() && !headerMap.containsKey(value)) { - headerMap.put(value, i); + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) throws Exception { + Map resolvedHeaderMap = new LinkedHashMap<>(); + for (Map.Entry entry : headerMap.entrySet()) { + String value = normalizeCellText(entry.getValue()); + if (!value.isBlank() && !resolvedHeaderMap.containsKey(value)) { + resolvedHeaderMap.put(value, entry.getKey()); + } + } + List missing = requiredColumns.stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + headerRead[0] = true; + headerMapHolder[0] = resolvedHeaderMap; + for (String line : preambleLines) { + writeLineToAll(writers, line); + } + writeLineToAll(writers, String.join("\t", headerColumns)); + for (int i = 0; i < blankHeaderRowsAfterSchema; i++) { + writeLineToAll(writers, "\t".repeat(Math.max(0, headerColumns.size() - 1))); } } - List missing = requiredColumns.stream() - .filter(column -> !headerMap.containsKey(column)) - .toList(); - if (!missing.isEmpty()) { - throw new BusinessException("Missing required columns: " + String.join(", ", missing)); - } - - List rows = new ArrayList<>(); - rows.addAll(preambleLines); - rows.add(String.join("\t", headerColumns)); - for (int i = 0; i < blankHeaderRowsAfterSchema; i++) { - rows.add("\t".repeat(Math.max(0, headerColumns.size() - 1))); - } - - long batchId = System.currentTimeMillis(); - int rowIndex = 1; - int asinIndex = headerMap.getOrDefault("ASIN", -1); - for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - if (row == null) { - continue; + @Override + public void onRow(String sheetName, Integer sheetNo, int excelRowIndex, Map headerMap, Map rowMap) throws Exception { + Map resolvedHeaderMap = headerMapHolder[0]; + if (resolvedHeaderMap == null) { + throw new BusinessException("Excel header row is empty."); } - - String asin = asinIndex >= 0 ? normalizeCellText(formatter.formatCellValue(row.getCell(asinIndex))) : ""; + int asinIndex = resolvedHeaderMap.getOrDefault("ASIN", -1); + String asin = asinIndex >= 0 ? normalizeCellText(rowMap.get(asinIndex)) : ""; if (asin.isBlank()) { - continue; + return; } List lineValues = new ArrayList<>(); for (String column : headerColumns) { if ("sku".equals(column)) { - lineValues.add(batchId + "-" + rowIndex); + lineValues.add(batchId + "-" + rowIndex[0]); continue; } if (fieldMapping.containsKey(column)) { String sourceColumn = fieldMapping.get(column); - Integer sourceIndex = headerMap.get(sourceColumn); - String value = sourceIndex == null - ? "" - : normalizeCellText(formatter.formatCellValue(row.getCell(sourceIndex))); - lineValues.add(value); + Integer sourceIndex = resolvedHeaderMap.get(sourceColumn); + lineValues.add(sourceIndex == null ? "" : normalizeCellText(rowMap.get(sourceIndex))); continue; } if (defaults.containsKey(column)) { @@ -343,10 +352,19 @@ public class ConvertRunService { lineValues.add(""); } - rows.add(String.join("\t", lineValues)); - rowIndex++; + writeLineToAll(writers, String.join("\t", lineValues)); + rowIndex[0]++; } - return rows; + }); + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + } + + private void writeLineToAll(Map writers, String line) throws IOException { + for (BufferedWriter writer : writers.values()) { + writer.write(line); + writer.newLine(); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java index c82eff7..11a676a 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java @@ -20,7 +20,7 @@ import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; @@ -232,7 +232,7 @@ public class DedupeRunService { DataFormatter formatter = new DataFormatter(); try (FileInputStream fis = new FileInputStream(inputFile); Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(fis); - XSSFWorkbook outputWorkbook = new XSSFWorkbook()) { + SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(200)) { Sheet sheet = workbook.getSheetAt(0); Row headerRow = sheet.getRow(0); if (headerRow == null) { @@ -275,7 +275,6 @@ public class DedupeRunService { // The preliminary global scan for mainIdHasSubIdMap was removed. // We now determine subset existence contextually (per group) during the main loop. } - List candidateRows = new ArrayList<>(); Set candidateAsinValues = new HashSet<>(); for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); @@ -288,7 +287,6 @@ public class DedupeRunService { continue; } } - candidateRows.add(row); if (asinColumnIndex != null) { String asinValue = dedupeTotalDataService.normalizeComparableValueOrBlank(formatter.formatCellValue(row.getCell(asinColumnIndex))); if (!asinValue.isBlank()) { @@ -300,7 +298,17 @@ public class DedupeRunService { Set matchedAsinValues = dedupeTotalDataService.findExistingComparableValues(candidateAsinValues); Set writtenAsinValues = new HashSet<>(); int outputRowIndex = 1; - for (Row row : candidateRows) { + for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { + Row row = sheet.getRow(rowNum); + if (row == null) { + continue; + } + if (idColumnIndex != null) { + String idValue = normalizeCellText(formatter.formatCellValue(row.getCell(idColumnIndex))); + if (!shouldKeepId(idValue, keepIntegerIds, keepUnderscoreIds, keepIntegerMainIdsWhenNoSubIds, sheet, rowNum, idColumnIndex, formatter)) { + continue; + } + } if (asinColumnIndex != null) { String asinValue = dedupeTotalDataService.normalizeComparableValueOrBlank(formatter.formatCellValue(row.getCell(asinColumnIndex))); if (!asinValue.isBlank()) { @@ -324,6 +332,7 @@ public class DedupeRunService { try (FileOutputStream fos = new FileOutputStream(outputFile)) { outputWorkbook.write(fos); } + outputWorkbook.dispose(); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java index 33b623c..763b53e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java @@ -23,7 +23,9 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.InputStream; +import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -114,9 +116,9 @@ public class DedupeTotalDataService { importProgressMap.put(importId, progress); try { - byte[] fileBytes = file.getBytes(); + File tempFile = saveMultipartToTempFile(file); String filename = file.getOriginalFilename(); - Thread.ofVirtual().start(() -> runImportTask(importId, fileBytes, filename)); + Thread.ofVirtual().start(() -> runImportTask(importId, tempFile, filename)); } catch (Exception e) { importProgressMap.remove(importId); throw new BusinessException("读取上传文件失败"); @@ -150,9 +152,9 @@ public class DedupeTotalDataService { deleteImportProgressMap.put(importId, progress); try { - byte[] fileBytes = file.getBytes(); + File tempFile = saveMultipartToTempFile(file); String filename = file.getOriginalFilename(); - Thread.ofVirtual().start(() -> runDeleteImportTask(importId, fileBytes, filename)); + Thread.ofVirtual().start(() -> runDeleteImportTask(importId, tempFile, filename)); } catch (Exception e) { deleteImportProgressMap.remove(importId); throw new BusinessException("读取上传文件失败"); @@ -211,6 +213,74 @@ public class DedupeTotalDataService { } } + private void runDeleteImportTask(String importId, File tempFile, String filename) { + DedupeTotalDataImportProgressVo progress = deleteImportProgressMap.get(importId); + if (progress == null) { + return; + } + progress.setStatus("running"); + try (InputStream inputStream = Files.newInputStream(tempFile.toPath())) { + DedupeTotalDataImportVo result = deleteFromExcelInternal(inputStream, filename, progress); + progress.setTotalRows(result.getTotalRows()); + progress.setAsinCount(result.getAsinCount()); + progress.setInsertedCount(result.getInsertedCount()); + progress.setSkippedCount(result.getSkippedCount()); + progress.setProcessedRows(result.getTotalRows()); + progress.setStatus("success"); + } catch (Exception e) { + progress.setStatus("failed"); + progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "鍒犻櫎 Excel 鍖归厤鏁版嵁澶辫触"); + } finally { + deleteQuietly(tempFile); + } + } + + private void runImportTask(String importId, File tempFile, String filename) { + DedupeTotalDataImportProgressVo progress = importProgressMap.get(importId); + if (progress == null) { + return; + } + progress.setStatus("running"); + try (InputStream inputStream = Files.newInputStream(tempFile.toPath())) { + DedupeTotalDataImportVo result = importFromExcelInternal(inputStream, filename, progress); + progress.setTotalRows(result.getTotalRows()); + progress.setAsinCount(result.getAsinCount()); + progress.setInsertedCount(result.getInsertedCount()); + progress.setSkippedCount(result.getSkippedCount()); + progress.setProcessedRows(result.getTotalRows()); + progress.setStatus("success"); + } catch (Exception e) { + progress.setStatus("failed"); + progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "瀵煎叆 Excel 澶辫触"); + } finally { + deleteQuietly(tempFile); + } + } + + private File saveMultipartToTempFile(MultipartFile file) throws Exception { + String suffix = ".xlsx"; + String name = file.getOriginalFilename(); + if (name != null) { + int idx = name.lastIndexOf('.'); + if (idx >= 0) { + suffix = name.substring(idx); + } + } + File tempFile = File.createTempFile("dedupe-total-data-", suffix); + file.transferTo(tempFile); + return tempFile; + } + + private void deleteQuietly(File file) { + if (file == null) { + return; + } + try { + Files.deleteIfExists(file.toPath()); + } catch (Exception ignored) { + } + } + @Transactional public DedupeTotalDataImportVo importFromExcel(MultipartFile file) { if (file == null || file.isEmpty()) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java index b9492bc..45b895c 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java @@ -85,6 +85,12 @@ public class DeleteBrandRunController { return ApiResponse.success(deleteBrandRunService.getTaskDetails(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量获取删除品牌任务进度摘要", description = "仅返回任务基础状态和行进度摘要,用于前端轮询降载。") + public ApiResponse getTaskProgressBatch(@Valid @RequestBody DeleteBrandTaskBatchRequest request) { + return ApiResponse.success(deleteBrandRunService.getTaskProgress(request.getTaskIds())); + } + @GetMapping("/tasks/{taskId}/deletion-status") @Operation(summary = "获取删除品牌任务删除状态", description = "供 Python/插件按 taskId 查询该删除品牌任务是否已被前端删空。") public ApiResponse getTaskDeletionStatus( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java index c080b5d..1e357ae 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java @@ -544,10 +544,87 @@ public class DeleteBrandRunService { return vo; } + public com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo getTaskProgress(java.util.List taskIds) { + com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo vo = new com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return vo; + } + + java.util.List normalizedTaskIds = taskIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .limit(50) + .toList(); + if (normalizedTaskIds.isEmpty()) { + return vo; + } + + java.util.Map cachedTasks = deleteBrandTaskCacheService.getTaskCacheBatch(normalizedTaskIds); + java.util.List missingTaskIds = new java.util.ArrayList<>(); + for (Long taskId : normalizedTaskIds) { + if (!cachedTasks.containsKey(taskId)) { + missingTaskIds.add(taskId); + } + } + + java.util.Map taskById = new java.util.LinkedHashMap<>(cachedTasks); + if (!missingTaskIds.isEmpty()) { + java.util.List dbTasks = fileTaskMapper.selectBatchIds(missingTaskIds).stream() + .filter(task -> task != null && MODULE_TYPE.equals(task.getModuleType())) + .toList(); + for (FileTaskEntity dbTask : dbTasks) { + taskById.put(dbTask.getId(), dbTask); + if ("RUNNING".equals(dbTask.getStatus())) { + deleteBrandTaskCacheService.saveTaskCache(dbTask); + } + } + } + + java.util.Map> progressByTaskId = deleteBrandTaskCacheService.getProgressBatch(normalizedTaskIds); + + for (Long taskId : normalizedTaskIds) { + FileTaskEntity task = taskById.get(taskId); + if (task == null) { + vo.getMissingTaskIds().add(taskId); + continue; + } + vo.getItems().add(buildTaskProgressDetail(task, progressByTaskId.get(taskId))); + } + return vo; + } + private DeleteBrandTaskDetailVo buildTaskDetail(FileTaskEntity task) { return buildTaskDetail(task, null); } + private DeleteBrandTaskDetailVo buildTaskProgressDetail(FileTaskEntity task, java.util.Map progress) { + task = refreshIndexedMatchesIfNeeded(task); + DeleteBrandTaskItemVo taskVo = new DeleteBrandTaskItemVo(); + taskVo.setId(task.getId()); + taskVo.setTaskNo(task.getTaskNo()); + taskVo.setStatus(task.getStatus()); + taskVo.setSourceFileCount(task.getSourceFileCount()); + taskVo.setSuccessFileCount(task.getSuccessFileCount()); + taskVo.setFailedFileCount(task.getFailedFileCount()); + taskVo.setErrorMessage(task.getErrorMessage()); + taskVo.setCreatedAt(task.getCreatedAt()); + taskVo.setUpdatedAt(task.getUpdatedAt()); + taskVo.setFinishedAt(task.getFinishedAt()); + if ("SUCCESS".equals(task.getStatus())) { + taskVo.setDownloadUrl(resolveTaskDownloadUrl(task.getId())); + taskVo.setDownloadFilename(resolveTaskDownloadFilename(task.getId())); + } else { + taskVo.setDownloadUrl(null); + taskVo.setDownloadFilename(null); + } + + DeleteBrandTaskDetailVo detail = new DeleteBrandTaskDetailVo(); + detail.setTask(taskVo); + detail.setLine_progress(buildLineProgress(task.getId(), progress)); + detail.setFileProgress(java.util.List.of()); + return detail; + } + private DeleteBrandTaskDetailVo buildTaskDetail(FileTaskEntity task, java.util.Map progress) { task = refreshIndexedMatchesIfNeeded(task); DeleteBrandTaskItemVo taskVo = new DeleteBrandTaskItemVo(); 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 703a2ce..a003416 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 @@ -17,10 +17,15 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.List; import java.util.Map; @Service @@ -34,6 +39,8 @@ public class DeleteBrandStaleTaskService { 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); + private static final Duration TEMP_DIR_CLEANUP_LOCK_TTL = Duration.ofMinutes(10); + private static final Duration TEMP_DIR_RETENTION = Duration.ofHours(48); private final FileTaskMapper fileTaskMapper; private final DeleteBrandTaskCacheService deleteBrandTaskCacheService; @@ -289,7 +296,7 @@ public class DeleteBrandStaleTaskService { log.info("[stale-check] shop-match candidates={} threshold={} timeoutMinutes={} initialThreshold={} initialTimeoutMinutes={}", runningTasks.size(), threshold, minutes, initialThreshold, initialMinutes); for (FileTaskEntity task : runningTasks) { - boolean hasUploadedPayload = !shopMatchTaskCacheService.getAllShopMergedPayload(task.getId()).isEmpty(); + boolean hasUploadedPayload = shopMatchTaskCacheService.hasAnyShopMergedPayload(task.getId()); boolean hasFinishedRows = (task.getSuccessFileCount() != null && task.getSuccessFileCount() > 0) || (task.getFailedFileCount() != null && task.getFailedFileCount() > 0); boolean hasStartedProgress = hasUploadedPayload || hasFinishedRows; @@ -352,6 +359,74 @@ public class DeleteBrandStaleTaskService { } } + @Scheduled(cron = "${aiimage.temp-dir.cleanup-cron:15 */30 * * * *}") + public void cleanupExpiredTempDirs() { + DistributedJobLockService.LockHandle lockHandle = + distributedJobLockService.tryLock("temp-dir:cleanup", TEMP_DIR_CLEANUP_LOCK_TTL); + if (lockHandle == null) { + log.info("[temp-dir-cleanup] skip because another instance holds the distributed lock"); + return; + } + try (lockHandle) { + Instant cutoff = Instant.now().minus(TEMP_DIR_RETENTION); + List dirNames = List.of( + "shop-match-cache", + "brand-task-cache", + "delete-brand-task-cache", + "shop-match-result", + "delete-brand-result", + "product-risk-result", + "price-track-result" + ); + for (String dirName : dirNames) { + cleanupTempRoot(dirName, cutoff); + } + } + } + + private void cleanupTempRoot(String dirName, Instant cutoff) { + Path root = Path.of(System.getProperty("java.io.tmpdir"), dirName); + if (!Files.isDirectory(root)) { + return; + } + try (var stream = Files.list(root)) { + for (Path child : stream.toList()) { + try { + FileTime lastModified = Files.getLastModifiedTime(child); + if (lastModified.toInstant().isAfter(cutoff)) { + continue; + } + deleteRecursively(child); + log.info("[temp-dir-cleanup] deleted expired temp path dir={} path={}", dirName, child); + } catch (Exception ex) { + log.warn("[temp-dir-cleanup] delete failed dir={} path={} msg={}", dirName, child, ex.getMessage()); + } + } + } catch (IOException ex) { + log.warn("[temp-dir-cleanup] scan failed dir={} msg={}", dirName, ex.getMessage()); + } + } + + private void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path)) { + return; + } + try (var walk = Files.walk(path)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(item -> { + try { + Files.deleteIfExists(item); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof IOException ioException) { + throw ioException; + } + throw ex; + } + } + private static final class ProductRiskStaleCheckStats { private int scannedTaskCount; private int finalizedTaskCount; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java index 65a8802..75e38ae 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java @@ -7,6 +7,9 @@ import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.time.Duration; import java.util.concurrent.ConcurrentHashMap; @@ -28,10 +31,17 @@ public class DeleteBrandTaskCacheService { public void saveParsedPayload(Long taskId, Object payload) { try { - stringRedisTemplate.opsForValue().set(buildPayloadKey(taskId), objectMapper.writeValueAsString(payload), Duration.ofHours(PAYLOAD_TTL_HOURS)); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildPayloadFile(taskId), + objectMapper.writeValueAsString(payload), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(System.currentTimeMillis(), payload)); } catch (Exception ex) { - throw new BusinessException("暂存删除品牌原始数据失败"); + throw new BusinessException("鏆傚瓨鍒犻櫎鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -46,21 +56,21 @@ public class DeleteBrandTaskCacheService { try { return objectMapper.convertValue(cached.value(), typeReference); } catch (Exception ignored) { - // fallthrough to redis + // fall through to file } } - String raw = stringRedisTemplate.opsForValue().get(buildPayloadKey(taskId)); - if (raw == null || raw.isBlank()) { + Path payloadFile = buildPayloadFile(taskId); + if (!Files.isRegularFile(payloadFile)) { parsedPayloadLocalCache.remove(taskId); return null; } try { - T parsed = objectMapper.readValue(raw, typeReference); + T parsed = objectMapper.readValue(Files.readString(payloadFile), typeReference); parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(now, parsed)); return parsed; } catch (Exception ex) { - throw new BusinessException("读取删除品牌原始数据失败"); + throw new BusinessException("璇诲彇鍒犻櫎鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -114,17 +124,17 @@ public class DeleteBrandTaskCacheService { public boolean hasSameResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) { if (chunkIndex == null || chunkIndex <= 0) { - throw new BusinessException("chunkIndex 不合法"); + throw new BusinessException("chunkIndex 涓嶅悎娉?"); } if (fileIdentity == null || fileIdentity.isBlank()) { - throw new BusinessException("fileIdentity 不能为空"); + throw new BusinessException("fileIdentity 涓嶈兘涓虹┖"); } String field = fileIdentity.trim() + "#" + chunkIndex; String chunkJson; try { chunkJson = objectMapper.writeValueAsString(chunk); } catch (Exception ex) { - throw new BusinessException("读取删除品牌结果分片失败"); + throw new BusinessException("璇诲彇鍒犻櫎鍝佺墝缁撴灉鍒嗙墖澶辫触"); } Object existing = stringRedisTemplate.opsForHash().get(buildResultChunksKey(taskId), field); if (chunkJson.equals(existing)) { @@ -137,17 +147,17 @@ public class DeleteBrandTaskCacheService { public boolean mergeResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) { String resultKey = buildResultChunksKey(taskId); if (chunkIndex == null || chunkIndex <= 0) { - throw new BusinessException("chunkIndex 不合法"); + throw new BusinessException("chunkIndex 涓嶅悎娉?"); } if (fileIdentity == null || fileIdentity.isBlank()) { - throw new BusinessException("fileIdentity 不能为空"); + throw new BusinessException("fileIdentity 涓嶈兘涓虹┖"); } String field = fileIdentity.trim() + "#" + chunkIndex; String chunkJson; try { chunkJson = objectMapper.writeValueAsString(chunk); } catch (Exception ex) { - throw new BusinessException("暂存删除品牌结果分片失败"); + throw new BusinessException("鏆傚瓨鍒犻櫎鍝佺墝缁撴灉鍒嗙墖澶辫触"); } Object existing = stringRedisTemplate.opsForHash().get(resultKey, field); if (chunkJson.equals(existing)) { @@ -178,14 +188,16 @@ public class DeleteBrandTaskCacheService { public void delete(Long taskId) { parsedPayloadLocalCache.remove(taskId); - stringRedisTemplate.delete(buildPayloadKey(taskId)); stringRedisTemplate.delete(buildProgressKey(taskId)); stringRedisTemplate.delete(buildResultChunksKey(taskId)); stringRedisTemplate.delete(buildTaskEntityKey(taskId)); + deleteTaskDirQuietly(taskId); } public void saveTaskCache(com.nanri.aiimage.modules.task.model.entity.FileTaskEntity task) { - if (task == null || task.getId() == null) return; + if (task == null || task.getId() == null) { + return; + } try { stringRedisTemplate.opsForValue().set(buildTaskEntityKey(task.getId()), objectMapper.writeValueAsString(task), Duration.ofHours(PAYLOAD_TTL_HOURS)); } catch (Exception ignored) { @@ -194,10 +206,14 @@ public class DeleteBrandTaskCacheService { public java.util.Map getTaskCacheBatch(java.util.List taskIds) { java.util.Map result = new java.util.LinkedHashMap<>(); - if (taskIds == null || taskIds.isEmpty()) return result; + if (taskIds == null || taskIds.isEmpty()) { + return result; + } java.util.List normalized = taskIds.stream().filter(id -> id != null && id > 0).distinct().toList(); - if (normalized.isEmpty()) return result; + if (normalized.isEmpty()) { + return result; + } java.util.List keys = normalized.stream().map(this::buildTaskEntityKey).toList(); java.util.List values = stringRedisTemplate.opsForValue().multiGet(keys); @@ -215,6 +231,30 @@ public class DeleteBrandTaskCacheService { return result; } + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "delete-brand-task-cache", String.valueOf(taskId)); + } + + private Path buildPayloadFile(Long taskId) { + return buildTaskDir(taskId).resolve("parsed-payload.json"); + } + + private void deleteTaskDirQuietly(Long taskId) { + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (Exception ignored) { + } + }); + } catch (Exception ignored) { + } + } + private String buildTaskEntityKey(Long taskId) { return "delete-brand:task:entity:" + taskId; } @@ -225,10 +265,6 @@ public class DeleteBrandTaskCacheService { } } - private String buildPayloadKey(Long taskId) { - return "delete-brand:task:parsed-payload:" + taskId; - } - private String buildProgressKey(Long taskId) { return "delete-brand:task:progress:" + taskId; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java index b40ab05..4cbdfe7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java @@ -17,4 +17,6 @@ public class PermissionMenuCreateRequest { @NotBlank(message = "菜单路由不能为空") private String routePath; + + private Integer sortOrder; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java index 38ef597..e2b6927 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java @@ -17,4 +17,6 @@ public class PermissionMenuUpdateRequest { @NotBlank(message = "菜单路由不能为空") private String routePath; + + private Integer sortOrder; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java index b3af65b..9ac7b4e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java @@ -1,6 +1,7 @@ package com.nanri.aiimage.modules.permission.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; @@ -11,5 +12,8 @@ public class AdminUserEntity { @TableId(type = IdType.AUTO) private Long id; + private String username; private String role; + @TableField("created_by_id") + private Long createdById; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java index c8e4262..cbebbf8 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java @@ -17,5 +17,6 @@ public class PermissionMenuEntity { private String columnKey; private String menuType; private String routePath; + private Integer sortOrder; private LocalDateTime createdAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java index 875dc87..2db9e38 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java @@ -12,5 +12,6 @@ public class PermissionMenuItemVo { private String columnKey; private String menuType; private String routePath; + private Integer sortOrder; private LocalDateTime createdAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java index 3645a2e..41681e7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java @@ -14,10 +14,16 @@ import java.util.List; public class PermissionMenuSchemaInitializer { private final JdbcTemplate jdbcTemplate; + private static final List DEFAULT_ADMIN_MENUS = List.of( - new DefaultAdminMenu("数据去重总数据", "admin_dedupe_total_data", "dedupe-total-data"), - new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage"), - new DefaultAdminMenu("跳过跟价ASIN", "admin_skip_price_asin", "skip-price-asin") + new DefaultAdminMenu("用户管理", "admin_users", "users", 10), + new DefaultAdminMenu("栏目权限配置", "admin_columns", "columns", 20), + new DefaultAdminMenu("数据去重总数据", "admin_dedupe_total_data", "dedupe-total-data", 30), + new DefaultAdminMenu("店铺密钥管理", "admin_shop_keys", "shop-keys", 40), + new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage", 50), + new DefaultAdminMenu("跳过跟价ASIN", "admin_skip_price_asin", "skip-price-asin", 60), + new DefaultAdminMenu("查看生成记录", "admin_history", "history", 70), + new DefaultAdminMenu("版本管理", "admin_version", "version", 80) ); @PostConstruct @@ -25,23 +31,19 @@ public class PermissionMenuSchemaInitializer { executeQuietly(""" CREATE TABLE IF NOT EXISTS columns ( id INT AUTO_INCREMENT PRIMARY KEY, - name VARCHAR(128) NOT NULL COMMENT '栏目名', - column_key VARCHAR(64) NOT NULL COMMENT '栏目标识', + name VARCHAR(128) NOT NULL COMMENT '菜单标题', + column_key VARCHAR(64) NOT NULL COMMENT '菜单唯一标识', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uk_column_key (column_key) ) """); executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key"); executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type"); + executeQuietly("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path"); executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''"); + executeQuietly("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0"); + executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_menu_type_route_path (menu_type, route_path)"); ensureDefaultAdminMenus(); - executeQuietly(""" - INSERT INTO columns (name, column_key, menu_type, route_path) - SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage' - WHERE NOT EXISTS ( - SELECT 1 FROM columns WHERE column_key = 'admin_shop_manage' - ) - """); executeQuietly(""" CREATE TABLE IF NOT EXISTS user_column_permission ( user_id INT NOT NULL, @@ -56,12 +58,17 @@ public class PermissionMenuSchemaInitializer { private void ensureDefaultAdminMenus() { for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) { executeQuietly(""" - INSERT INTO columns (name, column_key, menu_type, route_path) - SELECT '%s', '%s', 'admin', '%s' + INSERT INTO columns (name, column_key, menu_type, route_path, sort_order) + SELECT '%s', '%s', 'admin', '%s', %d WHERE NOT EXISTS ( SELECT 1 FROM columns WHERE column_key = '%s' ) - """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.columnKey())); + """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), menu.columnKey())); + executeQuietly(""" + UPDATE columns + SET sort_order = %d + WHERE column_key = '%s' AND (sort_order IS NULL OR sort_order = 0) + """.formatted(menu.sortOrder(), menu.columnKey())); } } @@ -73,6 +80,6 @@ public class PermissionMenuSchemaInitializer { } } - private record DefaultAdminMenu(String name, String columnKey, String routePath) { + private record DefaultAdminMenu(String name, String columnKey, String routePath, int sortOrder) { } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java index a0ef8f0..54ed17e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java @@ -19,6 +19,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; +import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -41,6 +42,7 @@ public class PermissionMenuService { public List list(String menuType) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(isValidMenuType(menuType), PermissionMenuEntity::getMenuType, normalizeMenuType(menuType)) + .orderByAsc(PermissionMenuEntity::getSortOrder) .orderByAsc(PermissionMenuEntity::getId); return permissionMenuMapper.selectList(query).stream() .map(this::toItemVo) @@ -54,12 +56,14 @@ public class PermissionMenuService { String menuType = normalizeMenuTypeRequired(request.getMenuType()); String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空"); ensureUniqueColumnKey(columnKey, null); + ensureUniqueRoutePath(menuType, routePath, null); PermissionMenuEntity entity = new PermissionMenuEntity(); entity.setName(name); entity.setColumnKey(columnKey); entity.setMenuType(menuType); entity.setRoutePath(routePath); + entity.setSortOrder(resolveSortOrder(request.getSortOrder(), null)); permissionMenuMapper.insert(entity); return toItemVo(getMenuById(entity.getId())); } @@ -72,11 +76,13 @@ public class PermissionMenuService { String menuType = normalizeMenuTypeRequired(request.getMenuType()); String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空"); ensureUniqueColumnKey(columnKey, id); + ensureUniqueRoutePath(menuType, routePath, id); entity.setName(name); entity.setColumnKey(columnKey); entity.setMenuType(menuType); entity.setRoutePath(routePath); + entity.setSortOrder(resolveSortOrder(request.getSortOrder(), id)); permissionMenuMapper.updateById(entity); return toItemVo(getMenuById(id)); } @@ -141,6 +147,9 @@ public class PermissionMenuService { .map(menuMap::get) .filter(menu -> menu != null) .filter(menu -> safeMenuType == null || safeMenuType.equals(menu.getMenuType())) + .sorted(Comparator + .comparing(PermissionMenuEntity::getSortOrder, Comparator.nullsLast(Integer::compareTo)) + .thenComparing(PermissionMenuEntity::getId, Comparator.nullsLast(Long::compareTo))) .map(this::toItemVo) .toList(); } @@ -196,6 +205,16 @@ public class PermissionMenuService { } } + private void ensureUniqueRoutePath(String menuType, String routePath, Long excludeId) { + PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper() + .eq(PermissionMenuEntity::getMenuType, menuType) + .eq(PermissionMenuEntity::getRoutePath, routePath) + .last("LIMIT 1")); + if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) { + throw new BusinessException("同一菜单类型下的菜单路由已存在"); + } + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty() && !message.isEmpty()) { @@ -247,7 +266,21 @@ public class PermissionMenuService { vo.setColumnKey(entity.getColumnKey()); vo.setMenuType(entity.getMenuType()); vo.setRoutePath(entity.getRoutePath()); + vo.setSortOrder(entity.getSortOrder()); vo.setCreatedAt(entity.getCreatedAt()); return vo; } + + private Integer resolveSortOrder(Integer sortOrder, Long excludeId) { + if (sortOrder != null) { + return sortOrder; + } + PermissionMenuEntity tail = permissionMenuMapper.selectOne(new LambdaQueryWrapper() + .ne(excludeId != null, PermissionMenuEntity::getId, excludeId) + .orderByDesc(PermissionMenuEntity::getSortOrder) + .orderByDesc(PermissionMenuEntity::getId) + .last("LIMIT 1")); + int currentMax = tail == null || tail.getSortOrder() == null ? 0 : tail.getSortOrder(); + return currentMax + 1; + } } 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 cf1b812..e0619cb 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 @@ -47,7 +47,8 @@ import java.util.List; @RequestMapping("/api/price-track") @Tag( name = "跟价", - description = "亚马逊跟价处理模块:包含备选店铺、紫鸟匹配、任务创建、Python 回传、任务轮询和结果下载接口。查询类接口需要携带 Query 参数 user_id。") + description = "亚马逊跟价处理模块,包含备选店铺、紫鸟匹配、任务创建、Python 回传、任务轮询和结果下载接口。查询类接口需携带 query 参数 user_id。" +) public class PriceTrackController { private final PriceTrackService priceTrackService; @@ -62,13 +63,13 @@ public class PriceTrackController { } @PostMapping("/candidates") - @Operation(summary = "新增备选店铺", description = "把店铺名称写入当前用户的备选店铺列表,供后续匹配和创建任务使用。") + @Operation(summary = "新增备选店铺", description = "新增一条备选店铺记录,供后续匹配和创建任务使用。") public ApiResponse addCandidate(@Valid @RequestBody PriceTrackCandidateAddRequest request) { return ApiResponse.success(priceTrackService.addCandidate(request)); } @DeleteMapping("/candidates/{id}") - @Operation(summary = "删除备选店铺", description = "删除一条备选店铺记录,id 必须属于当前 user_id。") + @Operation(summary = "删除备选店铺", description = "删除一条备选店铺记录,记录必须属于当前 user_id。") public ApiResponse deleteCandidate( @Parameter(description = "备选店铺记录主键", example = "10") @PathVariable Long id, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -107,7 +108,7 @@ public class PriceTrackController { } @GetMapping("/history") - @Operation(summary = "处理记录列表", description = "返回当前用户跟价模块下各店铺结果行,包含运行中和历史记录。") + @Operation(summary = "处理记录列表", description = "返回当前用户跟价模块下各店铺结果记录,包含运行中和历史记录。") public ApiResponse history( @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @RequestParam("user_id") Long userId) { @@ -115,7 +116,7 @@ public class PriceTrackController { } @DeleteMapping("/history/{resultId}") - @Operation(summary = "删除单条结果记录", description = "删除一条 biz_file_result,并同步重算父任务状态。") + @Operation(summary = "删除单条结果记录", description = "删除一条 biz_file_result 结果记录,并同步重算父任务状态。") public ApiResponse deleteHistory( @Parameter(description = "结果行主键 biz_file_result.id", example = "1001") @PathVariable Long resultId, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -131,7 +132,7 @@ public class PriceTrackController { } @DeleteMapping("/tasks/{taskId}") - @Operation(summary = "删除整条任务", description = "删除该任务以及其下属全部结果行,RUNNING、SUCCESS、FAILED 均可。") + @Operation(summary = "删除整条任务", description = "删除该任务以及其下全部结果行,RUNNING、SUCCESS、FAILED 均可删除。") public ApiResponse deleteTask( @Parameter(description = "任务主键 biz_file_task.id", example = "200") @PathVariable Long taskId, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -151,11 +152,17 @@ public class PriceTrackController { } @PostMapping("/tasks/batch") - @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概要和各店铺结果,供前端轮询使用。") + @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概要和各店铺结果,供前端查询使用。") public ApiResponse tasksBatch(@Valid @RequestBody PriceTrackTaskBatchRequest request) { return ApiResponse.success(priceTrackTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、时间和错误等轻量信息,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody PriceTrackTaskBatchRequest request) { + return ApiResponse.success(priceTrackTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation(summary = "Python 回传处理结果", description = "同一 taskId 可多次回传。成功时按 countries 生成结果文件,所有店铺进入终态后任务会变为 SUCCESS 或 FAILED。") public ApiResponse submitResult( 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 a743000..c405caf 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 @@ -8,13 +8,20 @@ import lombok.Data; import java.util.List; @Data -@Schema(description = "批量匹配店铺请求体:按店铺名查询紫鸟索引,返回是否命中及店铺元数据") +@Schema(description = "Price track match shops request") public class PriceTrackMatchShopsRequest { - @NotNull(message = "user_id不能为空") - @Schema(description = "当前用户 ID,用于审计和数据归属", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + + @NotNull(message = "userId is required") + @Schema(description = "Current user id", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; - @NotEmpty(message = "店铺列表不能为空") - @Schema(description = "待匹配的店铺名称列表,至少 1 个;返回体 items 与列表顺序对应", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"店铺甲\",\"店铺乙\"]") + @NotEmpty(message = "shopNames cannot be empty") + @Schema(description = "Shop names to match", requiredMode = Schema.RequiredMode.REQUIRED) private List shopNames; + + @Schema(description = "Selected ASIN file local paths") + private List asinFiles; + + @Schema(description = "Selected country codes") + private List countryCodes; } 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 5663628..37c5849 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 @@ -7,43 +7,73 @@ import java.util.List; import java.util.Map; @Data -@Schema(description = "Python 回传跟价结果请求体:按店铺提交各国家 ASIN 跟价结果或错误信息") +@Schema(description = "Python submit payload for price track task results") public class PriceTrackSubmitResultRequest { - @Schema(description = "本次回传涉及的店铺列表,至少 1 个,店名需要能和任务结果行匹配", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Shop result list", requiredMode = Schema.RequiredMode.REQUIRED) private List shops; @Data - @Schema(description = "单个店铺回传结果:成功时提供 countries,失败时可只提供 error") + @Schema(description = "Per-shop submit result") public static class ShopResult { - @Schema(description = "店铺名称,用于和任务内结果行匹配", example = "测试店铺A") + @Schema(description = "Shop name used to match task rows", example = "Test Shop A") private String shopName; - @Schema(description = "按国家分组的结果行,key 为国家代码,例如 DE、UK、FR、IT、ES") + @Schema(description = "Rows grouped by country code, for example DE/UK/FR/IT/ES") private Map> countries; - @Schema(description = "失败时的错误信息;非空则该店铺记为失败") + @Schema(description = "Failure message") private String error; - @Schema(description = "是否成功;false 按失败处理,true 或 null 通常表示结合 countries 判定") + @Schema(description = "Whether the shop finished successfully") private Boolean success; } @Data - @Schema(description = "单条 ASIN 跟价结果") + @Schema(description = "Per-ASIN price track result row") public static class AsinResult { + @Schema(description = "Shop mall name", example = "Amazon.de") + private String shopMallName; + @Schema(description = "ASIN", example = "B0ABCDE123") private String asin; - @Schema(description = "当前店铺价格", example = "19.99") + @Schema(description = "Price", example = "19.99") + private String price; + + @Schema(description = "Recommended price", example = "18.99") + private String recommendedPrice; + + @Schema(description = "Lowest price", example = "18.50") + private String minimumPrice; + + @Schema(description = "First place", example = "Competitor A") + private String firstPlace; + + @Schema(description = "Second place", example = "Competitor B") + private String secondPlace; + + @Schema(description = "Buy box shop name", example = "Shop A") + private String cartShopName; + + @Schema(description = "Price change status", example = "UPDATED") + private String priceChangeStatus; + + @Schema(description = "Modify count", example = "2") + private String modifyCount; + + @Schema(description = "Status", example = "SUCCESS") + private String status; + + @Schema(description = "Legacy current price", example = "19.99") private String currentPrice; - @Schema(description = "竞争对手价格", example = "18.50") + @Schema(description = "Legacy competitor price", example = "18.50") private String competitorPrice; - @Schema(description = "建议动作或跟价动作", example = "LOWER_PRICE") + @Schema(description = "Legacy action", example = "LOWER_PRICE") private String action; - @Schema(description = "该行是否已处理完成") + @Schema(description = "Legacy done flag") private Boolean done; } } 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 7acb2a7..1e6b686 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 @@ -4,13 +4,20 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import java.util.List; +import java.util.Map; @Data -@Schema(description = "创建任务响应:包含任务 id 和各店铺的初始结果快照") +@Schema(description = "price track create task response") public class PriceTrackCreateTaskVo { - @Schema(description = "新建任务主键 biz_file_task.id,前端推送队列时需要回传该值", example = "200") + @Schema(description = "task id", example = "200") private Long taskId; - @Schema(description = "各店铺一条初始结果快照,包含 resultId、taskId、店铺信息和初始任务状态") + @Schema(description = "initial task items") private List items; + + @Schema(description = "all skip asins grouped by country") + private Map> skipAsinsByCountry; + + @Schema(description = "parsed asin rows by country") + private Map>> asinRowsByCountry; } 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 e039a29..8e5a86c 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 @@ -5,35 +5,47 @@ import lombok.Data; import java.util.ArrayList; import java.util.List; +import java.util.Map; @Data -@Schema(description = "批量匹配店铺响应") +@Schema(description = "Price track shop match response") public class PriceTrackMatchShopsVo { - @Schema(description = "逐店返回的匹配结果,顺序与请求 shopNames 对应") + + @Schema(description = "Match results in the same order as requested shop names") private List items = new ArrayList<>(); + @Schema(description = "All skip ASINs grouped by country code") + private Map> skipAsinsByCountry; + + @Schema(description = "Parsed asin rows grouped by country code") + private Map>> asinRowsByCountry; + @Data - @Schema(description = "单店匹配结果,同时也是创建任务时 items 的结构") + @Schema(description = "Single matched shop item") public static class PriceTrackShopQueueItem { - @Schema(description = "店铺名称", example = "某某店铺") + + @Schema(description = "Shop name", example = "Demo Shop") private String shopName; - @Schema(description = "紫鸟店铺 ID,未命中时可能为空") + @Schema(description = "Matched shop id") private Object shopId; - @Schema(description = "平台,例如亚马逊", example = "亚马逊") + @Schema(description = "Platform", example = "Amazon") private String platform; - @Schema(description = "公司名称或主体标识") + @Schema(description = "Company name") private String companyName; - @Schema(description = "是否命中紫鸟索引;false 时不可用于创建任务") + @Schema(description = "Whether the shop matched") private Boolean matched; - @Schema(description = "匹配状态码,例如 MATCHED、PENDING、CONFLICT、INDEX_STALE") + @Schema(description = "Match status, such as MATCHED or PENDING") private String matchStatus; - @Schema(description = "人类可读说明,供前端展示") + @Schema(description = "Readable match message") private String matchMessage; + + @Schema(description = "All skip ASINs grouped by country code") + private Map> skipAsins; } } 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 index 9fc5029..4b4d03f 100644 --- 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 @@ -19,7 +19,19 @@ import java.util.Map; @Slf4j public class PriceTrackExcelAssemblyService { - private static final String[] HEADER = {"ASIN", "当前店铺价格", "竞争对手价格", "建议动作", "是否完成"}; + private static final String[] RESULT_HEADER = { + "\u5e97\u94fa\u5546\u57ce\u540d\u79f0", + "ASIN", + "\u4ef7\u683c", + "\u63a8\u8350\u4ef7", + "\u6700\u4f4e\u4ef7", + "\u7b2c\u4e00\u540d", + "\u7b2c\u4e8c\u540d", + "\u8d2d\u7269\u8f66\u5e97\u94fa\u540d", + "\u6539\u4ef7\u60c5\u51b5", + "\u4fee\u6539\u6b21\u6570", + "\u72b6\u6001" + }; public void writeWorkbook(File outputXlsx, Map> countries) { Map> safe = countries == null ? Map.of() : countries; @@ -28,8 +40,8 @@ public class PriceTrackExcelAssemblyService { 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]); + for (int i = 0; i < RESULT_HEADER.length; i++) { + headerRow.createCell(i).setCellValue(RESULT_HEADER[i]); } List rows = safe.getOrDefault(sheetName, List.of()); int rowIdx = 1; @@ -38,20 +50,26 @@ public class PriceTrackExcelAssemblyService { 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())); + row.createCell(0).setCellValue(valueOf(item.getShopMallName())); + row.createCell(1).setCellValue(valueOf(item.getAsin())); + row.createCell(2).setCellValue(firstNonBlank(item.getPrice(), item.getCurrentPrice())); + row.createCell(3).setCellValue(valueOf(item.getRecommendedPrice())); + row.createCell(4).setCellValue(firstNonBlank(item.getMinimumPrice(), item.getCompetitorPrice())); + row.createCell(5).setCellValue(valueOf(item.getFirstPlace())); + row.createCell(6).setCellValue(valueOf(item.getSecondPlace())); + row.createCell(7).setCellValue(valueOf(item.getCartShopName())); + row.createCell(8).setCellValue(firstNonBlank(item.getPriceChangeStatus(), item.getAction())); + row.createCell(9).setCellValue(valueOf(item.getModifyCount())); + row.createCell(10).setCellValue(firstNonBlank(item.getStatus(), item.getDone() == null ? null : String.valueOf(item.getDone()))); } - for (int i = 0; i < HEADER.length; i++) { + for (int i = 0; i < RESULT_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()); + throw new BusinessException("鐢熸垚 Excel 澶辫触: " + ex.getMessage()); } } @@ -82,4 +100,20 @@ public class PriceTrackExcelAssemblyService { } return out; } + + private static String valueOf(String value) { + return value == null ? "" : value; + } + + private static String firstNonBlank(String... values) { + if (values == null || values.length == 0) { + return ""; + } + for (String value : values) { + if (value != null && !value.isBlank()) { + return value; + } + } + return ""; + } } 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 d9876b7..9f0f285 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 @@ -24,8 +24,10 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; @Service @@ -40,6 +42,7 @@ public class PriceTrackService { private final ObjectMapper objectMapper; private final ZiniaoShopSwitchService ziniaoShopSwitchService; private final SkipPriceAsinService skipPriceAsinService; + private final PriceTrackTaskService priceTrackTaskService; public List listCandidates(Long userId) { if (userId == null || userId <= 0) { @@ -139,9 +142,22 @@ public class PriceTrackService { throw new BusinessException("shop_names 没有有效店铺名"); } + boolean asinMode = request.getAsinFiles() != null && !request.getAsinFiles().isEmpty(); + Map> skipAsinsByCountry = asinMode + ? new LinkedHashMap<>() + : skipPriceAsinService.listAllSkipAsinsByCountry(); + Map>> asinRowsByCountry = + !asinMode + ? new LinkedHashMap<>() + : priceTrackTaskService.parseMatchAsinRowsByCountry( + request.getAsinFiles(), + request.getCountryCodes()); + PriceTrackMatchShopsVo vo = new PriceTrackMatchShopsVo(); + vo.setSkipAsinsByCountry(skipAsinsByCountry); + vo.setAsinRowsByCountry(asinRowsByCountry); for (String shopName : ordered) { - vo.getItems().add(matchOneShop(shopName)); + vo.getItems().add(matchOneShop(shopName, skipAsinsByCountry)); } return vo; } @@ -198,9 +214,13 @@ public class PriceTrackService { return vo; } - private PriceTrackMatchShopsVo.PriceTrackShopQueueItem matchOneShop(String shopName) { + private PriceTrackMatchShopsVo.PriceTrackShopQueueItem matchOneShop( + String shopName, + Map> skipAsins + ) { PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem(); item.setShopName(shopName); + item.setSkipAsins(skipAsins == null ? new LinkedHashMap<>() : new LinkedHashMap<>(skipAsins)); try { ZiniaoShopMatchResultVo match = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); if (match == null) { 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 da04c7e..649d53c 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 @@ -4,7 +4,9 @@ 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.common.util.ExcelStreamReader; import com.nanri.aiimage.modules.file.service.oss.OssStorageService; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackShopCandidateMapper; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCreateTaskRequest; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest; @@ -30,12 +32,19 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Locale; @Service @RequiredArgsConstructor @@ -179,8 +188,33 @@ public class PriceTrackTaskService { return batch; } + public PriceTrackTaskBatchVo getTaskProgressBatch(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; + } + PriceTrackTaskDetailVo detail = new PriceTrackTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + batch.getItems().add(detail); + } + return batch; + } + @Transactional public PriceTrackCreateTaskVo createTask(PriceTrackCreateTaskRequest request) { + if (request.isStatusMode() == request.isAsinMode()) throw new BusinessException("跟价模式必须二选一"); + if (request.isAsinMode() && (request.getAsinFiles() == null || request.getAsinFiles().isEmpty())) { + throw new BusinessException("自定义 ASIN 模式必须上传 ASIN 文件"); + } if (request.getUserId() == null || request.getUserId() <= 0) throw new BusinessException("user_id 不合法"); if (request.getItems() == null || request.getItems().isEmpty()) throw new BusinessException("items 不能为空"); @@ -195,13 +229,14 @@ public class PriceTrackTaskService { } // 汇总店铺名并查询需要跳过的 ASIN - List shopNames = uniqueItems.stream() - .map(PriceTrackMatchShopsVo.PriceTrackShopQueueItem::getShopName) - .filter(s -> s != null && !s.isBlank()) - .distinct() - .toList(); - Map> skipAsinsByShop = skipPriceAsinService.listSkipAsinsByShops(shopNames); - log.info("[price-track] createTask skipAsins shops={}", skipAsinsByShop.keySet()); + Map> skipAsinsByCountry = request.isAsinMode() + ? new LinkedHashMap<>() + : skipPriceAsinService.listAllSkipAsinsByCountry(); + Map>> asinRowsByCountry = request.isAsinMode() + ? parseAsinRowsByCountry(request.getAsinFiles(), request.getCountryCodes()) + : new LinkedHashMap<>(); + log.info("[price-track] createTask skipAsins countries={} asinMode={}", + skipAsinsByCountry.keySet(), request.isAsinMode()); // 创建任务记录 FileTaskEntity task = new FileTaskEntity(); @@ -242,7 +277,8 @@ public class PriceTrackTaskService { ctx.put("statusMode", request.isStatusMode()); ctx.put("asinMode", request.isAsinMode()); ctx.put("countryCodes", request.getCountryCodes()); - ctx.put("skipAsinsByShop", skipAsinsByShop); + ctx.put("skipAsinsByCountry", skipAsinsByCountry); + ctx.put("asinRowsByCountry", asinRowsByCountry); ctx.put("items", uniqueItems); task.setRequestJson(objectMapper.writeValueAsString(ctx)); task.setResultJson(objectMapper.writeValueAsString(snapshot)); @@ -257,6 +293,8 @@ public class PriceTrackTaskService { PriceTrackCreateTaskVo vo = new PriceTrackCreateTaskVo(); vo.setTaskId(task.getId()); vo.setItems(snapshot); + vo.setSkipAsinsByCountry(skipAsinsByCountry); + vo.setAsinRowsByCountry(asinRowsByCountry); return vo; } @@ -272,7 +310,7 @@ public class PriceTrackTaskService { } if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { log.warn("[price-track] submitResult rejected taskId={} status={}", taskId, task.getStatus()); - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } priceTrackTaskCacheService.touchTaskHeartbeat(taskId); @@ -452,6 +490,211 @@ public class PriceTrackTaskService { } } + public Map>> parseMatchAsinRowsByCountry(List asinFiles, List countryCodes) { + return parseAsinRowsByCountry(asinFiles, countryCodes); + } + + private Map>> parseAsinRowsByCountry(List asinFiles, List countryCodes) { + Map>> merged = new LinkedHashMap<>(); + if (asinFiles == null || asinFiles.isEmpty()) { + return merged; + } + for (String rawPath : asinFiles) { + if (rawPath == null || rawPath.isBlank()) { + continue; + } + File file = new File(rawPath); + if (!file.isFile()) { + throw new BusinessException("ASIN file not found: " + rawPath); + } + String lowerName = file.getName().toLowerCase(Locale.ROOT); + if (lowerName.endsWith(".csv")) { + mergeCountryRows(merged, parseCsvAsinRows(file, countryCodes)); + continue; + } + if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) { + mergeCountryRows(merged, parseWorkbookAsinRows(file, countryCodes)); + continue; + } + throw new BusinessException("Unsupported ASIN file type: " + file.getName()); + } + return merged; + } + + private Map>> parseWorkbookAsinRows(File file, List countryCodes) { + Map>> out = new LinkedHashMap<>(); + Map[] headerIndexHolder = new Map[]{Map.of()}; + String[] countryCodeHolder = new String[]{null}; + int[] sheetCount = new int[]{0}; + try { + ExcelStreamReader.readAllSheets(file, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) { + sheetCount[0]++; + countryCodeHolder[0] = resolveCountryCode(sheetName, countryCodes, false); + headerIndexHolder[0] = buildHeaderIndex(headerMap); + } + + @Override + public void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) { + String countryCode = countryCodeHolder[0]; + if (countryCode == null && sheetCount[0] == 1 && countryCodes != null && countryCodes.size() == 1) { + countryCode = countryCodes.get(0); + } + if (countryCode == null) { + return; + } + if (headerIndexHolder[0].isEmpty()) { + return; + } + Map item = extractAsinRow(rowMap, headerIndexHolder[0]); + if (!item.isEmpty()) { + out.computeIfAbsent(countryCode, key -> new ArrayList<>()).add(item); + } + } + }); + } catch (BusinessException ex) { + throw ex; + } catch (Exception ex) { + throw new BusinessException("Failed to parse ASIN workbook"); + } + return out; + } + + private Map>> parseCsvAsinRows(File file, List countryCodes) { + if (countryCodes == null || countryCodes.size() != 1) { + throw new BusinessException("CSV ASIN file requires exactly one selected country"); + } + Map>> out = new LinkedHashMap<>(); + List> rows = out.computeIfAbsent(countryCodes.get(0), key -> new ArrayList<>()); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + String headerLine = reader.readLine(); + if (headerLine == null) { + return out; + } + List headers = splitCsvLine(headerLine); + Map headerIndex = buildHeaderIndex(headers); + String line; + while ((line = reader.readLine()) != null) { + List values = splitCsvLine(line); + Map item = extractAsinRow(values, headerIndex); + if (!item.isEmpty()) { + rows.add(item); + } + } + } catch (BusinessException ex) { + throw ex; + } catch (Exception ex) { + throw new BusinessException("Failed to parse ASIN csv"); + } + return out; + } + + private void mergeCountryRows(Map>> target, Map>> incoming) { + for (Map.Entry>> entry : incoming.entrySet()) { + target.computeIfAbsent(entry.getKey(), key -> new ArrayList<>()).addAll(entry.getValue()); + } + } + + private String resolveCountryCode(String sheetName, List countryCodes, boolean singleSheetFallback) { + String normalized = normalizeHeaderText(sheetName).toUpperCase(Locale.ROOT); + for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) { + if (code.name().equals(normalized) || normalizeHeaderText(code.getSheetName()).equals(normalizeHeaderText(sheetName))) { + return code.name(); + } + } + if (singleSheetFallback && countryCodes != null && countryCodes.size() == 1) { + return countryCodes.get(0); + } + return null; + } + + private Map buildHeaderIndex(Map headerRow) { + List headers = new ArrayList<>(); + int maxIndex = headerRow.keySet().stream().mapToInt(Integer::intValue).max().orElse(-1); + for (int i = 0; i <= maxIndex; i++) { + headers.add(normalizeCellText(headerRow.get(i))); + } + return buildHeaderIndex(headers); + } + + private Map buildHeaderIndex(List headers) { + Map index = new LinkedHashMap<>(); + for (int i = 0; i < headers.size(); i++) { + String key = mapHeaderKey(headers.get(i)); + if (key != null && !index.containsKey(key)) { + index.put(key, i); + } + } + return index; + } + + private Map extractAsinRow(Map row, Map headerIndex) { + Map item = new LinkedHashMap<>(); + for (Map.Entry entry : headerIndex.entrySet()) { + item.put(entry.getKey(), normalizeCellText(row.get(entry.getValue()))); + } + return isEmptyAsinRow(item) ? Map.of() : item; + } + + private Map extractAsinRow(List values, Map headerIndex) { + Map item = new LinkedHashMap<>(); + for (Map.Entry entry : headerIndex.entrySet()) { + int idx = entry.getValue(); + item.put(entry.getKey(), idx >= 0 && idx < values.size() ? normalizeCellText(values.get(idx)) : ""); + } + return isEmptyAsinRow(item) ? Map.of() : item; + } + + private boolean isEmptyAsinRow(Map row) { + return row.values().stream().allMatch(value -> value == null || value.isBlank()); + } + + private String mapHeaderKey(String rawHeader) { + String header = normalizeHeaderText(rawHeader); + if (header.isEmpty()) { + return null; + } + return switch (header) { + case "店铺商城名称", "shopmallname" -> "shopMallName"; + case "asin" -> "asin"; + case "价格", "price" -> "price"; + case "推荐价", "recommendedprice" -> "recommendedPrice"; + case "最低价", "minimumprice" -> "minimumPrice"; + case "第一名", "firstplace" -> "firstPlace"; + case "第二名", "secondplace" -> "secondPlace"; + case "购物车店铺名", "cartshopname" -> "cartShopName"; + case "改价情况", "pricechangestatus" -> "priceChangeStatus"; + case "修改次数", "modifycount" -> "modifyCount"; + case "状态", "status" -> "status"; + default -> null; + }; + } + + private String normalizeCellText(String value) { + if (value == null) { + return ""; + } + return value.replace("\ufeff", "") + .replace("\u3000", " ") + .replace("\r", " ") + .replace("\n", " ") + .trim() + .replaceAll("\\s+", " "); + } + + private String normalizeHeaderText(String value) { + return normalizeCellText(value) + .replaceAll("\\s+", "") + .toLowerCase(Locale.ROOT); + } + + private List splitCsvLine(String line) { + return Arrays.stream((line == null ? "" : line).split(",", -1)) + .map(String::trim) + .toList(); + } + private List dedupeQueueItems(List raw) { Map byNorm = new LinkedHashMap<>(); for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : raw) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java index e401ccb..dad10af 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java @@ -159,6 +159,12 @@ public class ProductRiskResolveController { return ApiResponse.success(productRiskTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、时间和错误等轻量信息,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) { + return ApiResponse.success(productRiskTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation( summary = "Python 回传处理结果", diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java index f841151..837fd9f 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java @@ -147,6 +147,7 @@ public class ProductRiskTaskService { .eq(FileResultEntity::getTaskId, taskId) .eq(FileResultEntity::getModuleType, MODULE_TYPE)); fileTaskMapper.deleteById(taskId); + cleanupTaskCacheIfTerminal(taskId, "DELETE_EMPTY"); } /** @@ -283,6 +284,27 @@ public class ProductRiskTaskService { return batch; } + public ProductRiskTaskBatchVo getTaskProgressBatch(List taskIds) { + ProductRiskTaskBatchVo batch = new ProductRiskTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + batch.getItems().add(detail); + } + return batch; + } + public String resolveResultDownloadUrl(Long resultId, Long userId) { FileResultEntity entity = fileResultMapper.selectById(resultId); if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) { @@ -390,7 +412,7 @@ public class ProductRiskTaskService { if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { log.warn("[product-risk] submitResult rejected taskId={} status={} payloadShopCount={}", taskId, task.getStatus(), request.getShops() == null ? 0 : request.getShops().size()); - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } String oldStatus = task.getStatus(); 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 4d50b06..1efa657 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 @@ -44,7 +44,7 @@ public class ShopManageController { private final ShopManageGroupService shopManageGroupService; @GetMapping - @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名称、创建人进行筛选") + @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选") @ApiResponses({ @io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "200", @@ -56,14 +56,21 @@ public class ShopManageController { @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @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)); + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + return ApiResponse.success(shopManageService.page( + page, + pageSize, + groupId, + shopName, + operatorId, + Boolean.TRUE.equals(superAdmin))); } @PostMapping @Operation(summary = "新增店铺", description = "创建店铺记录,并写入创建人") public ApiResponse create( - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageCreateRequest request) { return ApiResponse.success("创建成功", @@ -71,10 +78,10 @@ public class ShopManageController { } @PutMapping("/{id}") - @Operation(summary = "更新店铺", description = "按 ID 更新店铺,普通管理员只能修改自己创建的数据") + @Operation(summary = "更新店铺", description = "按 ID 更新店铺") public ApiResponse update( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageUpdateRequest request) { return ApiResponse.success("更新成功", @@ -82,33 +89,42 @@ public class ShopManageController { } @DeleteMapping("/{id}") - @Operation(summary = "删除店铺", description = "按 ID 删除店铺,普通管理员只能删除自己创建的数据") + @Operation(summary = "删除店铺", description = "按 ID 删除店铺") public ApiResponse delete( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @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 = "普通管理员只返回自己创建的分组,超级管理员返回全部") + @Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部") public ApiResponse> listGroups( - @Parameter(description = "创建人用户 ID,普通管理员只传自己") @RequestParam(required = false) Long createdById) { - return ApiResponse.success(shopManageGroupService.list(createdById)); + @Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById, + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + if (Boolean.TRUE.equals(superAdmin)) { + return ApiResponse.success(shopManageGroupService.list(createdById)); + } + return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false)); } @PostMapping("/groups") @Operation(summary = "新增分组", description = "创建分组并写入创建人") - public ApiResponse createGroup(@Valid @RequestBody ShopManageGroupCreateRequest request) { - return ApiResponse.success("创建成功", shopManageGroupService.create(request)); + public ApiResponse createGroup( + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, + @Valid @RequestBody ShopManageGroupCreateRequest request) { + return ApiResponse.success("创建成功", + shopManageGroupService.create(request, operatorId, Boolean.TRUE.equals(superAdmin))); } @PutMapping("/groups/{id}") - @Operation(summary = "更新分组", description = "普通管理员只能修改自己创建的分组") + @Operation(summary = "更新分组", description = "普通管理员只能修改自己可访问的分组") public ApiResponse updateGroup( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageGroupUpdateRequest request) { return ApiResponse.success("更新成功", @@ -116,10 +132,10 @@ public class ShopManageController { } @DeleteMapping("/groups/{id}") - @Operation(summary = "删除分组", description = "普通管理员只能删除自己创建的分组") + @Operation(summary = "删除分组", description = "普通管理员只能删除自己可访问的分组") public ApiResponse deleteGroup( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @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); 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 d840a87..74c951b 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 @@ -1,8 +1,8 @@ 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.dto.SkipPriceAsinCreateRequest; 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; @@ -36,14 +36,27 @@ public class SkipPriceAsinController { @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @Parameter(description = "分组ID") @RequestParam(required = false) Long groupId, @Parameter(description = "店铺名") @RequestParam(required = false) String shopName, - @Parameter(description = "ASIN") @RequestParam(required = false) String asin) { - return ApiResponse.success(skipPriceAsinService.page(page, pageSize, groupId, shopName, asin)); + @Parameter(description = "ASIN") @RequestParam(required = false) String asin, + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + return ApiResponse.success(skipPriceAsinService.page( + page, + pageSize, + groupId, + shopName, + asin, + operatorId, + Boolean.TRUE.equals(superAdmin))); } @PostMapping @Operation(summary = "新增或覆盖跳过跟价 ASIN") - public ApiResponse create(@Valid @RequestBody SkipPriceAsinCreateRequest request) { - return ApiResponse.success("保存成功", skipPriceAsinService.createOrUpdate(request)); + public ApiResponse create( + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, + @Valid @RequestBody SkipPriceAsinCreateRequest request) { + return ApiResponse.success("保存成功", + skipPriceAsinService.createOrUpdate(request, operatorId, Boolean.TRUE.equals(superAdmin))); } @PutMapping("/{id}/countries/{country}") @@ -51,16 +64,25 @@ public class SkipPriceAsinController { public ApiResponse updateCountry( @Parameter(description = "主键ID", required = true) @PathVariable Long id, @Parameter(description = "国家编码", required = true) @PathVariable String country, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody SkipPriceAsinCountryUpdateRequest request) { - return ApiResponse.success("保存成功", skipPriceAsinService.updateCountry(id, country, request.getAsin())); + return ApiResponse.success("保存成功", skipPriceAsinService.updateCountry( + id, + country, + request.getAsin(), + operatorId, + Boolean.TRUE.equals(superAdmin))); } @DeleteMapping("/{id}/countries/{country}") @Operation(summary = "删除指定国家的跳过跟价 ASIN") public ApiResponse deleteCountry( @Parameter(description = "主键ID", required = true) @PathVariable Long id, - @Parameter(description = "国家编码", required = true) @PathVariable String country) { - skipPriceAsinService.deleteCountry(id, country); + @Parameter(description = "国家编码", required = true) @PathVariable String country, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + skipPriceAsinService.deleteCountry(id, country, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); } } 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 62d2d5b..236cba7 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 @@ -12,7 +12,11 @@ public class ShopManageGroupCreateRequest { @NotBlank(message = "分组名称不能为空") private String groupName; - @Schema(description = "创建人用户 ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "关联用户ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "关联用户不能为空") + private Long userId; + + @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 1469aca..cfa0f92 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 @@ -2,6 +2,7 @@ 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 @@ -10,4 +11,8 @@ public class ShopManageGroupUpdateRequest { @Schema(description = "分组名称", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "分组名称不能为空") private String groupName; + + @Schema(description = "关联用户ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "关联用户不能为空") + private Long userId; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java index 537d03e..22d666d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java @@ -6,6 +6,7 @@ import jakarta.validation.constraints.NotNull; import lombok.Data; import java.util.List; +import java.util.Map; @Data public class SkipPriceAsinCreateRequest { @@ -19,6 +20,13 @@ public class SkipPriceAsinCreateRequest { @NotEmpty(message = "请至少选择一个国家") private List countries; - @NotBlank(message = "ASIN 不能为空") + /** + * 兼容旧请求: 选中的国家共用同一个 ASIN。 + */ private String asin; + + /** + * 新请求: 每个国家对应独立 ASIN,例如 {"DE":"B0...", "UK":"B0..."}。 + */ + private Map asinMappings; } 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 623de76..33e4dee 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 @@ -15,6 +15,8 @@ public class ShopManageGroupEntity { @TableId(type = IdType.AUTO) private Long id; private String groupName; + @TableField("user_id") + private Long userId; @TableField("created_by_id") private Long createdById; private LocalDateTime createdAt; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java index a3da49e..3f6de7f 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java @@ -8,6 +8,8 @@ import java.time.LocalDateTime; public class ShopManageGroupItemVo { private Long id; private String groupName; + private Long userId; + private String username; 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 95d2314..b18f70d 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 @@ -2,6 +2,8 @@ package com.nanri.aiimage.modules.shopkey.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper; +import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity; 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; @@ -13,7 +15,9 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; @Service @RequiredArgsConstructor @@ -21,6 +25,7 @@ public class ShopManageGroupService { private final ShopManageGroupMapper groupMapper; private final ShopManageMapper shopManageMapper; + private final AdminUserMapper adminUserMapper; public List list() { return list(null); @@ -35,13 +40,56 @@ public class ShopManageGroupService { .toList(); } + public List listAccessible(Long operatorId, boolean superAdmin) { + if (superAdmin) { + return list(); + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + return groupMapper.selectList(new LambdaQueryWrapper() + .and(wrapper -> wrapper + .eq(ShopManageGroupEntity::getCreatedById, normalizedOperatorId) + .or() + .eq(ShopManageGroupEntity::getUserId, normalizedOperatorId)) + .orderByAsc(ShopManageGroupEntity::getId)) + .stream() + .map(this::toVo) + .toList(); + } + + public Set listAccessibleGroupIds(Long operatorId, boolean superAdmin) { + if (superAdmin) { + return groupMapper.selectList(new LambdaQueryWrapper() + .select(ShopManageGroupEntity::getId)) + .stream() + .map(ShopManageGroupEntity::getId) + .filter(id -> id != null && id > 0) + .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + return groupMapper.selectList(new LambdaQueryWrapper() + .select(ShopManageGroupEntity::getId) + .and(wrapper -> wrapper + .eq(ShopManageGroupEntity::getCreatedById, normalizedOperatorId) + .or() + .eq(ShopManageGroupEntity::getUserId, normalizedOperatorId))) + .stream() + .map(ShopManageGroupEntity::getId) + .filter(id -> id != null && id > 0) + .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); + } + @Transactional - public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request) { + public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request, Long operatorId, boolean superAdmin) { Long createdById = normalizePositiveId(request.getCreatedById(), "创建人不能为空"); + AdminUserEntity bindUser = getBindableUser(request.getUserId(), operatorId, superAdmin); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, null, createdById, false); + ensureGroupNameMatchesUser(groupName, bindUser); + ensureGroupNameUnique(groupName, null); + ensureUserUnique(request.getUserId(), null); + ShopManageGroupEntity entity = new ShopManageGroupEntity(); entity.setGroupName(groupName); + entity.setUserId(bindUser.getId()); entity.setCreatedById(createdById); groupMapper.insert(entity); return toVo(getById(entity.getId())); @@ -51,9 +99,14 @@ public class ShopManageGroupService { public ShopManageGroupItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageGroupUpdateRequest request) { ShopManageGroupEntity entity = getById(id); validateOwnership(entity, operatorId, superAdmin); + AdminUserEntity bindUser = getBindableUser(request.getUserId(), operatorId, superAdmin); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, id, operatorId, superAdmin); + ensureGroupNameMatchesUser(groupName, bindUser); + ensureGroupNameUnique(groupName, id); + ensureUserUnique(bindUser.getId(), id); + entity.setGroupName(groupName); + entity.setUserId(bindUser.getId()); groupMapper.updateById(entity); return toVo(getById(id)); } @@ -84,12 +137,9 @@ public class ShopManageGroupService { return entity; } - private void ensureGroupNameUnique(String groupName, Long excludeId, Long operatorId, boolean superAdmin) { + private void ensureGroupNameUnique(String groupName, Long excludeId) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(ShopManageGroupEntity::getGroupName, groupName); - if (!superAdmin) { - query.eq(ShopManageGroupEntity::getCreatedById, normalizePositiveId(operatorId, "操作人不能为空")); - } if (excludeId != null) { query.ne(ShopManageGroupEntity::getId, excludeId); } @@ -99,16 +149,54 @@ public class ShopManageGroupService { } } + private void ensureUserUnique(Long userId, Long excludeId) { + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(ShopManageGroupEntity::getUserId, userId); + if (excludeId != null) { + query.ne(ShopManageGroupEntity::getId, excludeId); + } + Long count = groupMapper.selectCount(query); + if (count != null && count > 0) { + throw new BusinessException("该用户已绑定分组"); + } + } + + private void ensureGroupNameMatchesUser(String groupName, AdminUserEntity bindUser) { + if (bindUser == null || bindUser.getUsername() == null || !groupName.equals(bindUser.getUsername().trim())) { + throw new BusinessException("分组名称必须与关联用户名一致"); + } + } + 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("只能操作自己创建的分组数据"); + boolean createdBySelf = entity.getCreatedById() != null && entity.getCreatedById().equals(normalizedOperatorId); + boolean boundToSelf = entity.getUserId() != null && entity.getUserId().equals(normalizedOperatorId); + if (!createdBySelf && !boundToSelf) { + throw new BusinessException("只能操作自己有权限的分组数据"); } } + private AdminUserEntity getBindableUser(Long userId, Long operatorId, boolean superAdmin) { + Long normalizedUserId = normalizePositiveId(userId, "关联用户不能为空"); + AdminUserEntity user = adminUserMapper.selectById(normalizedUserId); + if (user == null) { + throw new BusinessException("关联用户不存在"); + } + if (superAdmin) { + return user; + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + boolean self = user.getId() != null && user.getId().equals(normalizedOperatorId); + boolean createdBySelf = user.getCreatedById() != null && user.getCreatedById().equals(normalizedOperatorId); + if (!self && !createdBySelf) { + throw new BusinessException("只能关联自己可见的用户"); + } + return user; + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty()) { @@ -128,6 +216,9 @@ public class ShopManageGroupService { ShopManageGroupItemVo vo = new ShopManageGroupItemVo(); vo.setId(entity.getId()); vo.setGroupName(entity.getGroupName()); + vo.setUserId(entity.getUserId()); + AdminUserEntity bindUser = entity.getUserId() == null ? null : adminUserMapper.selectById(entity.getUserId()); + vo.setUsername(bindUser == null ? "" : (bindUser.getUsername() == null ? "" : bindUser.getUsername())); vo.setCreatedAt(entity.getCreatedAt()); vo.setUpdatedAt(entity.getUpdatedAt()); return vo; 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 f6ab333..4f72fb6 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 @@ -18,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; @Service @RequiredArgsConstructor @@ -27,24 +28,27 @@ public class ShopManageService { private final ShopManageGroupService shopManageGroupService; private final ShopCredentialCryptoService shopCredentialCryptoService; - public ShopManagePageVo page(long page, long pageSize) { - 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) { + public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, boolean superAdmin) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = shopName == null ? "" : shopName.trim(); + Set accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); 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); + + if (!superAdmin) { + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + query.and(wrapper -> { + wrapper.eq(ShopManageEntity::getCreatedById, normalizedOperatorId); + if (!accessibleGroupIds.isEmpty()) { + wrapper.or().in(ShopManageEntity::getGroupId, accessibleGroupIds); + } + }); + } + Long total = shopManageMapper.selectCount(query); List rows = shopManageMapper .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); @@ -90,7 +94,7 @@ public class ShopManageService { @Transactional public ShopManageItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageUpdateRequest request) { ShopManageEntity entity = getById(id); - validateOwnership(entity, operatorId, superAdmin); + validateGroupAccess(entity, operatorId, superAdmin); ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); String shopName = normalizeRequired(request.getShopName(), "店铺名称不能为空"); String mallName = normalizeRequired(request.getMallName(), "商城名称不能为空"); @@ -110,7 +114,7 @@ public class ShopManageService { @Transactional public void delete(Long id, Long operatorId, boolean superAdmin) { ShopManageEntity entity = getById(id); - validateOwnership(entity, operatorId, superAdmin); + validateGroupAccess(entity, operatorId, superAdmin); shopManageMapper.deleteById(entity.getId()); } @@ -146,14 +150,8 @@ 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 void validateGroupAccess(ShopManageEntity entity, Long operatorId, boolean superAdmin) { + shopManageGroupService.getAccessibleById(entity.getGroupId(), operatorId, superAdmin); } private String normalizeRequired(String value, String message) { @@ -208,7 +206,6 @@ public class ShopManageService { vo.setMallName(entity.getMallName()); vo.setAccount(entity.getAccount()); String masked = entity.getPassword() == null || entity.getPassword().isBlank() ? "" : "******"; - // 兼容旧前端字段:password 继续返回脱敏值 vo.setPassword(masked); vo.setPasswordMasked(masked); vo.setCreatedAt(entity.getCreatedAt()); 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 8a95f2d..0407766 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 @@ -28,11 +28,13 @@ public class SkipPriceAsinService { private final SkipPriceAsinMapper skipPriceAsinMapper; private final ShopManageGroupService shopManageGroupService; - public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin) { + public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin, + Long operatorId, boolean superAdmin) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = normalizeBlank(shopName); String safeAsin = normalizeBlank(asin); + Set accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId) @@ -45,6 +47,14 @@ public class SkipPriceAsinService { .or().like(SkipPriceAsinEntity::getAsinEs, safeAsin)) .orderByDesc(SkipPriceAsinEntity::getId); + if (!superAdmin) { + if (accessibleGroupIds.isEmpty()) { + query.eq(SkipPriceAsinEntity::getId, -1L); + } else { + query.in(SkipPriceAsinEntity::getGroupId, accessibleGroupIds); + } + } + Long total = skipPriceAsinMapper.selectCount(query); List rows = skipPriceAsinMapper .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); @@ -64,11 +74,11 @@ public class SkipPriceAsinService { } @Transactional - public SkipPriceAsinItemVo createOrUpdate(SkipPriceAsinCreateRequest request) { - ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId()); + public SkipPriceAsinItemVo createOrUpdate(SkipPriceAsinCreateRequest request, Long operatorId, boolean superAdmin) { + ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空"); - String asin = normalizeAsin(request.getAsin()); Set countries = normalizeCountries(request.getCountries()); + Map countryAsinMap = normalizeCountryAsinMap(countries, request); SkipPriceAsinEntity entity = skipPriceAsinMapper.selectOne(new LambdaQueryWrapper() .eq(SkipPriceAsinEntity::getGroupId, group.getId()) @@ -80,8 +90,8 @@ public class SkipPriceAsinService { entity.setShopName(shopName); } - for (String country : countries) { - setCountryAsin(entity, country, asin); + for (Map.Entry entry : countryAsinMap.entrySet()) { + setCountryAsin(entity, entry.getKey(), entry.getValue()); } if (entity.getId() == null) { @@ -94,8 +104,9 @@ public class SkipPriceAsinService { } @Transactional - public void deleteCountry(Long id, String country) { + public void deleteCountry(Long id, String country, Long operatorId, boolean superAdmin) { SkipPriceAsinEntity entity = getById(id); + validateGroupAccess(entity, operatorId, superAdmin); String normalizedCountry = normalizeCountry(country); setCountryAsin(entity, normalizedCountry, ""); if (isEmptyRow(entity)) { @@ -106,8 +117,9 @@ public class SkipPriceAsinService { } @Transactional - public SkipPriceAsinItemVo updateCountry(Long id, String country, String asin) { + public SkipPriceAsinItemVo updateCountry(Long id, String country, String asin, Long operatorId, boolean superAdmin) { SkipPriceAsinEntity entity = getById(id); + validateGroupAccess(entity, operatorId, superAdmin); String normalizedCountry = normalizeCountry(country); String normalizedAsin = normalizeAsin(asin); setCountryAsin(entity, normalizedCountry, normalizedAsin); @@ -131,6 +143,10 @@ public class SkipPriceAsinService { return entity; } + private void validateGroupAccess(SkipPriceAsinEntity entity, Long operatorId, boolean superAdmin) { + shopManageGroupService.getAccessibleById(entity.getGroupId(), operatorId, superAdmin); + } + private SkipPriceAsinItemVo toItemVo(SkipPriceAsinEntity entity, String groupName) { SkipPriceAsinItemVo vo = new SkipPriceAsinItemVo(); vo.setId(entity.getId()); @@ -176,6 +192,27 @@ public class SkipPriceAsinService { return normalized; } + private Map normalizeCountryAsinMap(Set countries, SkipPriceAsinCreateRequest request) { + LinkedHashMap normalized = new LinkedHashMap<>(); + Map requestMappings = request.getAsinMappings(); + if (requestMappings != null && !requestMappings.isEmpty()) { + for (String country : countries) { + String asin = requestMappings.get(country); + if (asin == null) { + asin = requestMappings.get(country.toLowerCase(Locale.ROOT)); + } + normalized.put(country, normalizeAsin(asin)); + } + return normalized; + } + + String asin = normalizeAsin(request.getAsin()); + for (String country : countries) { + normalized.put(country, asin); + } + return normalized; + } + private String normalizeCountry(String country) { String normalized = normalizeBlank(country).toUpperCase(Locale.ROOT); if (!SUPPORTED_COUNTRIES.contains(normalized)) { @@ -228,10 +265,6 @@ public class SkipPriceAsinService { && normalizeBlank(entity.getAsinEs()).isEmpty(); } - /** - * 按店铺名列表批量查询跳过跟价ASIN,返回 Map{shopName -> {countryCode -> asin列表}} - * 用于跟价任务创建时将skip ASIN数据下发给Python队列 - */ public Map> listSkipAsinsByShops(List shopNames) { if (shopNames == null || shopNames.isEmpty()) { return Map.of(); @@ -252,4 +285,37 @@ public class SkipPriceAsinService { } return result; } + + public Map> listAllSkipAsinsByCountry() { + List rows = skipPriceAsinMapper.selectList( + new LambdaQueryWrapper() + .orderByDesc(SkipPriceAsinEntity::getId)); + Map> grouped = new LinkedHashMap<>(); + grouped.put("DE", new LinkedHashSet<>()); + grouped.put("UK", new LinkedHashSet<>()); + grouped.put("FR", new LinkedHashSet<>()); + grouped.put("IT", new LinkedHashSet<>()); + grouped.put("ES", new LinkedHashSet<>()); + + for (SkipPriceAsinEntity row : rows) { + addCountryAsin(grouped.get("DE"), row.getAsinDe()); + addCountryAsin(grouped.get("UK"), row.getAsinUk()); + addCountryAsin(grouped.get("FR"), row.getAsinFr()); + addCountryAsin(grouped.get("IT"), row.getAsinIt()); + addCountryAsin(grouped.get("ES"), row.getAsinEs()); + } + + Map> result = new LinkedHashMap<>(); + for (Map.Entry> entry : grouped.entrySet()) { + result.put(entry.getKey(), List.copyOf(entry.getValue())); + } + return result; + } + + private void addCountryAsin(Set bucket, String asin) { + String normalized = normalizeBlank(asin); + if (!normalized.isEmpty()) { + bucket.add(normalized); + } + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java index 0e4d174..afd9300 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java @@ -163,6 +163,12 @@ public class ShopMatchController { return ApiResponse.success(shopMatchTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、阶段信息与时间等轻量字段,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) { + return ApiResponse.success(shopMatchTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation(summary = "提交匹配结果", description = "Python 可多次分批回传结果;后端会组装文件并在超时场景自动补偿收尾。") public ApiResponse submitResult( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java index 31a908a..1f98db7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java @@ -5,10 +5,17 @@ import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchShopPayloadDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; import java.time.Duration; +import java.util.Comparator; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; @@ -19,21 +26,29 @@ public class ShopMatchTaskCacheService { private static final long PAYLOAD_TTL_HOURS = 24; - private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; public ShopMatchShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) { if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { return null; } - Object raw = stringRedisTemplate.opsForHash().get(buildShopPayloadKey(taskId), shopKey); - if (!(raw instanceof String json) || json.isBlank()) { + Path file = buildShopPayloadFile(taskId, shopKey); + if (!Files.isRegularFile(file)) { return null; } try { - return objectMapper.readValue(json, ShopMatchShopPayloadDto.class); + PayloadFile payloadFile = objectMapper.readValue(Files.readString(file), PayloadFile.class); + if (payloadFile == null || payloadFile.payload == null) { + return null; + } + if (payloadFile.shopKey == null || !shopKey.equals(payloadFile.shopKey)) { + log.warn("[shop-match] payload file shop key mismatch taskId={} shopKey={} storedKey={}", + taskId, shopKey, payloadFile.shopKey); + return null; + } + return payloadFile.payload; } catch (Exception ex) { - throw new BusinessException("读取匹配店铺缓存失败"); + throw new BusinessException("璇诲彇鍖归厤搴楅摵缂撳瓨澶辫触"); } } @@ -42,11 +57,16 @@ public class ShopMatchTaskCacheService { return; } try { - String key = buildShopPayloadKey(taskId); - stringRedisTemplate.opsForHash().put(key, shopKey, objectMapper.writeValueAsString(payload)); - stringRedisTemplate.expire(key, Duration.ofHours(PAYLOAD_TTL_HOURS)); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildShopPayloadFile(taskId, shopKey), + objectMapper.writeValueAsString(new PayloadFile(shopKey, payload)), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); } catch (Exception ex) { - throw new BusinessException("暂存匹配店铺结果失败"); + throw new BusinessException("鏆傚瓨鍖归厤搴楅摵缁撴灉澶辫触"); } } @@ -54,25 +74,52 @@ public class ShopMatchTaskCacheService { if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { return; } - stringRedisTemplate.opsForHash().delete(buildShopPayloadKey(taskId), shopKey); + try { + Files.deleteIfExists(buildShopPayloadFile(taskId, shopKey)); + } catch (IOException ex) { + log.warn("[shop-match] delete shop payload failed taskId={} shopKey={} msg={}", taskId, shopKey, ex.getMessage()); + } } public Map getAllShopMergedPayload(Long taskId) { try { - Map raw = stringRedisTemplate.opsForHash().entries(buildShopPayloadKey(taskId)); - if (raw == null || raw.isEmpty()) { + Path taskDir = buildTaskDir(taskId); + if (!Files.isDirectory(taskDir)) { return Map.of(); } LinkedHashMap out = new LinkedHashMap<>(); - for (Map.Entry entry : raw.entrySet()) { - if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String val) || val.isBlank()) { - continue; + try (var stream = Files.list(taskDir)) { + for (Path path : stream + .filter(file -> file.getFileName().toString().endsWith(".json")) + .sorted(Comparator.comparing(file -> file.getFileName().toString())) + .toList()) { + PayloadFile payloadFile = objectMapper.readValue(Files.readString(path), PayloadFile.class); + if (payloadFile == null || payloadFile.shopKey == null || payloadFile.shopKey.isBlank() || payloadFile.payload == null) { + continue; + } + out.put(payloadFile.shopKey, payloadFile.payload); } - out.put(key, objectMapper.readValue(val, ShopMatchShopPayloadDto.class)); } return out; } catch (Exception ex) { - throw new BusinessException("读取匹配店铺缓存失败"); + throw new BusinessException("璇诲彇鍖归厤搴楅摵缂撳瓨澶辫触"); + } + } + + public boolean hasAnyShopMergedPayload(Long taskId) { + if (taskId == null || taskId <= 0) { + return false; + } + Path taskDir = buildTaskDir(taskId); + if (!Files.isDirectory(taskDir)) { + return false; + } + try (var stream = Files.list(taskDir)) { + return stream.anyMatch(file -> Files.isRegularFile(file) + && file.getFileName().toString().endsWith(".json")); + } catch (IOException ex) { + log.warn("[shop-match] scan task cache failed taskId={} msg={}", taskId, ex.getMessage()); + return false; } } @@ -81,13 +128,57 @@ public class ShopMatchTaskCacheService { return; } try { - stringRedisTemplate.delete(buildShopPayloadKey(taskId)); + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ex) { + log.warn("[shop-match] delete task cache path failed taskId={} path={} msg={}", + taskId, path, ex.getMessage()); + } + }); + } } catch (Exception ex) { log.warn("[shop-match] delete task cache failed taskId={} msg={}", taskId, ex.getMessage()); } } - private String buildShopPayloadKey(Long taskId) { - return "shop-match:task:shop-payload:" + taskId; + public Duration getPayloadTtl() { + return Duration.ofHours(PAYLOAD_TTL_HOURS); + } + + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "shop-match-cache", String.valueOf(taskId)); + } + + private Path buildShopPayloadFile(Long taskId, String shopKey) { + return buildTaskDir(taskId).resolve(hashShopKey(shopKey) + ".json"); + } + + private String hashShopKey(String shopKey) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(shopKey.trim().getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(bytes); + } catch (Exception ex) { + throw new IllegalStateException("failed to hash shop key", ex); + } + } + + private static class PayloadFile { + public String shopKey; + public ShopMatchShopPayloadDto payload; + + public PayloadFile() { + } + + public PayloadFile(String shopKey, ShopMatchShopPayloadDto payload) { + this.shopKey = shopKey; + this.payload = payload; + } } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java index b37b684..c308662 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java @@ -185,6 +185,25 @@ public class ShopMatchTaskService { return batch; } + public ProductRiskTaskBatchVo getTaskProgressBatch(List taskIds) { + ProductRiskTaskBatchVo batch = new ProductRiskTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + batch.getItems().add(buildTaskProgressDetail(task)); + } + return batch; + } + public String resolveResultDownloadUrl(Long resultId, Long userId) { FileResultEntity entity = fileResultMapper.selectById(resultId); if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) { @@ -376,7 +395,7 @@ public class ShopMatchTaskService { throw new BusinessException("任务不存在"); } if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper() @@ -595,7 +614,11 @@ public class ShopMatchTaskService { task.setSuccessFileCount(ok); task.setFailedFileCount(fail); task.setUpdatedAt(now()); - if (!allDone) { + if (shouldRemainRunningUntilNextStage(task)) { + task.setStatus("RUNNING"); + task.setErrorMessage(null); + task.setFinishedAt(null); + } else if (!allDone) { task.setStatus("RUNNING"); task.setErrorMessage(null); task.setFinishedAt(null); @@ -623,6 +646,18 @@ public class ShopMatchTaskService { } } + private boolean shouldRemainRunningUntilNextStage(FileTaskEntity task) { + ShopMatchCreateTaskRequest request = parseTaskRequestSilently(task); + if (request == null || request.getScheduleTimes() == null || request.getScheduleTimes().isEmpty()) { + return false; + } + Integer activeStageIndex = request.getActiveStageIndex(); + if (activeStageIndex == null) { + return false; + } + return activeStageIndex < request.getScheduleTimes().size() - 1; + } + private ProductRiskTaskDetailVo buildTaskDetail(FileTaskEntity task) { ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); detail.setTask(toTaskItemVo(task)); @@ -636,6 +671,12 @@ public class ShopMatchTaskService { return detail; } + private ProductRiskTaskDetailVo buildTaskProgressDetail(FileTaskEntity task) { + ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + return detail; + } + private List buildSnapshotFromDb(Long taskId, String taskStatus) { List rows = fileResultMapper.selectList(new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java index 524de90..ad2477e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java @@ -5,6 +5,7 @@ import cn.hutool.core.util.IdUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.util.ExcelStreamReader; import com.nanri.aiimage.config.StorageProperties; import com.nanri.aiimage.modules.file.service.oss.OssStorageService; import com.nanri.aiimage.modules.split.model.dto.SplitRunRequest; @@ -17,20 +18,14 @@ 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 lombok.RequiredArgsConstructor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.nio.file.Files; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -217,84 +212,119 @@ public class SplitRunService { String originalFilename, SplitRunRequest request ) throws Exception { - DataFormatter formatter = new DataFormatter(); - try (FileInputStream fis = new FileInputStream(inputFile); - Workbook workbook = WorkbookFactory.create(fis)) { - Sheet sheet = workbook.getSheetAt(0); - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - throw new BusinessException("Excel header row is empty."); - } - - Map headerMap = buildHeaderMap(headerRow, formatter); - List missing = request.getSelectedColumns().stream() - .filter(column -> !headerMap.containsKey(column)) - .toList(); - if (!missing.isEmpty()) { - throw new BusinessException("Missing required columns: " + String.join(", ", missing)); - } - - List> rowsData = new ArrayList<>(); - for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - if (row == null) { - continue; - } - List projected = new ArrayList<>(); - for (String column : request.getSelectedColumns()) { - Integer sourceIndex = headerMap.get(column); - String value = sourceIndex == null - ? "" - : normalizeCellText(formatter.formatCellValue(row.getCell(sourceIndex))); - projected.add(value); - } - rowsData.add(projected); - } - - if (rowsData.isEmpty()) { - throw new BusinessException("No data rows available for splitting."); - } - - List>> chunks = buildChunks(rowsData, request); - File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "split-result")); - String sourceStem = FileUtil.mainName(originalFilename); - List results = new ArrayList<>(); - - for (int i = 0; i < chunks.size(); i++) { - File outputFile = buildNamedOutputFile(outputDir, sourceStem + "_split_" + (i + 1) + ".xlsx"); - try (XSSFWorkbook outputWorkbook = new XSSFWorkbook()) { - Sheet outputSheet = outputWorkbook.createSheet(sheet.getSheetName()); - Row outputHeaderRow = outputSheet.createRow(0); - for (int colIndex = 0; colIndex < request.getSelectedColumns().size(); colIndex++) { - outputHeaderRow.createCell(colIndex).setCellValue(request.getSelectedColumns().get(colIndex)); - } - int outputRowIndex = 1; - for (List rowValues : chunks.get(i)) { - Row outputRow = outputSheet.createRow(outputRowIndex++); - for (int colIndex = 0; colIndex < rowValues.size(); colIndex++) { - outputRow.createCell(colIndex).setCellValue(rowValues.get(colIndex)); - } - } - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - outputWorkbook.write(fos); - } - } - results.add(new SplitChunkResult(outputFile, chunks.get(i).size())); - } - - return results; + CountResult countResult = countSplitRows(inputFile, request.getSelectedColumns()); + if (countResult.rowCount() <= 0) { + throw new BusinessException("No data rows available for splitting."); } + + List chunkSizes = buildChunkSizes(countResult.rowCount(), request); + File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "split-result")); + String sourceStem = FileUtil.mainName(originalFilename); + List results = new ArrayList<>(); + List writers = new ArrayList<>(); + try { + for (int i = 0; i < chunkSizes.size(); i++) { + File outputFile = buildNamedOutputFile(outputDir, sourceStem + "_split_" + (i + 1) + ".xlsx"); + ChunkWriter writer = new ChunkWriter(outputFile, countResult.sheetName(), request.getSelectedColumns(), chunkSizes.get(i)); + writers.add(writer); + results.add(new SplitChunkResult(outputFile, chunkSizes.get(i))); + } + + Map[] headerMapHolder = new Map[]{null}; + int[] chunkIndex = new int[]{0}; + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) { + Map resolvedHeaderMap = buildHeaderMap(headerMap); + List missing = request.getSelectedColumns().stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + headerMapHolder[0] = resolvedHeaderMap; + } + + @Override + public void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) throws Exception { + if (chunkIndex[0] >= writers.size()) { + return; + } + Map resolvedHeaderMap = headerMapHolder[0]; + if (resolvedHeaderMap == null) { + throw new BusinessException("Excel header row is empty."); + } + List projected = new ArrayList<>(); + for (String column : request.getSelectedColumns()) { + Integer sourceIndex = resolvedHeaderMap.get(column); + projected.add(sourceIndex == null ? "" : normalizeCellText(rowMap.get(sourceIndex))); + } + ChunkWriter writer = writers.get(chunkIndex[0]); + writer.writeRow(projected); + if (writer.isFull()) { + chunkIndex[0]++; + } + } + }); + } finally { + IOException closeException = null; + for (ChunkWriter writer : writers) { + try { + writer.close(); + } catch (IOException ex) { + if (closeException == null) { + closeException = ex; + } + } + } + if (closeException != null) { + throw closeException; + } + } + + return results; } - private Map buildHeaderMap(Row headerRow, DataFormatter formatter) { + private CountResult countSplitRows(File inputFile, List selectedColumns) throws IOException { + int[] rowCount = new int[]{0}; + String[] sheetName = new String[]{"Sheet1"}; + boolean[] headerRead = new boolean[]{false}; + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String currentSheetName, Integer sheetNo, Map headerMap) { + Map resolvedHeaderMap = buildHeaderMap(headerMap); + List missing = selectedColumns.stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + sheetName[0] = currentSheetName == null || currentSheetName.isBlank() ? "Sheet1" : currentSheetName; + headerRead[0] = true; + } + + @Override + public void onRow(String currentSheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) { + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + rowCount[0]++; + } + }); + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + return new CountResult(rowCount[0], sheetName[0]); + } + + private Map buildHeaderMap(Map headerRow) { Map headerMap = new HashMap<>(); - for (int i = 0; i < headerRow.getLastCellNum(); i++) { - Cell cell = headerRow.getCell(i); - String value = normalizeHeaderName(cell == null ? null : formatter.formatCellValue(cell)); + for (Map.Entry entry : headerRow.entrySet()) { + String value = normalizeHeaderName(entry.getValue()); if (value.isBlank() || headerMap.containsKey(value)) { continue; } - headerMap.put(value, i); + headerMap.put(value, entry.getKey()); if (HEADER_STOP_COLUMN.equals(value)) { break; } @@ -302,14 +332,13 @@ public class SplitRunService { return headerMap; } - private List>> buildChunks(List> rowsData, SplitRunRequest request) { - int totalRows = rowsData.size(); - List>> chunks = new ArrayList<>(); + private List buildChunkSizes(int totalRows, SplitRunRequest request) { + List chunks = new ArrayList<>(); if (SPLIT_MODE_ROWS_PER_FILE.equals(request.getSplitMode())) { int chunkSize = request.getRowsPerFile(); for (int i = 0; i < totalRows; i += chunkSize) { - chunks.add(rowsData.subList(i, Math.min(i + chunkSize, totalRows))); + chunks.add(Math.min(chunkSize, totalRows - i)); } return chunks; } @@ -317,12 +346,8 @@ public class SplitRunService { int actualParts = Math.min(request.getParts(), totalRows); int base = totalRows / actualParts; int remainder = totalRows % actualParts; - int start = 0; for (int i = 0; i < actualParts; i++) { - int size = base + (i < remainder ? 1 : 0); - int end = start + size; - chunks.add(rowsData.subList(start, end)); - start = end; + chunks.add(base + (i < remainder ? 1 : 0)); } return chunks; } @@ -448,4 +473,48 @@ public class SplitRunService { private record TaskSplitChunkResult(String relativePath, String sourceFilename, File outputFile, int rowCount) { } + + private record CountResult(int rowCount, String sheetName) { + } + + private static final class ChunkWriter implements AutoCloseable { + private final File outputFile; + private final SXSSFWorkbook workbook; + private final org.apache.poi.ss.usermodel.Sheet sheet; + private final int rowLimit; + private int writtenRows; + + private ChunkWriter(File outputFile, String sheetName, List columns, int rowLimit) { + this.outputFile = outputFile; + this.rowLimit = rowLimit; + this.workbook = new SXSSFWorkbook(200); + this.sheet = workbook.createSheet(sheetName == null || sheetName.isBlank() ? "Sheet1" : sheetName); + org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0); + for (int i = 0; i < columns.size(); i++) { + headerRow.createCell(i).setCellValue(columns.get(i)); + } + } + + private void writeRow(List values) { + org.apache.poi.ss.usermodel.Row outputRow = sheet.createRow(writtenRows + 1); + for (int colIndex = 0; colIndex < values.size(); colIndex++) { + outputRow.createCell(colIndex).setCellValue(values.get(colIndex)); + } + writtenRows++; + } + + private boolean isFull() { + return writtenRows >= rowLimit; + } + + @Override + public void close() throws IOException { + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + workbook.write(fos); + } finally { + workbook.dispose(); + workbook.close(); + } + } + } } diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml index 066b61c..26247eb 100644 --- a/backend-java/src/main/resources/application.yml +++ b/backend-java/src/main/resources/application.yml @@ -82,12 +82,12 @@ aiimage: heartbeat-timeout-minutes: ${AIIMAGE_DELETE_BRAND_HEARTBEAT_TIMEOUT_MINUTES:15} stale-check-cron: ${AIIMAGE_DELETE_BRAND_STALE_CHECK_CRON:*/30 * * * * *} 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} + product-risk-stale-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_STALE_TIMEOUT_MINUTES:20} + product-risk-initial-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_INITIAL_TIMEOUT_MINUTES:20} + price-track-stale-timeout-minutes: ${AIIMAGE_PRICE_TRACK_STALE_TIMEOUT_MINUTES:20} + price-track-initial-timeout-minutes: ${AIIMAGE_PRICE_TRACK_INITIAL_TIMEOUT_MINUTES:20} + shop-match-stale-timeout-minutes: ${AIIMAGE_SHOP_MATCH_STALE_TIMEOUT_MINUTES:20} + shop-match-initial-timeout-minutes: ${AIIMAGE_SHOP_MATCH_INITIAL_TIMEOUT_MINUTES:20} module-cleanup: enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true} cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *} diff --git a/backend-java/src/main/resources/db/V24__price_track_tables.sql b/backend-java/src/main/resources/db/V24__price_track_tables.sql new file mode 100644 index 0000000..f10c436 --- /dev/null +++ b/backend-java/src/main/resources/db/V24__price_track_tables.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS biz_price_track_shop_candidate ( + id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT 'primary key', + user_id BIGINT NOT NULL COMMENT 'user id', + shop_name VARCHAR(255) NOT NULL COMMENT 'normalized shop name', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time', + UNIQUE KEY uk_user_shop (user_id, shop_name), + KEY idx_user_id (user_id) +) COMMENT='price track candidate shops'; + +CREATE TABLE IF NOT EXISTS biz_price_track_country_pref ( + user_id BIGINT NOT NULL PRIMARY KEY COMMENT 'user id', + country_codes_json VARCHAR(256) NOT NULL COMMENT 'country code order json', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updated time' +) COMMENT='price track country preference'; diff --git a/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql b/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql new file mode 100644 index 0000000..74322ce --- /dev/null +++ b/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql @@ -0,0 +1,6 @@ +ALTER TABLE `columns` + ADD COLUMN `sort_order` INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER `route_path`; + +UPDATE `columns` +SET `sort_order` = `id` +WHERE `sort_order` = 0; diff --git a/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql b/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql new file mode 100644 index 0000000..af919d6 --- /dev/null +++ b/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql @@ -0,0 +1,55 @@ +SET @db_name = DATABASE(); + +SET @user_id_col_exists := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND COLUMN_NAME = 'user_id' +); + +SET @sql_add_user_id_col := IF(@user_id_col_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD COLUMN user_id BIGINT NULL COMMENT ''关联用户ID'' AFTER group_name', + 'SELECT 1' +); +PREPARE stmt_add_user_id_col FROM @sql_add_user_id_col; +EXECUTE stmt_add_user_id_col; +DEALLOCATE PREPARE stmt_add_user_id_col; + +UPDATE biz_shop_manage_group g +LEFT JOIN users u ON u.username = g.group_name +SET g.user_id = u.id +WHERE g.user_id IS NULL + AND u.id IS NOT NULL; + +SET @user_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_user_id' +); + +SET @sql_add_user_id_idx := IF(@user_id_idx_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD INDEX idx_user_id (user_id)', + 'SELECT 1' +); +PREPARE stmt_add_user_id_idx FROM @sql_add_user_id_idx; +EXECUTE stmt_add_user_id_idx; +DEALLOCATE PREPARE stmt_add_user_id_idx; + +SET @user_id_uk_exists := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND INDEX_NAME = 'uk_user_id' +); + +SET @sql_add_user_id_uk := IF(@user_id_uk_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD UNIQUE KEY uk_user_id (user_id)', + 'SELECT 1' +); +PREPARE stmt_add_user_id_uk FROM @sql_add_user_id_uk; +EXECUTE stmt_add_user_id_uk; +DEALLOCATE PREPARE stmt_add_user_id_uk; diff --git a/backend/__pycache__/config.cpython-312.pyc b/backend/__pycache__/config.cpython-312.pyc index 57fc226..8a02d24 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 268c8ae..4b38d6b 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 c225db2..c5a0e46 100644 --- a/backend/blueprints/admin_api.py +++ b/backend/blueprints/admin_api.py @@ -62,6 +62,34 @@ ADMIN_MENU_ACCESS_CONFIG = { }, } +ADMIN_MENU_ACCESS_CONFIG.update({ + 'users': { + 'column_key': 'admin_users', + 'route_path': 'users', + 'error': '无权访问用户管理模块', + }, + 'columns': { + 'column_key': 'admin_columns', + 'route_path': 'columns', + 'error': '无权访问栏目权限配置模块', + }, + 'shop-keys': { + 'column_key': 'admin_shop_keys', + 'route_path': 'shop-keys', + 'error': '无权访问店铺密钥管理模块', + }, + 'history': { + 'column_key': 'admin_history', + 'route_path': 'history', + 'error': '无权访问查看生成记录模块', + }, + 'version': { + 'column_key': 'admin_version', + 'route_path': 'version', + 'error': '无权访问版本管理模块', + }, +}) + def _safe_version_key(version): """将版本号转换为安全的 OSS 对象名片段""" @@ -98,10 +126,155 @@ def _format_permission_item(item): 'column_key': item.get('columnKey') or '', 'menu_type': item.get('menuType') or 'app', 'route_path': item.get('routePath') or '', + 'sort_order': item.get('sortOrder') if item.get('sortOrder') is not None else 0, 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], } +def _parse_optional_int(value): + if value is None: + return None + text = str(value).strip() + if text == '': + return None + return int(text) + + +def _ensure_column_sort_schema(): + conn = get_db() + try: + with conn.cursor() as cur: + try: + cur.execute("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path") + except Exception: + pass + try: + cur.execute("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0") + except Exception: + pass + conn.commit() + finally: + conn.close() + + +def _load_local_column_sort_map(): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT id, sort_order FROM columns") + rows = cur.fetchall() + return {int(row['id']): int(row.get('sort_order') or 0) for row in rows if row.get('id') is not None} + finally: + conn.close() + + +def _load_local_columns(menu_type=None): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + sql = """ + SELECT id, name, column_key, menu_type, route_path, sort_order, created_at + FROM columns + """ + params = [] + if menu_type: + sql += " WHERE menu_type = %s" + params.append(menu_type) + sql += " ORDER BY sort_order ASC, id ASC" + cur.execute(sql, params) + return cur.fetchall() + finally: + conn.close() + + +def _sync_local_columns_from_backend(items): + if not items: + return + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + for item in items: + item_id = item.get('id') + if item_id is None: + continue + sort_order = item.get('sort_order') + cur.execute( + """ + INSERT INTO columns (id, name, column_key, menu_type, route_path, sort_order, created_at) + VALUES (%s, %s, %s, %s, %s, %s, COALESCE(%s, NOW())) + ON DUPLICATE KEY UPDATE + name = VALUES(name), + column_key = VALUES(column_key), + menu_type = VALUES(menu_type), + route_path = VALUES(route_path), + sort_order = CASE + WHEN columns.sort_order IS NULL OR columns.sort_order = 0 THEN VALUES(sort_order) + ELSE columns.sort_order + END + """, + ( + int(item_id), + item.get('name') or '', + item.get('column_key') or '', + item.get('menu_type') or 'app', + item.get('route_path') or '', + int(sort_order if sort_order not in (None, '') else item_id), + item.get('created_at') or None, + ), + ) + conn.commit() + finally: + conn.close() + + +def _set_local_column_sort_order(column_id, sort_order): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute( + "UPDATE columns SET sort_order = %s WHERE id = %s", + (int(sort_order), int(column_id)), + ) + conn.commit() + finally: + conn.close() + + +def _get_next_local_column_sort_order(): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT COALESCE(MAX(sort_order), 0) AS max_sort FROM columns") + row = cur.fetchone() or {} + return int(row.get('max_sort') or 0) + 1 + finally: + conn.close() + + +def _swap_local_column_sort_order(column_id, target_id): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT id, sort_order FROM columns WHERE id IN (%s, %s) ORDER BY id", (int(column_id), int(target_id))) + rows = cur.fetchall() + if len(rows) != 2: + raise ValueError('菜单不存在') + by_id = {int(row['id']): int(row.get('sort_order') or 0) for row in rows} + left_sort = by_id.get(int(column_id), 0) or int(column_id) + right_sort = by_id.get(int(target_id), 0) or int(target_id) + cur.execute("UPDATE columns SET sort_order = %s WHERE id = %s", (right_sort, int(column_id))) + cur.execute("UPDATE columns SET sort_order = %s WHERE id = %s", (left_sort, int(target_id))) + conn.commit() + finally: + conn.close() + + def _sync_user_column_permissions(user_id, column_ids): _, error_response, status = _proxy_backend_java( 'PUT', @@ -111,8 +284,14 @@ def _sync_user_column_permissions(user_id, column_ids): return error_response, status +def _get_current_admin_id(current_row=None): + if current_row and current_row.get('id'): + return current_row.get('id') + return session.get('user_id') + + def _get_current_admin_permission_sets(): - user_id = session.get('user_id') + user_id = _get_current_admin_id() if not user_id: return set(), set() conn = get_db() @@ -152,6 +331,60 @@ def _ensure_admin_menu_access(*menu_names): return role, current_row, (jsonify({'success': False, 'error': error_message}), 403) +def _ensure_dedupe_total_data_access(): + return _ensure_admin_menu_access('dedupe-total-data') + + +def _load_current_admin_menu_items(): + role, current_row = get_current_admin_role() + if not role or not current_row: + return None, None, None, (jsonify({'success': False, 'error': '需要管理员权限'}), 403) + user_id = _get_current_admin_id(current_row) + if not user_id: + return role, current_row, None, (jsonify({'success': False, 'error': '当前登录用户缺少有效ID'}), 400) + result, error_response, status = _proxy_backend_java( + 'GET', + f'/api/admin/permission-users/{user_id}/column-permissions', + params={'menuType': 'admin'}, + ) + if error_response is not None: + return role, current_row, None, (error_response, status) + items = [_format_permission_item(item) for item in (result.get('data') or [])] + return role, current_row, items, None + + +@admin_api.route('/current-user') +@admin_required +def get_admin_current_user(): + role, current_row = get_current_admin_role() + if not role or not current_row: + return jsonify({'success': False, 'error': '需要管理员权限'}), 403 + return jsonify({ + 'success': True, + 'item': { + 'id': current_row.get('id'), + 'username': current_row.get('username') or session.get('username') or '', + 'role': role, + } + }) + + +@admin_api.route('/current-user/menus') +@admin_required +def get_admin_current_user_menus(): + _, _, items, denied = _load_current_admin_menu_items() + if denied: + return denied + return jsonify({'success': True, 'items': items}) + + +@admin_api.route('/logout', methods=['POST']) +@admin_required +def admin_logout(): + session.clear() + return jsonify({'success': True, 'msg': '退出成功', 'redirect': '/login'}) + + # ---------- 用户管理 ---------- @admin_api.route('/users') @@ -162,7 +395,13 @@ def list_users(): if not role: return jsonify({'success': False, 'error': '需要管理员权限'}), 403 page = max(1, int(request.args.get('page', 1))) - page_size = min(50, max(5, int(request.args.get('page_size', 15)))) + _, _, denied = _ensure_admin_menu_access('users', 'history', 'shop-manage', 'skip-price-asin') + if denied: + return denied + _, _, denied = _ensure_admin_menu_access('users', 'history', 'shop-manage', 'skip-price-asin') + if denied: + return denied + page_size = min(999, max(5, int(request.args.get('page_size', 15)))) offset = (page - 1) * page_size search_username = (request.args.get('username') or request.args.get('search') or '').strip() created_by_id_arg = request.args.get('created_by_id') or request.args.get('admin_id') @@ -249,6 +488,9 @@ def list_users(): @admin_api.route('/user', methods=['POST']) @admin_required def create_user(): + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied data = request.get_json() or {} username = (data.get('username') or '').strip() password = data.get('password') or '' @@ -312,6 +554,9 @@ def create_user(): def update_user(uid): """更新用户(密码、角色)""" data = request.get_json() or {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied password = data.get('password') want_role = (data.get('role') or '').strip() or data.get('role') role, current_row = get_current_admin_role() @@ -368,6 +613,9 @@ def update_user(uid): @admin_required def delete_user(uid): """删除用户""" + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied if session.get('user_id') == uid: return jsonify({'success': False, 'error': '不能删除当前登录账号'}) role, current_row = get_current_admin_role() @@ -405,6 +653,9 @@ def delete_user(uid): @admin_required def history(): """管理员分页获取所有生成记录""" + _, _, denied = _ensure_admin_menu_access('history') + if denied: + return denied page = max(1, int(request.args.get('page', 1))) page_size = min(50, max(10, int(request.args.get('page_size', 15)))) offset = (page - 1) * page_size @@ -473,28 +724,49 @@ def history(): @admin_api.route('/columns') @admin_required def list_columns(): - params = {} + _, _, denied = _ensure_admin_menu_access('columns', 'users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type + params = {'menuType': menu_type} if menu_type else None result, error_response, status = _proxy_backend_java( 'GET', '/api/admin/permission-menus', - params=params or None, + params=params, ) - if error_response is not None: - return error_response, status - return jsonify({'success': True, 'items': [_format_permission_item(item) for item in (result.get('data') or [])]}) + if error_response is None: + _sync_local_columns_from_backend([_format_permission_item(item) for item in (result.get('data') or [])]) + local_rows = _load_local_columns(menu_type or None) + items = [ + { + 'id': row.get('id'), + 'name': row.get('name') or '', + 'column_key': row.get('column_key') or '', + 'menu_type': row.get('menu_type') or 'app', + 'route_path': row.get('route_path') or '', + 'sort_order': int(row.get('sort_order') or 0), + 'created_at': str(row.get('created_at') or '')[:16].replace('T', ' '), + } + for row in local_rows + ] + return jsonify({'success': True, 'items': items}) @admin_api.route('/column', methods=['POST']) @admin_required def create_column(): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied data = request.get_json() or {} name = (data.get('name') or '').strip() column_key = (data.get('column_key') or '').strip() - menu_type = (data.get('menu_type') or 'app').strip() or 'app' + menu_type = (data.get('menu_type') or '').strip() or 'admin' route_path = (data.get('route_path') or '').strip() + try: + sort_order = _parse_optional_int(data.get('sort_order')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '排序必须是数字'}) if not name: return jsonify({'success': False, 'error': '栏目名不能为空'}) if not column_key: @@ -514,17 +786,27 @@ def create_column(): if error_response is not None: return error_response, status item = result.get('data') or {} + _sync_local_columns_from_backend([_format_permission_item(item)]) + if item.get('id') is not None: + _set_local_column_sort_order(item.get('id'), sort_order if sort_order is not None else _get_next_local_column_sort_order()) return jsonify({'success': True, 'msg': result.get('message') or '创建成功', 'id': item.get('id')}) @admin_api.route('/column/', methods=['PUT']) @admin_required def update_column(cid): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied data = request.get_json() or {} name = (data.get('name') or '').strip() column_key = (data.get('column_key') or '').strip() - menu_type = (data.get('menu_type') or 'app').strip() or 'app' + menu_type = (data.get('menu_type') or '').strip() or 'admin' route_path = (data.get('route_path') or '').strip() + try: + sort_order = _parse_optional_int(data.get('sort_order')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '排序必须是数字'}) if not name: return jsonify({'success': False, 'error': '栏目名不能为空'}) if not column_key: @@ -543,32 +825,76 @@ def update_column(cid): ) if error_response is not None: return error_response, status + _sync_local_columns_from_backend([{ + 'id': cid, + 'name': name, + 'column_key': column_key, + 'menu_type': menu_type, + 'route_path': route_path, + 'sort_order': sort_order if sort_order is not None else cid, + 'created_at': None, + }]) + if sort_order is not None: + _set_local_column_sort_order(cid, sort_order) return jsonify({'success': True, 'msg': result.get('message') or '更新成功'}) +@admin_api.route('/column/reorder', methods=['POST']) +@admin_required +def reorder_column(): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied + data = request.get_json() or {} + try: + column_id = int(data.get('column_id')) + target_id = int(data.get('target_id')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '菜单重排参数无效'}), 400 + if column_id == target_id: + return jsonify({'success': True, 'msg': '排序未变化'}) + try: + _swap_local_column_sort_order(column_id, target_id) + except ValueError as exc: + return jsonify({'success': False, 'error': str(exc)}), 400 + except Exception as exc: + return jsonify({'success': False, 'error': str(exc)}), 500 + return jsonify({'success': True, 'msg': '排序更新成功'}) + + @admin_api.route('/column/', methods=['DELETE']) @admin_required def delete_column(cid): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/permission-menus/{cid}', ) if error_response is not None: return error_response, status + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM columns WHERE id = %s", (cid,)) + conn.commit() + finally: + conn.close() return jsonify({'success': True, 'msg': result.get('message') or '删除成功'}) @admin_api.route('/user//columns') @admin_required def get_user_columns(uid): - params = {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type result, error_response, status = _proxy_backend_java( 'GET', f'/api/admin/permission-users/{uid}/columns', - params=params or None, + params={'menuType': menu_type} if menu_type else None, ) if error_response is not None: return error_response, status @@ -579,14 +905,14 @@ def get_user_columns(uid): @admin_api.route('/user//column-permissions') @admin_required def get_user_column_permissions(uid): - params = {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type result, error_response, status = _proxy_backend_java( 'GET', f'/api/admin/permission-users/{uid}/column-permissions', - params=params or None, + params={'menuType': menu_type} if menu_type else None, ) if error_response is not None: return error_response, status @@ -610,6 +936,9 @@ def _set_user_column_permissions(cur, user_id, column_ids): @admin_api.route('/versions') @admin_required def list_versions(): + _, _, denied = _ensure_admin_menu_access('version') + if denied: + return denied """获取版本列表""" try: conn = get_db() @@ -637,6 +966,9 @@ def list_versions(): @admin_required def upload_version(): """接收版本号 + zip 文件,上传到 OSS,写入 web_config""" + _, _, denied = _ensure_admin_menu_access('version') + if denied: + return denied version = (request.form.get('version') or '').strip() if not version: return jsonify({'success': False, 'error': '请填写版本号'}) @@ -675,6 +1007,9 @@ def upload_version(): @admin_api.route('/shop-keys') @admin_required def list_shop_keys(): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied page = max(1, int(request.args.get('page', 1))) page_size = min(100, max(1, int(request.args.get('page_size', 15)))) result, error_response, status = _proxy_backend_java( @@ -707,6 +1042,9 @@ def list_shop_keys(): @admin_api.route('/shop-key', methods=['POST']) @admin_required def create_shop_key(): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied data = request.get_json() or {} payload = { 'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(), @@ -736,6 +1074,9 @@ def create_shop_key(): @admin_api.route('/shop-key/', methods=['PUT']) @admin_required def update_shop_key(item_id): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied data = request.get_json() or {} payload = { 'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(), @@ -765,6 +1106,9 @@ def update_shop_key(item_id): @admin_api.route('/shop-key/', methods=['DELETE']) @admin_required def delete_shop_key(item_id): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-keys/{item_id}', @@ -1007,8 +1351,9 @@ 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 current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' if group_id_raw: try: group_id = int(group_id_raw) @@ -1164,10 +1509,16 @@ def list_shop_manage_groups(): role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied + params = {} + if current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' + if role != 'super_admin' and current_row and current_row.get('id'): + params['createdById'] = current_row.get('id') 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, + params=params, ) if error_response is not None: return error_response, status @@ -1175,6 +1526,8 @@ def list_shop_manage_groups(): { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], } @@ -1186,17 +1539,22 @@ def list_shop_manage_groups(): @admin_api.route('/shop-manage-group', methods=['POST']) @admin_required def create_shop_manage_group(): - _, current_row, 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 {} payload = { 'groupName': (data.get('group_name') or '').strip(), + 'userId': data.get('user_id'), 'createdById': current_row.get('id') if current_row else None, } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/shop-manages/groups', + 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: @@ -1208,6 +1566,8 @@ def create_shop_manage_group(): 'item': { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], }, @@ -1221,7 +1581,10 @@ def update_shop_manage_group(item_id): 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(), + 'userId': data.get('user_id'), + } result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/shop-manages/groups/{item_id}', @@ -1240,6 +1603,8 @@ def update_shop_manage_group(item_id): 'item': { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], }, @@ -1249,7 +1614,7 @@ def update_shop_manage_group(item_id): @admin_api.route('/skip-price-asins') @admin_required def list_skip_price_asins(): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied page = max(1, int(request.args.get('page', 1))) @@ -1258,6 +1623,9 @@ def list_skip_price_asins(): shop_name = (request.args.get('shop_name') or '').strip() asin = (request.args.get('asin') or '').strip() params = {'page': page, 'pageSize': page_size} + if current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' if group_id_raw: try: group_id = int(group_id_raw) @@ -1305,19 +1673,31 @@ def list_skip_price_asins(): @admin_api.route('/skip-price-asin', methods=['POST']) @admin_required def create_skip_price_asin(): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied data = request.get_json() or {} + asin_mappings = data.get('asin_mappings') or {} + fallback_asin = (data.get('asin') or '').strip() + if not fallback_asin and isinstance(asin_mappings, dict): + for value in asin_mappings.values(): + fallback_asin = (value or '').strip() + if fallback_asin: + break payload = { 'groupId': data.get('group_id'), 'shopName': (data.get('shop_name') or '').strip(), 'countries': data.get('countries') or [], - 'asin': (data.get('asin') or '').strip(), + 'asin': fallback_asin, + 'asinMappings': asin_mappings, } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/skip-price-asins', + 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: @@ -1345,12 +1725,16 @@ def create_skip_price_asin(): @admin_api.route('/skip-price-asin//country/', methods=['DELETE']) @admin_required def delete_skip_price_asin_country(item_id, country): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + 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 @@ -1379,7 +1763,7 @@ def delete_shop_manage_group(item_id): @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') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied data = request.get_json() or {} @@ -1387,6 +1771,10 @@ def update_skip_price_asin_country(item_id, country): result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + 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: diff --git a/backend/utils/__pycache__/db.cpython-312.pyc b/backend/utils/__pycache__/db.cpython-312.pyc index 74e0984..7b0e8ac 100644 Binary files a/backend/utils/__pycache__/db.cpython-312.pyc and b/backend/utils/__pycache__/db.cpython-312.pyc differ diff --git a/backend/utils/db.py b/backend/utils/db.py index 0e72f51..edf13ef 100644 --- a/backend/utils/db.py +++ b/backend/utils/db.py @@ -122,10 +122,18 @@ def init_db(): cur.execute("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type") except Exception: pass + try: + cur.execute("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path") + except Exception: + pass try: cur.execute("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''") except Exception: pass + try: + cur.execute("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0") + except Exception: + pass cur.execute(""" CREATE TABLE IF NOT EXISTS user_column_permission ( user_id INT NOT NULL, diff --git a/backend/web_source/_admin_extracted.js b/backend/web_source/_admin_extracted.js new file mode 100644 index 0000000..cabf972 --- /dev/null +++ b/backend/web_source/_admin_extracted.js @@ -0,0 +1,2337 @@ + + (function () { + // Tab 切换 + var adminTabsEl = document.getElementById('adminTabs'); + if (adminTabsEl) adminTabsEl.innerHTML = ''; + var activeAdminTabName = ''; + var ADMIN_PANEL_MAP = { + 'users': 'panel-users', + 'columns': 'panel-columns', + 'dedupe-total-data': 'panel-dedupe-total-data', + 'shop-keys': 'panel-shop-keys', + 'shop-manage': 'panel-shop-manage', + 'skip-price-asin': 'panel-skip-price-asin', + 'history': 'panel-history', + 'version': 'panel-version' + }; + function runTabLoader(tabName) { + if (tabName === 'users') { loadUsers(1); loadColumnsForPermission(); } + else if (tabName === 'columns') loadColumns(); + else if (tabName === 'dedupe-total-data') loadDedupeTotalData(1); + else if (tabName === 'shop-keys') loadShopKeys(1); + else if (tabName === 'shop-manage') loadShopManage(1); + else if (tabName === 'skip-price-asin') loadSkipPriceAsin(1); + else if (tabName === 'history') loadHistory(1); + else if (tabName === 'version') loadVersions(); + } + function hideAllAdminPanels() { + document.querySelectorAll('.tab-panel').forEach(function (panel) { + panel.classList.remove('active'); + panel.style.display = 'none'; + }); + } + function getActiveAdminTabName() { + return activeAdminTabName; + } + function activateAdminTab(tabName) { + var panelId = ADMIN_PANEL_MAP[tabName]; + var panel = panelId ? document.getElementById(panelId) : null; + if (!panel) return; + activeAdminTabName = tabName; + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.classList.toggle('active', tab.dataset.tab === tabName); + }); + hideAllAdminPanels(); + panel.style.display = ''; + panel.classList.add('active'); + runTabLoader(tabName); + } + function renderAdminTabs(items) { + var knownItems = (items || []).filter(function (item) { + return !!ADMIN_PANEL_MAP[item.route_path]; + }); + if (!knownItems.length) { + activeAdminTabName = ''; + if (adminTabsEl) adminTabsEl.innerHTML = '
暂无可用菜单
'; + hideAllAdminPanels(); + return; + } + if (adminTabsEl) { + adminTabsEl.innerHTML = knownItems.map(function (item) { + return '
' + (item.name || item.route_path) + '
'; + }).join(''); + } + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.onclick = function () { + activateAdminTab(tab.dataset.tab); + }; + }); + var fallbackTab = activeAdminTabName && knownItems.some(function (item) { return item.route_path === activeAdminTabName; }) + ? activeAdminTabName + : knownItems[0].route_path; + activateAdminTab(fallbackTab); + } + function loadAdminMenus(preferredTab) { + if (preferredTab) activeAdminTabName = preferredTab; + fetch('/api/admin/current-user/menus') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + if (adminTabsEl) adminTabsEl.innerHTML = '
菜单加载失败
'; + hideAllAdminPanels(); + return; + } + renderAdminTabs(res.items || []); + }) + .catch(function () { + if (adminTabsEl) adminTabsEl.innerHTML = '
菜单加载失败
'; + hideAllAdminPanels(); + }); + } + hideAllAdminPanels(); + + // ========== 用户管理 ========== + var userPage = 1, userPageSize = 15; + var currentUserId = null; + var currentUserRole = 'admin'; + var currentUserUsername = ''; + var adminsList = []; + function roleLabel(role) { + if (role === 'super_admin') return '超级管理员'; + if (role === 'admin') return '管理员'; + return '普通账号'; + } + function buildUserListQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + userPageSize; + var kw = (document.getElementById('searchUsername').value || '').trim(); + if (kw) q += '&username=' + encodeURIComponent(kw); + var cby = document.getElementById('filterCreatedBy').value; + if (cby) q += '&created_by_id=' + encodeURIComponent(cby); + return q; + } + function loadUsers(page) { + userPage = page || 1; + fetch('/api/admin/users?' + buildUserListQuery(userPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('userListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + currentUserId = res.current_user_id || null; + currentUserRole = res.current_user_role || 'admin'; + currentUserUsername = (res.current_user_username || '').trim(); + adminsList = res.admins || []; + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无用户'; + } else { + tbody.innerHTML = items.map(function (u) { + return '' + u.id + '' + (u.username || '') + '' + + roleLabel(u.role || 'normal') + '' + (u.creator_username || '-') + '' + (u.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('userPagination', res.total, res.page, res.page_size, loadUsers); + bindUserActions(); + updateCreateFormByRole(); + updateUserFilterByRole(); + }) + .catch(function () { + document.getElementById('userListBody').innerHTML = '请求失败'; + }); + } + function updateUserFilterByRole() { + var grp = document.getElementById('filterCreatedByGroup'); + var sel = document.getElementById('filterCreatedBy'); + if (currentUserRole === 'super_admin') { + grp.style.display = 'block'; + var cur = sel.value; + sel.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + sel.appendChild(opt); + }); + sel.value = cur || ''; + } else { + grp.style.display = 'none'; + } + } + + function updateDedupeTotalDataAccess() { + var tab = document.querySelector('.tab[data-tab="dedupe-total-data"]'); + var panel = document.getElementById('panel-dedupe-total-data'); + var canUse = currentUserRole === 'super_admin' || (currentUserRole === 'admin' && currentUserUsername === ''); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function updateShopManageAccess() { + var tab = document.querySelector('.tab[data-tab="shop-manage"]'); + var panel = document.getElementById('panel-shop-manage'); + if (!tab || !panel) return; + var canUse = currentUserRole === 'super_admin' || + !!currentUserAdminPermissionKeys['admin_shop_manage'] || + !!currentUserAdminPermissionRoutes['shop-manage']; + tab.style.display = canUse ? '' : 'none'; + panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab.classList.contains('active')) { + tab.classList.remove('active'); + panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + updateShopManageAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + updateShopManageAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + updateShopManageAccess(); + }) + .catch(function () { + updateShopManageAccess(); + }); + } + function applyTabAccess(tabName, canUse) { + var tab = document.querySelector('.tab[data-tab="' + tabName + '"]'); + var panel = document.getElementById('panel-' + tabName); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function hasAdminTabAccess(tabName) { + var config = ADMIN_TAB_ACCESS_CONFIG[tabName]; + if (!config) return true; + if (currentUserRole === 'super_admin') return true; + if (config.superAdminOnly) return false; + return !!currentUserAdminPermissionKeys[config.columnKey] || + !!currentUserAdminPermissionRoutes[config.routePath]; + } + function refreshAdminTabAccess() { + Object.keys(ADMIN_TAB_ACCESS_CONFIG).forEach(function (tabName) { + applyTabAccess(tabName, hasAdminTabAccess(tabName)); + }); + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + refreshAdminTabAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + refreshAdminTabAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + refreshAdminTabAccess(); + }) + .catch(function () { + refreshAdminTabAccess(); + }); + } + var allColumnsList = []; + function loadColumnsForPermission() { + fetch('/api/admin/columns?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) return; + allColumnsList = res.items || []; + renderColumnPermissionWrap('createColumnPermissionWrap'); + renderColumnPermissionWrap('editColumnPermissionWrap'); + var selCreate = document.getElementById('createColumnPermissionWrap'); + var selEdit = document.getElementById('editColumnPermissionWrap'); + if (selCreate && !selCreate._colCardsBound) { + selCreate._colCardsBound = true; + selCreate.onchange = function () { renderColumnCards('createColumnPermissionWrap'); }; + } + if (selEdit && !selEdit._colCardsBound) { + selEdit._colCardsBound = true; + selEdit.onchange = function () { renderColumnCards('editColumnPermissionWrap'); }; + } + }) + .catch(function () { }); + } + var columnCardsContainerMap = { createColumnPermissionWrap: 'createColumnCards', editColumnPermissionWrap: 'editColumnCards' }; + function renderColumnCards(selectId) { + var sel = document.getElementById(selectId); + var cardsId = columnCardsContainerMap[selectId]; + var cardsEl = cardsId ? document.getElementById(cardsId) : null; + if (!sel || sel.tagName !== 'SELECT' || !cardsEl) return; + cardsEl.innerHTML = ''; + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled || !opt.selected) continue; + var card = document.createElement('span'); + card.className = 'column-permission-card'; + card.textContent = opt.textContent; + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'col-card-remove'; + btn.setAttribute('aria-label', '移除'); + btn.textContent = '×'; + (function (option, seldId) { + btn.onclick = function () { + option.selected = false; + renderColumnCards(seldId); + }; + })(opt, selectId); + card.appendChild(btn); + cardsEl.appendChild(card); + } + } + function renderColumnPermissionWrap(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + sel.innerHTML = ''; + allColumnsList.forEach(function (c) { + var opt = document.createElement('option'); + opt.value = c.id; + opt.textContent = c.name + ' (' + c.column_key + ')'; + sel.appendChild(opt); + }); + if (allColumnsList.length === 0) { + var opt = document.createElement('option'); + opt.disabled = true; + opt.textContent = '暂无菜单,请先在“栏目权限配置”中新增菜单'; + sel.appendChild(opt); + } + renderColumnCards(wrapId); + } + function getSelectedColumnIds(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return []; + var ids = []; + for (var i = 0; i < sel.options.length; i++) { + if (sel.options[i].selected) { + var v = parseInt(sel.options[i].value, 10); + if (!isNaN(v)) ids.push(v); + } + } + return ids; + } + function setColumnPermissionCheckboxes(wrapId, columnIds) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + var set = {}; + (columnIds || []).forEach(function (id) { set[id] = true; }); + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled) continue; + opt.selected = set[parseInt(opt.value, 10)] || false; + } + renderColumnCards(wrapId); + } + function updateCreateFormByRole() { + var roleSel = document.getElementById('createRole'); + var optAdmin = document.getElementById('optAdmin'); + var formCreatedBy = document.getElementById('formGroupCreatedBy'); + var selCreatedBy = document.getElementById('createCreatedBy'); + if (currentUserRole === 'super_admin') { + if (optAdmin) optAdmin.style.display = ''; + formCreatedBy.style.display = (roleSel.value === 'normal') ? 'block' : 'none'; + selCreatedBy.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + selCreatedBy.appendChild(opt); + }); + } else { + if (optAdmin) optAdmin.style.display = 'none'; + roleSel.value = 'normal'; + formCreatedBy.style.display = 'none'; + } + } + function bindUserActions() { + document.querySelectorAll('[data-edit]').forEach(function (btn) { + btn.onclick = function () { + var raw = (btn.getAttribute('data-user') || '{}').replace(/"/g, '"'); + var u; + try { u = JSON.parse(raw); } catch (e) { u = {}; } + document.getElementById('editUserId').value = u.id || ''; + document.getElementById('editUsername').value = u.username || ''; + document.getElementById('editPassword').value = ''; + var editRole = document.getElementById('editRole'); + var editFormGroupRole = document.getElementById('editFormGroupRole'); + var editFormGroupCreator = document.getElementById('editFormGroupCreator'); + var editCreatorName = document.getElementById('editCreatorName'); + editFormGroupRole.style.display = (currentUserRole === 'super_admin' && u.role !== 'super_admin') ? 'block' : 'none'; + editFormGroupCreator.style.display = (u.role === 'normal' && u.creator_username) ? 'block' : 'none'; + editCreatorName.value = u.creator_username || ''; + if (u.role !== 'super_admin') { editRole.value = u.role || 'normal'; } + document.getElementById('msgEdit').textContent = ''; + if (allColumnsList.length) { + renderColumnPermissionWrap('editColumnPermissionWrap'); + fetch('/api/admin/user/' + (u.id) + '/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success && res.column_ids) setColumnPermissionCheckboxes('editColumnPermissionWrap', res.column_ids); + }); + } + document.getElementById('editUserModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除用户 "' + (btn.dataset.name || '') + '" 吗?')) return; + fetch('/api/admin/user/' + btn.dataset.delete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadUsers(userPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + + document.getElementById('btnSearchUsers').onclick = function () { loadUsers(1); }; + document.getElementById('createRole').onchange = function () { updateCreateFormByRole(); }; + document.getElementById('btnCreate').onclick = function () { + var username = (document.getElementById('username').value || '').trim(); + var password = document.getElementById('password').value || ''; + var role = document.getElementById('createRole').value || 'normal'; + var createdById = document.getElementById('createCreatedBy').value ? parseInt(document.getElementById('createCreatedBy').value, 10) : null; + var msgEl = document.getElementById('msgCreate'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!username || username.length < 2) { + msgEl.textContent = '用户名至少 2 个字符'; + msgEl.classList.add('err'); + return; + } + if (!password || password.length < 6) { + msgEl.textContent = '密码至少 6 个字符'; + msgEl.classList.add('err'); + return; + } + var body = { username: username, password: password, role: role }; + if (role === 'normal' && currentUserRole === 'super_admin' && createdById) body.created_by_id = createdById; + body.column_ids = getSelectedColumnIds('createColumnPermissionWrap'); + fetch('/api/admin/user', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '创建成功'; + msgEl.classList.add('ok'); + document.getElementById('username').value = ''; + document.getElementById('password').value = ''; + loadUsers(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + + document.getElementById('btnSaveUser').onclick = function () { + var uid = document.getElementById('editUserId').value; + var password = document.getElementById('editPassword').value; + var editRoleEl = document.getElementById('editRole'); + var msgEl = document.getElementById('msgEdit'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + var body = {}; + if (password) body.password = password; + if (currentUserRole === 'super_admin' && editRoleEl && editRoleEl.offsetParent !== null) + body.role = editRoleEl.value || 'normal'; + body.column_ids = getSelectedColumnIds('editColumnPermissionWrap'); + fetch('/api/admin/user/' + uid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '保存成功'; + msgEl.classList.add('ok'); + document.getElementById('editUserModal').classList.remove('show'); + loadUsers(userPage); + if (String(uid || '') === String(currentUserId || '')) { + loadAdminMenus(getActiveAdminTabName()); + } + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEdit').onclick = function () { + document.getElementById('editUserModal').classList.remove('show'); + }; + + // ========== 生成记录 ========== + var historyPage = 1, historyPageSize = 15; + function toSqlDatetime(val) { + if (!val) return ''; + return val.replace('T', ' '); + } + function buildHistoryQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + historyPageSize; + var uid = document.getElementById('filterUser').value; + var start = toSqlDatetime(document.getElementById('filterTimeStart').value); + var end = toSqlDatetime(document.getElementById('filterTimeEnd').value); + if (uid) q += '&user_id=' + uid; + if (start) q += '&time_start=' + encodeURIComponent(start); + if (end) q += '&time_end=' + encodeURIComponent(end); + return q; + } + function loadHistory(page) { + historyPage = page || 1; + fetch('/api/admin/history?' + buildHistoryQuery(historyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('historyListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无记录'; + } else { + tbody.innerHTML = items.map(function (h) { + var urls = (h.result_urls || []); + var thumbUrls = (h.long_image_url ? [h.long_image_url] : []).concat(urls); + var thumbs = thumbUrls.slice(0, 3).map(function (url) { + return ''; + }).join(''); + return '' + h.id + '' + (h.username || '-') + '' + + (h.panel_type || '-') + '' + (h.created_at || '') + '' + + '
' + (thumbs || '-') + '
'; + }).join(''); + } + renderPagination('historyPagination', res.total, res.page, res.page_size, loadHistory); + }) + .catch(function () { + document.getElementById('historyListBody').innerHTML = '请求失败'; + }); + } + function loadUserOptions() { + fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + (res.items || []).forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + var shopManageGroupUsers = []; + function refreshShopManageGroupUserSelect(selectedUserId) { + var sel = document.getElementById('shopManageGroupUserSelect'); + if (!sel) return; + var opts = ['']; + shopManageGroupUsers.forEach(function (u) { + opts.push(''); + }); + sel.innerHTML = opts.join(''); + if (selectedUserId != null && selectedUserId !== '') { + sel.value = String(selectedUserId); + } + syncShopManageGroupNameWithUser(); + } + function syncShopManageGroupNameWithUser() { + var sel = document.getElementById('shopManageGroupUserSelect'); + var input = document.getElementById('shopManageGroupInput'); + if (!sel || !input) return; + var selectedUser = null; + shopManageGroupUsers.some(function (u) { + if (String(u.id) === String(sel.value || '')) { + selectedUser = u; + return true; + } + return false; + }); + input.value = selectedUser ? (selectedUser.username || '') : ''; + } + function loadUserOptions() { + return fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var items = res.items || []; + shopManageGroupUsers = items.map(function (u) { + return { id: u.id, username: u.username || '', role: u.role || 'normal' }; + }); + refreshShopManageGroupUserSelect(document.getElementById('shopManageGroupUserSelect') ? document.getElementById('shopManageGroupUserSelect').value : ''); + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + items.forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + document.getElementById('btnFilterHistory').onclick = function () { loadHistory(1); }; + + // ========== 数据去重总数据 ========== + var dedupeTotalDataPage = 1, dedupeTotalDataPageSize = 15; + function buildDedupeTotalDataQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + dedupeTotalDataPageSize; + var keyword = (document.getElementById('searchDedupeTotalData').value || '').trim(); + if (keyword) q += '&keyword=' + encodeURIComponent(keyword); + return q; + } + function loadDedupeTotalData(page) { + dedupeTotalDataPage = page || 1; + fetch('/api/admin/dedupe-total-data?' + buildDedupeTotalDataQuery(dedupeTotalDataPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('dedupeTotalDataListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无总数据'; + } else { + tbody.innerHTML = items.map(function (item) { + return '' + item.id + '' + (item.data_value || '') + '' + (item.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('dedupeTotalDataPagination', res.total, res.page, res.page_size, loadDedupeTotalData); + bindDedupeTotalDataActions(); + }) + .catch(function () { + document.getElementById('dedupeTotalDataListBody').innerHTML = '请求失败'; + }); + } + function bindDedupeTotalDataActions() { + document.querySelectorAll('[data-dedupe-total-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editDedupeTotalDataId').value = btn.dataset.dedupeTotalEdit || ''; + document.getElementById('editDedupeTotalDataValue').value = (btn.dataset.value || '').replace(/"/g, '"'); + document.getElementById('msgEditDedupeTotalData').textContent = ''; + document.getElementById('msgEditDedupeTotalData').className = 'msg'; + document.getElementById('editDedupeTotalDataModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-dedupe-total-delete]').forEach(function (btn) { + btn.onclick = function () { + var value = (btn.dataset.value || '').replace(/"/g, '"'); + if (!confirm('确定删除总数据“' + value + '”吗?')) return; + fetch('/api/admin/dedupe-total-data/' + btn.dataset.dedupeTotalDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadDedupeTotalData(dedupeTotalDataPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnSearchDedupeTotalData').onclick = function () { loadDedupeTotalData(1); }; + var dedupeImportPollTimer = null; + var dedupeDeleteImportPollTimer = null; + function stopDedupeImportProgress() { + if (dedupeImportPollTimer) { + clearInterval(dedupeImportPollTimer); + dedupeImportPollTimer = null; + } + } + function stopDedupeDeleteImportProgress() { + if (dedupeDeleteImportPollTimer) { + clearInterval(dedupeDeleteImportPollTimer); + dedupeDeleteImportPollTimer = null; + } + } + function setDedupeImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataProgressWrap'); + var fill = document.getElementById('dedupeTotalDataProgressFill'); + var textEl = document.getElementById('dedupeTotalDataProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function setDedupeDeleteImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataDeleteProgressWrap'); + var fill = document.getElementById('dedupeTotalDataDeleteProgressFill'); + var textEl = document.getElementById('dedupeTotalDataDeleteProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function pollDedupeImport(importId) { + stopDedupeImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = res.error || '查询导入进度失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeImportProgress(percent, '处理中:已处理 ' + processedRows + ' / ' + totalRows + ',新增 ' + (progress.inserted_count || 0) + ',跳过 ' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '导入成功:总行数 ' + (progress.total_rows || 0) + ',ASIN 数量 ' + (progress.asin_count || 0) + ',新增 ' + (progress.inserted_count || 0) + ',跳过 ' + (progress.skipped_count || 0); + document.getElementById('msgDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = progress.error_message || '导入失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '查询导入进度失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeImportPollTimer = setInterval(tick, 1000); + } + function pollDedupeDeleteImport(importId) { + stopDedupeDeleteImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/delete-import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = res.error || '查询删除进度失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeDeleteImportProgress(percent, '处理中:已处理 ' + processedRows + ' / ' + totalRows + ',删除 ' + (progress.deleted_count || 0) + ',跳过 ' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '删除成功:总行数 ' + (progress.total_rows || 0) + ',ASIN 数量 ' + (progress.asin_count || 0) + ',删除 ' + (progress.deleted_count || 0) + ',跳过 ' + (progress.skipped_count || 0); + document.getElementById('msgDeleteDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = progress.error_message || '删除失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '查询删除进度失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeDeleteImportPollTimer = setInterval(tick, 1000); + } + + document.getElementById('btnAddDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataFile'); + var msgEl = document.getElementById('msgDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeImportProgress(); + document.getElementById('dedupeTotalDataProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 Excel 文件'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '仅支持 .xlsx 或 .xls 文件'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeImportProgress(percent, '上传中:' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '返回格式错误' }; } + if (!res.success) { + msgEl.textContent = res.error || '导入失败'; + msgEl.className = 'msg err'; + return; + } + setDedupeImportProgress(100, '上传完成,后端处理中...'); + pollDedupeImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnDeleteImportDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataDeleteFile'); + var msgEl = document.getElementById('msgDeleteDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeDeleteImportProgress(); + document.getElementById('dedupeTotalDataDeleteProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 Excel 文件'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '仅支持 .xlsx 或 .xls 文件'; + msgEl.classList.add('err'); + return; + } + if (!confirm('确定按 Excel 中的 ASIN 批量删除匹配的总数据吗?')) { + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/delete-import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeDeleteImportProgress(percent, '上传中:' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '返回格式错误' }; } + if (!res.success) { + msgEl.textContent = res.error || '删除失败'; + msgEl.className = 'msg err'; + return; + } + setDedupeDeleteImportProgress(100, '上传完成,后端处理中...'); + pollDedupeDeleteImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnSaveDedupeTotalData').onclick = function () { + var itemId = document.getElementById('editDedupeTotalDataId').value; + var value = (document.getElementById('editDedupeTotalDataValue').value || '').trim(); + var msgEl = document.getElementById('msgEditDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!value) { + msgEl.textContent = '请填写总数据值'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/dedupe-total-data/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data_value: value }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + loadDedupeTotalData(dedupeTotalDataPage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditDedupeTotalData').onclick = function () { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + }; + + // ========== 店铺密钥管理 ========== + var shopKeyPage = 1, shopKeyPageSize = 15; + function buildShopKeyQuery(page) { + return 'page=' + (page || 1) + '&page_size=' + shopKeyPageSize; + } + function loadShopKeys(page) { + shopKeyPage = page || 1; + fetch('/api/admin/shop-keys?' + buildShopKeyQuery(shopKeyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopKeyListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无店铺密钥'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopKeyPage - 1) * shopKeyPageSize + index + 1; + return '' + rowNo + '' + (item.ziniao_account_name || '') + '' + (item.ziniao_token || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopKeyPagination', res.total, res.page, res.page_size, loadShopKeys); + bindShopKeyActions(); + }) + .catch(function () { + document.getElementById('shopKeyListBody').innerHTML = '请求失败'; + }); + } + function bindShopKeyActions() { + document.querySelectorAll('[data-shop-key-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopKey || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopKeyId').value = item.id || ''; + document.getElementById('editShopKeyZiniaoAccountName').value = item.ziniao_account_name || ''; + document.getElementById('editShopKeyZiniaoToken').value = item.ziniao_token || ''; + document.getElementById('msgEditShopKey').textContent = ''; + document.getElementById('msgEditShopKey').className = 'msg'; + document.getElementById('editShopKeyModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-shop-key-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.ziniaoAccountName || '').replace(/"/g, '"'); + if (!confirm('确定删除店铺密钥“' + name + '”吗?')) return; + fetch('/api/admin/shop-key/' + btn.dataset.shopKeyDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopKeys(shopKeyPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnCreateShopKey').onclick = function () { + var ziniaoAccountName = (document.getElementById('shopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('shopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopKeyZiniaoAccountName').value = ''; + document.getElementById('shopKeyZiniaoToken').value = ''; + msgEl.textContent = res.msg || '创建成功'; + msgEl.className = 'msg ok'; + loadShopKeys(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + document.getElementById('btnSaveShopKey').onclick = function () { + var itemId = document.getElementById('editShopKeyId').value; + var ziniaoAccountName = (document.getElementById('editShopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('editShopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgEditShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopKeyModal').classList.remove('show'); + loadShopKeys(shopKeyPage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopKey').onclick = function () { + document.getElementById('editShopKeyModal').classList.remove('show'); + }; + + // ========== 店铺管理 ========== + var shopManagePage = 1, shopManagePageSize = 15; + var shopManageGroups = []; + + function buildShopManageQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + shopManagePageSize; + var groupId = (document.getElementById('shopManageFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('shopManageFilterShopName').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '加载分组失败'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function openShopManageGroupModal() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '暂无分组'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + document.getElementById('shopManageGroupInput').value = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('确定删除分组“' + gname + '”吗?')) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '删除失败'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + function loadShopManage(page) { + shopManagePage = page || 1; + fetch('/api/admin/shop-manages?' + buildShopManageQuery(shopManagePage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopManageListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无店铺'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopManagePage - 1) * shopManagePageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + (item.password || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopManagePagination', res.total, res.page, res.page_size, loadShopManage); + bindShopManageActions(); + }) + .catch(function () { + document.getElementById('shopManageListBody').innerHTML = '请求失败'; + }); + } + + function bindShopManageActions() { + document.querySelectorAll('[data-shop-manage-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopManage || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopManageId').value = item.id || ''; + document.getElementById('editShopManageShopName').value = item.shop_name || ''; + document.getElementById('editShopManageMallName').value = item.mall_name || ''; + document.getElementById('editShopManageAccount').value = item.account || ''; + document.getElementById('editShopManagePassword').value = item.password || ''; + document.getElementById('msgEditShopManage').textContent = ''; + document.getElementById('msgEditShopManage').className = 'msg'; + loadShopManageGroups(null, item.group_id).then(function () { + document.getElementById('editShopManageModal').classList.add('show'); + }); + }; + }); + document.querySelectorAll('[data-shop-manage-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.shopManageName || '').replace(/"/g, '"'); + if (!confirm('确定删除店铺“' + name + '”吗?')) return; + fetch('/api/admin/shop-manage/' + btn.dataset.shopManageDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopManage(shopManagePage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnSearchShopManage').onclick = function () { + loadShopManage(1); + }; + document.getElementById('shopManageFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadShopManage(1); + } + }); + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = function () { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + }; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupName) { + msgEl.textContent = '请输入分组名称'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '加载分组失败'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function resetShopManageGroupForm() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + refreshShopManageGroupUserSelect(''); + } + + function openShopManageGroupModal() { + resetShopManageGroupForm(); + loadUserOptions() + .then(function () { return loadShopManageGroups(); }) + .then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '暂无分组'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.username || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + refreshShopManageGroupUserSelect(btn.dataset.shopGroupUserId || ''); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('确定删除分组“' + gname + '”吗?')) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '删除失败'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + document.getElementById('shopManageGroupUserSelect').onchange = syncShopManageGroupNameWithUser; + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = resetShopManageGroupForm; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var userId = (document.getElementById('shopManageGroupUserSelect').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!userId || !groupName) { + msgEl.textContent = '请选择关联用户'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName, user_id: Number(userId) }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + resetShopManageGroupForm(); + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnCreateShopManage').onclick = function () { + var groupId = (document.getElementById('shopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('shopManageShopName').value || '').trim(); + var mallName = (document.getElementById('shopManageMallName').value || '').trim(); + var account = (document.getElementById('shopManageAccount').value || '').trim(); + var password = (document.getElementById('shopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '请完整填写分组、店铺名、店铺商城名、账号、密码'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopManageGroupSelect').value = ''; + document.getElementById('shopManageShopName').value = ''; + document.getElementById('shopManageMallName').value = ''; + document.getElementById('shopManageAccount').value = ''; + document.getElementById('shopManagePassword').value = ''; + msgEl.textContent = res.msg || '创建成功'; + msgEl.className = 'msg ok'; + loadShopManage(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnSaveShopManage').onclick = function () { + var itemId = document.getElementById('editShopManageId').value; + var groupId = (document.getElementById('editShopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('editShopManageShopName').value || '').trim(); + var mallName = (document.getElementById('editShopManageMallName').value || '').trim(); + var account = (document.getElementById('editShopManageAccount').value || '').trim(); + var password = (document.getElementById('editShopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgEditShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '请完整填写分组、店铺名、店铺商城名、账号、密码'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopManageModal').classList.remove('show'); + loadShopManage(shopManagePage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopManage').onclick = function () { + document.getElementById('editShopManageModal').classList.remove('show'); + }; + + // ========== 版本管理 ========== + // ========== 跳过跟价 ASIN ========== + var skipPriceAsinPage = 1, skipPriceAsinPageSize = 15; + var chooseSkipPriceAsinShopPage = 1, chooseSkipPriceAsinShopPageSize = 10; + var skipPriceCountryColumns = [ + { code: 'DE', field: 'asin_de', label: '德国' }, + { code: 'UK', field: 'asin_uk', label: '英国' }, + { code: 'FR', field: 'asin_fr', label: '法国' }, + { code: 'IT', field: 'asin_it', label: '意大利' }, + { code: 'ES', field: 'asin_es', label: '西班牙' } + ]; + function buildChooseSkipPriceAsinShopQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + chooseSkipPriceAsinShopPageSize; + var groupId = (document.getElementById('chooseSkipPriceAsinShopGroupId').value || '').trim(); + var shopName = (document.getElementById('chooseSkipPriceAsinShopKeyword').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + function loadChooseSkipPriceAsinShops(page) { + chooseSkipPriceAsinShopPage = page || 1; + fetch('/api/admin/shop-manages?' + buildChooseSkipPriceAsinShopQuery(chooseSkipPriceAsinShopPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('chooseSkipPriceAsinShopListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (!items.length) { + tbody.innerHTML = '暂无店铺'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (chooseSkipPriceAsinShopPage - 1) * chooseSkipPriceAsinShopPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + + '' + + ''; + }).join(''); + } + renderPagination('chooseSkipPriceAsinShopPagination', res.total, res.page, res.page_size, loadChooseSkipPriceAsinShops); + bindChooseSkipPriceAsinShopActions(); + }) + .catch(function () { + document.getElementById('chooseSkipPriceAsinShopListBody').innerHTML = '请求失败'; + }); + } + function bindChooseSkipPriceAsinShopActions() { + document.querySelectorAll('[data-choose-skip-price-asin-shop]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('skipPriceAsinShopName').value = (btn.dataset.shopName || '').replace(/"/g, '"'); + if (!document.getElementById('skipPriceAsinGroupSelect').value && btn.dataset.groupId) { + document.getElementById('skipPriceAsinGroupSelect').value = btn.dataset.groupId; + } + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + }); + } + function openChooseSkipPriceAsinShopModal() { + var currentGroupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + if (currentGroupId) { + document.getElementById('chooseSkipPriceAsinShopGroupId').value = currentGroupId; + } + document.getElementById('chooseSkipPriceAsinShopKeyword').value = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + document.getElementById('chooseSkipPriceAsinShopModal').classList.add('show'); + loadChooseSkipPriceAsinShops(1); + } + function setupSkipPriceAsinShopPicker() { + var input = document.getElementById('skipPriceAsinShopName'); + var button = document.getElementById('btnChooseSkipPriceAsinShop'); + if (!input || !button) return; + var inputParent = input.parentNode; + if (inputParent && inputParent.style && inputParent.style.display === 'flex') return; + var legacyWrap = button.parentNode; + var wrapper = document.createElement('div'); + wrapper.style.display = 'flex'; + wrapper.style.gap = '8px'; + wrapper.style.alignItems = 'center'; + input.parentNode.insertBefore(wrapper, input); + wrapper.appendChild(input); + wrapper.appendChild(button); + button.style.whiteSpace = 'nowrap'; + button.style.marginTop = '0'; + if (legacyWrap && legacyWrap !== wrapper) { + legacyWrap.style.display = 'none'; + } + } + function getSelectedSkipPriceCountries() { + return Array.from(document.getElementById('skipPriceAsinCountries').selectedOptions).map(function (option) { + return option.value; + }); + } + function renderSkipPriceAsinInputs() { + var container = document.getElementById('skipPriceAsinInputs'); + var selectedCountries = getSelectedSkipPriceCountries(); + var existingValues = {}; + container.querySelectorAll('[data-skip-price-country-input]').forEach(function (input) { + existingValues[input.getAttribute('data-skip-price-country-input')] = input.value; + }); + if (!selectedCountries.length) { + container.innerHTML = '
请选择国家后输入 ASIN
'; + return; + } + container.innerHTML = selectedCountries.map(function (countryCode) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + var value = existingValues[countryCode] || ''; + return '
' + + '' + label + '' + + '' + + '
'; + }).join(''); + } + function collectSkipPriceAsinMappings(countries) { + var mappings = {}; + for (var i = 0; i < countries.length; i++) { + var countryCode = countries[i]; + var input = document.querySelector('[data-skip-price-country-input="' + countryCode + '"]'); + var asin = input ? (input.value || '').trim().toUpperCase() : ''; + if (!asin) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + throw new Error(label + ' ASIN 不能为空'); + } + mappings[countryCode] = asin; + } + return mappings; + } + function buildSkipPriceAsinQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + skipPriceAsinPageSize; + var groupId = (document.getElementById('skipPriceAsinFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinFilterShopName').value || '').trim(); + var asin = (document.getElementById('skipPriceAsinFilterAsin').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + if (asin) query += '&asin=' + encodeURIComponent(asin); + return query; + } + function renderSkipPriceAsinCell(item, country) { + var value = item[country.field] || ''; + 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, '"'); + var countryCode = btn.dataset.country || ''; + if (!confirm('确定删除店铺“' + shopName + '”在 ' + countryCode + ' 的 ASIN 吗?')) return; + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinDelete + '/country/' + countryCode, { + method: 'DELETE' + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '删除失败'); + }); + }; + }); + } + function loadSkipPriceAsin(page) { + skipPriceAsinPage = page || 1; + fetch('/api/admin/skip-price-asins?' + buildSkipPriceAsinQuery(skipPriceAsinPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('skipPriceAsinListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无数据'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (skipPriceAsinPage - 1) * skipPriceAsinPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + + skipPriceCountryColumns.map(function (country) { + return '' + renderSkipPriceAsinCell(item, country) + ''; + }).join('') + + ''; + }).join(''); + } + renderPagination('skipPriceAsinPagination', res.total, res.page, res.page_size, loadSkipPriceAsin); + bindSkipPriceAsinActions(); + }) + .catch(function () { + document.getElementById('skipPriceAsinListBody').innerHTML = '请求失败'; + }); + } + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnChooseSkipPriceAsinShop').onclick = openChooseSkipPriceAsinShopModal; + document.getElementById('btnSearchChooseSkipPriceAsinShop').onclick = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopGroupId').onchange = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopKeyword').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadChooseSkipPriceAsinShops(1); + } + }); + document.getElementById('btnCloseChooseSkipPriceAsinShopModal').onclick = function () { + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + document.getElementById('skipPriceAsinCountries').addEventListener('change', renderSkipPriceAsinInputs); + document.getElementById('btnSearchSkipPriceAsin').onclick = function () { + loadSkipPriceAsin(1); + }; + document.getElementById('skipPriceAsinFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('skipPriceAsinFilterAsin').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('btnCreateSkipPriceAsin').onclick = function () { + var groupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + var countries = getSelectedSkipPriceCountries(); + var msgEl = document.getElementById('msgSkipPriceAsin'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !countries.length) { + msgEl.textContent = '请完整填写分组、店铺名、国家和 ASIN'; + msgEl.className = 'msg err'; + return; + } + var asinMappings = {}; + try { + asinMappings = collectSkipPriceAsinMappings(countries); + } catch (err) { + msgEl.textContent = err.message || '请输入 ASIN'; + msgEl.className = 'msg err'; + return; + } + var fallbackAsin = ''; + Object.keys(asinMappings).some(function (countryCode) { + fallbackAsin = asinMappings[countryCode] || ''; + return !!fallbackAsin; + }); + fetch('/api/admin/skip-price-asin', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + group_id: Number(groupId), + shop_name: shopName, + countries: countries, + asin: fallbackAsin, + asin_mappings: asinMappings + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('skipPriceAsinGroupSelect').value = ''; + document.getElementById('skipPriceAsinShopName').value = ''; + Array.from(document.getElementById('skipPriceAsinCountries').options).forEach(function (option) { + option.selected = false; + }); + renderSkipPriceAsinInputs(); + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadSkipPriceAsin(1); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + setupSkipPriceAsinShopPicker(); + renderSkipPriceAsinInputs(); + function loadVersions() { + fetch('/api/admin/versions') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('versionListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无版本记录'; + } else { + tbody.innerHTML = items.map(function (v) { + var url = (v.file_url || '').replace(/"/g, '"'); + return '' + (v.version || '') + '' + url + '' + (v.created_at || '') + '下载'; + }).join(''); + } + }) + .catch(function () { + document.getElementById('versionListBody').innerHTML = '请求失败'; + }); + } + document.getElementById('btnUploadVersion').onclick = function () { + var version = (document.getElementById('versionNumber').value || '').trim(); + var fileInput = document.getElementById('versionZip'); + var msgEl = document.getElementById('msgVersion'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!version) { + msgEl.textContent = '请填写版本号'; + msgEl.classList.add('err'); + return; + } + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 zip 压缩包'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + if (!(file.name || '').toLowerCase().endsWith('.zip')) { + msgEl.textContent = '仅支持 .zip 格式'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('version', version); + formData.append('file', file); + msgEl.textContent = '上传中...'; + msgEl.classList.remove('err', 'ok'); + fetch('/api/admin/version', { + method: 'POST', + body: formData + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = '发布成功。版本:' + res.version + ',链接:' + (res.file_url || ''); + msgEl.classList.add('ok'); + document.getElementById('versionNumber').value = ''; + fileInput.value = ''; + loadVersions(); + } else { + msgEl.textContent = res.error || '上传失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + + // ========== 栏目权限配置 ========== + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '暂无菜单,请在上方新增'; + } else { + tbody.innerHTML = allColumnsList.map(function (c) { + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + (c.created_at || '') + '' + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '请求失败'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除菜单“' + (btn.dataset.name || '').replace(/"/g, '"') + '”吗?')) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '新增成功'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '新增失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { msgEl.textContent = '请求失败'; msgEl.classList.add('err'); }); + }; + document.getElementById('btnSaveColumn').onclick = function () { + var cid = document.getElementById('editColumnId').value; + var name = (document.getElementById('editColumnName').value || '').trim(); + var key = (document.getElementById('editColumnKey').value || '').trim(); + var msgEl = document.getElementById('msgEditColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column/' + cid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editColumnModal').classList.remove('show'); + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditColumn').onclick = function () { + document.getElementById('editColumnModal').classList.remove('show'); + }; + + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '暂无菜单,请先在上方新增'; + } else { + tbody.innerHTML = allColumnsList.map(function (c, index) { + var moveButtons = + ' ' + + ' '; + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + ((c.menu_type || '') === 'admin' ? '后台(admin)' : '软件(app)') + '' + (c.sort_order != null ? c.sort_order : 0) + '' + (c.route_path || '') + '' + (c.created_at || '') + '' + + moveButtons + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '请求失败'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-move-up]').forEach(function (btn) { + btn.onclick = function () { + if (btn.disabled) return; + moveColumnItem(btn.dataset.columnMoveUp, -1, btn); + }; + }); + document.querySelectorAll('[data-column-move-down]').forEach(function (btn) { + btn.onclick = function () { + if (btn.disabled) return; + moveColumnItem(btn.dataset.columnMoveDown, 1, btn); + }; + }); + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('editColumnRoutePath').value = (btn.dataset.route || '').replace(/"/g, '"'); + document.getElementById('editColumnMenuType').value = ((btn.dataset.menuType || 'app').replace(/"/g, '"') || 'app'); + document.getElementById('editColumnSortOrder').value = ((btn.dataset.sortOrder || '0').replace(/"/g, '"') || '0'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除菜单“' + (btn.dataset.name || '').replace(/"/g, '"') + '”吗?')) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + function updateColumnSortOrder(column, sortOrder) { + return fetch('/api/admin/column/' + column.id, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: column.name || '', + column_key: column.column_key || '', + route_path: column.route_path || '', + menu_type: column.menu_type || 'app', + sort_order: sortOrder + }) + }).then(function (r) { return r.json(); }); + } + function moveColumnItem(columnId, delta, triggerBtn) { + var currentIndex = -1; + for (var i = 0; i < allColumnsList.length; i++) { + if (String(allColumnsList[i].id) === String(columnId)) { + currentIndex = i; + break; + } + } + if (currentIndex < 0) return; + var targetIndex = currentIndex + delta; + if (targetIndex < 0 || targetIndex >= allColumnsList.length) return; + var currentItem = allColumnsList[currentIndex]; + var targetItem = allColumnsList[targetIndex]; + if (!currentItem || !targetItem) return; + if (triggerBtn) triggerBtn.disabled = true; + var currentSort = currentItem.sort_order != null ? currentItem.sort_order : (currentIndex + 1); + var targetSort = targetItem.sort_order != null ? targetItem.sort_order : (targetIndex + 1); + Promise.all([ + updateColumnSortOrder(currentItem, targetSort), + updateColumnSortOrder(targetItem, currentSort) + ]).then(function (results) { + var failed = (results || []).find(function (res) { return !res || !res.success; }); + if (failed) { + alert((failed && failed.error) || '排序保存失败'); + return; + } + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + }).catch(function () { + alert('排序保存失败'); + }).finally(function () { + if (triggerBtn) triggerBtn.disabled = false; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var routePath = (document.getElementById('columnRoutePath').value || '').trim(); + var sortOrderValue = (document.getElementById('columnSortOrder').value || '').trim(); + var menuType = (document.getElementById('columnMenuType').value || 'admin').trim() || 'admin'; + var sortOrder = sortOrderValue === '' ? null : parseInt(sortOrderValue, 10); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + if (!routePath) { + msgEl.textContent = '请填写菜单路由'; msgEl.classList.add('err'); return; + } + if (sortOrderValue !== '' && isNaN(sortOrder)) { + msgEl.textContent = '排序必须是数字'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key, route_path: routePath, menu_type: menuType, sort_order: sortOrder }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '新增成功'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + document.getElementById('columnRoutePath').value = ''; + document.getElementById('columnSortOrder').value = ''; + document.getElementById('columnMenuType').value = 'admin'; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '新增失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { msgEl.textContent = '请求失败'; msgEl.classList.add('err'); }); + }; + document.getElementById('btnSaveColumn').onclick = function () { + var cid = document.getElementById('editColumnId').value; + var name = (document.getElementById('editColumnName').value || '').trim(); + var key = (document.getElementById('editColumnKey').value || '').trim(); + var routePath = (document.getElementById('editColumnRoutePath').value || '').trim(); + var sortOrderValue = (document.getElementById('editColumnSortOrder').value || '').trim(); + var menuType = (document.getElementById('editColumnMenuType').value || 'admin').trim() || 'admin'; + var sortOrder = sortOrderValue === '' ? null : parseInt(sortOrderValue, 10); + var msgEl = document.getElementById('msgEditColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + if (!routePath) { + msgEl.textContent = '请填写菜单路由'; msgEl.classList.add('err'); return; + } + if (sortOrderValue !== '' && isNaN(sortOrder)) { + msgEl.textContent = '排序必须是数字'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column/' + cid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key, route_path: routePath, menu_type: menuType, sort_order: sortOrder }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editColumnModal').classList.remove('show'); + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + + // ========== 分页 ========== + function renderPagination(elId, total, page, pageSize, onPage) { + var el = document.getElementById(elId); + if (!el) return; + var totalPages = Math.max(1, Math.ceil(total / pageSize)); + el.innerHTML = '共' + total + ' 条' + + '' + + '第' + page + ' / ' + totalPages + ' 页' + + ''; + el.querySelectorAll('[data-p]').forEach(function (b) { + if (!b.disabled) b.onclick = function () { onPage(parseInt(b.dataset.p, 10)); }; + }); + } + + // 初始化 + function loadAdminCurrentUser() { + fetch('/api/admin/current-user') + .then(function (r) { + if (r.status === 404) { + return fetch('/api/auth/check') + .then(function (fallbackResp) { return fallbackResp.json(); }) + .then(function (fallbackRes) { + if (fallbackRes && fallbackRes.logged_in) { + return { + success: true, + item: { + username: '当前用户', + role: '' + } + }; + } + return { success: false }; + }); + } + return r.json(); + }) + .then(function (res) { + var nameEl = document.getElementById('adminCurrentUsername'); + var roleEl = document.getElementById('adminCurrentUserRole'); + if (!res.success) { + nameEl.textContent = '未登录'; + roleEl.style.display = 'none'; + return; + } + var item = res.item || {}; + nameEl.textContent = item.username || '管理员'; + if (item.role) { + roleEl.textContent = item.role === 'super_admin' ? '超级管理员' : '管理员'; + roleEl.style.display = 'inline-block'; + } else { + roleEl.style.display = 'none'; + } + }) + .catch(function () { + fetch('/api/auth/check') + .then(function (r) { return r.json(); }) + .then(function (res) { + document.getElementById('adminCurrentUsername').textContent = res && res.logged_in ? '当前用户' : '未登录'; + document.getElementById('adminCurrentUserRole').style.display = 'none'; + }) + .catch(function () { + document.getElementById('adminCurrentUsername').textContent = '当前用户'; + document.getElementById('adminCurrentUserRole').style.display = 'none'; + }); + }); + } + + document.getElementById('btnAdminLogout').onclick = function () { + fetch('/api/admin/logout', { + method: 'POST', + headers: { 'X-Requested-With': 'XMLHttpRequest' } + }) + .then(function (r) { + if (r.status === 404) { + window.location.href = '/logout'; + return null; + } + return r.json(); + }) + .then(function (res) { + if (!res) return; + if (!res.success) { + alert(res.error || '退出失败'); + return; + } + window.location.href = res.redirect || '/login'; + }) + .catch(function () { + window.location.href = '/logout'; + }); + }; + + loadAdminCurrentUser(); + loadUserOptions(); + loadColumnsForPermission(); + loadShopManageGroups(); + loadAdminMenus(); + }) (); + \ No newline at end of file diff --git a/backend/web_source/_tmp_prefix.js b/backend/web_source/_tmp_prefix.js new file mode 100644 index 0000000..c578064 --- /dev/null +++ b/backend/web_source/_tmp_prefix.js @@ -0,0 +1,2000 @@ + + (function () { + // Tab 鍒囨崲 + var adminTabsEl = document.getElementById('adminTabs'); + if (adminTabsEl) adminTabsEl.innerHTML = ''; + var activeAdminTabName = ''; + var ADMIN_PANEL_MAP = { + 'users': 'panel-users', + 'columns': 'panel-columns', + 'dedupe-total-data': 'panel-dedupe-total-data', + 'shop-keys': 'panel-shop-keys', + 'shop-manage': 'panel-shop-manage', + 'skip-price-asin': 'panel-skip-price-asin', + 'history': 'panel-history', + 'version': 'panel-version' + }; + function runTabLoader(tabName) { + if (tabName === 'users') { loadUsers(1); loadColumnsForPermission(); } + else if (tabName === 'columns') loadColumns(); + else if (tabName === 'dedupe-total-data') loadDedupeTotalData(1); + else if (tabName === 'shop-keys') loadShopKeys(1); + else if (tabName === 'shop-manage') loadShopManage(1); + else if (tabName === 'skip-price-asin') loadSkipPriceAsin(1); + else if (tabName === 'history') loadHistory(1); + else if (tabName === 'version') loadVersions(); + } + function hideAllAdminPanels() { + document.querySelectorAll('.tab-panel').forEach(function (panel) { + panel.classList.remove('active'); + panel.style.display = 'none'; + }); + } + function getActiveAdminTabName() { + return activeAdminTabName; + } + function activateAdminTab(tabName) { + var panelId = ADMIN_PANEL_MAP[tabName]; + var panel = panelId ? document.getElementById(panelId) : null; + if (!panel) return; + activeAdminTabName = tabName; + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.classList.toggle('active', tab.dataset.tab === tabName); + }); + hideAllAdminPanels(); + panel.style.display = ''; + panel.classList.add('active'); + runTabLoader(tabName); + } + function renderAdminTabs(items) { + var knownItems = (items || []).filter(function (item) { + return !!ADMIN_PANEL_MAP[item.route_path]; + }); + if (!knownItems.length) { + activeAdminTabName = ''; + if (adminTabsEl) adminTabsEl.innerHTML = '
鏆傛棤鍙敤鑿滃崟
'; + hideAllAdminPanels(); + return; + } + if (adminTabsEl) { + adminTabsEl.innerHTML = knownItems.map(function (item) { + return '
' + (item.name || item.route_path) + '
'; + }).join(''); + } + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.onclick = function () { + activateAdminTab(tab.dataset.tab); + }; + }); + var fallbackTab = activeAdminTabName && knownItems.some(function (item) { return item.route_path === activeAdminTabName; }) + ? activeAdminTabName + : knownItems[0].route_path; + activateAdminTab(fallbackTab); + } + function loadAdminMenus(preferredTab) { + if (preferredTab) activeAdminTabName = preferredTab; + fetch('/api/admin/current-user/menus') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + if (adminTabsEl) adminTabsEl.innerHTML = '
鑿滃崟鍔犺浇澶辫触
'; + hideAllAdminPanels(); + return; + } + renderAdminTabs(res.items || []); + }) + .catch(function () { + if (adminTabsEl) adminTabsEl.innerHTML = '
鑿滃崟鍔犺浇澶辫触
'; + hideAllAdminPanels(); + }); + } + hideAllAdminPanels(); + + // ========== 鐢ㄦ埛绠$悊 ========== + var userPage = 1, userPageSize = 15; + var currentUserId = null; + var currentUserRole = 'admin'; + var currentUserUsername = ''; + var adminsList = []; + function roleLabel(role) { + if (role === 'super_admin') return '瓒呯骇绠$悊鍛?; + if (role === 'admin') return '绠$悊鍛?; + return '鏅€氳处鍙?; + } + function buildUserListQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + userPageSize; + var kw = (document.getElementById('searchUsername').value || '').trim(); + if (kw) q += '&username=' + encodeURIComponent(kw); + var cby = document.getElementById('filterCreatedBy').value; + if (cby) q += '&created_by_id=' + encodeURIComponent(cby); + return q; + } + function loadUsers(page) { + userPage = page || 1; + fetch('/api/admin/users?' + buildUserListQuery(userPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('userListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + currentUserId = res.current_user_id || null; + currentUserRole = res.current_user_role || 'admin'; + currentUserUsername = (res.current_user_username || '').trim(); + adminsList = res.admins || []; + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鐢ㄦ埛'; + } else { + tbody.innerHTML = items.map(function (u) { + return '' + u.id + '' + (u.username || '') + '' + + roleLabel(u.role || 'normal') + '' + (u.creator_username || '-') + '' + (u.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('userPagination', res.total, res.page, res.page_size, loadUsers); + bindUserActions(); + updateCreateFormByRole(); + updateUserFilterByRole(); + }) + .catch(function () { + document.getElementById('userListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function updateUserFilterByRole() { + var grp = document.getElementById('filterCreatedByGroup'); + var sel = document.getElementById('filterCreatedBy'); + if (currentUserRole === 'super_admin') { + grp.style.display = 'block'; + var cur = sel.value; + sel.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + sel.appendChild(opt); + }); + sel.value = cur || ''; + } else { + grp.style.display = 'none'; + } + } + + function updateDedupeTotalDataAccess() { + var tab = document.querySelector('.tab[data-tab="dedupe-total-data"]'); + var panel = document.getElementById('panel-dedupe-total-data'); + var canUse = currentUserRole === 'super_admin' || (currentUserRole === 'admin' && currentUserUsername === ''); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function updateShopManageAccess() { + var tab = document.querySelector('.tab[data-tab="shop-manage"]'); + var panel = document.getElementById('panel-shop-manage'); + if (!tab || !panel) return; + var canUse = currentUserRole === 'super_admin' || + !!currentUserAdminPermissionKeys['admin_shop_manage'] || + !!currentUserAdminPermissionRoutes['shop-manage']; + tab.style.display = canUse ? '' : 'none'; + panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab.classList.contains('active')) { + tab.classList.remove('active'); + panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + updateShopManageAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + updateShopManageAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + updateShopManageAccess(); + }) + .catch(function () { + updateShopManageAccess(); + }); + } + function applyTabAccess(tabName, canUse) { + var tab = document.querySelector('.tab[data-tab="' + tabName + '"]'); + var panel = document.getElementById('panel-' + tabName); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function hasAdminTabAccess(tabName) { + var config = ADMIN_TAB_ACCESS_CONFIG[tabName]; + if (!config) return true; + if (currentUserRole === 'super_admin') return true; + if (config.superAdminOnly) return false; + return !!currentUserAdminPermissionKeys[config.columnKey] || + !!currentUserAdminPermissionRoutes[config.routePath]; + } + function refreshAdminTabAccess() { + Object.keys(ADMIN_TAB_ACCESS_CONFIG).forEach(function (tabName) { + applyTabAccess(tabName, hasAdminTabAccess(tabName)); + }); + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + refreshAdminTabAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + refreshAdminTabAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + refreshAdminTabAccess(); + }) + .catch(function () { + refreshAdminTabAccess(); + }); + } + var allColumnsList = []; + function loadColumnsForPermission() { + fetch('/api/admin/columns?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) return; + allColumnsList = res.items || []; + renderColumnPermissionWrap('createColumnPermissionWrap'); + renderColumnPermissionWrap('editColumnPermissionWrap'); + var selCreate = document.getElementById('createColumnPermissionWrap'); + var selEdit = document.getElementById('editColumnPermissionWrap'); + if (selCreate && !selCreate._colCardsBound) { + selCreate._colCardsBound = true; + selCreate.onchange = function () { renderColumnCards('createColumnPermissionWrap'); }; + } + if (selEdit && !selEdit._colCardsBound) { + selEdit._colCardsBound = true; + selEdit.onchange = function () { renderColumnCards('editColumnPermissionWrap'); }; + } + }) + .catch(function () { }); + } + var columnCardsContainerMap = { createColumnPermissionWrap: 'createColumnCards', editColumnPermissionWrap: 'editColumnCards' }; + function renderColumnCards(selectId) { + var sel = document.getElementById(selectId); + var cardsId = columnCardsContainerMap[selectId]; + var cardsEl = cardsId ? document.getElementById(cardsId) : null; + if (!sel || sel.tagName !== 'SELECT' || !cardsEl) return; + cardsEl.innerHTML = ''; + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled || !opt.selected) continue; + var card = document.createElement('span'); + card.className = 'column-permission-card'; + card.textContent = opt.textContent; + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'col-card-remove'; + btn.setAttribute('aria-label', '绉婚櫎'); + btn.textContent = '脳'; + (function (option, seldId) { + btn.onclick = function () { + option.selected = false; + renderColumnCards(seldId); + }; + })(opt, selectId); + card.appendChild(btn); + cardsEl.appendChild(card); + } + } + function renderColumnPermissionWrap(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + sel.innerHTML = ''; + allColumnsList.forEach(function (c) { + var opt = document.createElement('option'); + opt.value = c.id; + opt.textContent = c.name + ' (' + c.column_key + ')'; + sel.appendChild(opt); + }); + if (allColumnsList.length === 0) { + var opt = document.createElement('option'); + opt.disabled = true; + opt.textContent = '鏆傛棤鑿滃崟锛岃鍏堝湪鈥滄爮鐩潈闄愰厤缃€濅腑鏂板鑿滃崟'; + sel.appendChild(opt); + } + renderColumnCards(wrapId); + } + function getSelectedColumnIds(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return []; + var ids = []; + for (var i = 0; i < sel.options.length; i++) { + if (sel.options[i].selected) { + var v = parseInt(sel.options[i].value, 10); + if (!isNaN(v)) ids.push(v); + } + } + return ids; + } + function setColumnPermissionCheckboxes(wrapId, columnIds) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + var set = {}; + (columnIds || []).forEach(function (id) { set[id] = true; }); + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled) continue; + opt.selected = set[parseInt(opt.value, 10)] || false; + } + renderColumnCards(wrapId); + } + function updateCreateFormByRole() { + var roleSel = document.getElementById('createRole'); + var optAdmin = document.getElementById('optAdmin'); + var formCreatedBy = document.getElementById('formGroupCreatedBy'); + var selCreatedBy = document.getElementById('createCreatedBy'); + if (currentUserRole === 'super_admin') { + if (optAdmin) optAdmin.style.display = ''; + formCreatedBy.style.display = (roleSel.value === 'normal') ? 'block' : 'none'; + selCreatedBy.innerHTML = ''; + (res.items || []).forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + var shopManageGroupUsers = []; + function refreshShopManageGroupUserSelect(selectedUserId) { + var sel = document.getElementById('shopManageGroupUserSelect'); + if (!sel) return; + var opts = ['']; + shopManageGroupUsers.forEach(function (u) { + opts.push(''); + }); + sel.innerHTML = opts.join(''); + if (selectedUserId != null && selectedUserId !== '') { + sel.value = String(selectedUserId); + } + syncShopManageGroupNameWithUser(); + } + function syncShopManageGroupNameWithUser() { + var sel = document.getElementById('shopManageGroupUserSelect'); + var input = document.getElementById('shopManageGroupInput'); + if (!sel || !input) return; + var selectedUser = null; + shopManageGroupUsers.some(function (u) { + if (String(u.id) === String(sel.value || '')) { + selectedUser = u; + return true; + } + return false; + }); + input.value = selectedUser ? (selectedUser.username || '') : ''; + } + function loadUserOptions() { + return fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var items = res.items || []; + shopManageGroupUsers = items.map(function (u) { + return { id: u.id, username: u.username || '', role: u.role || 'normal' }; + }); + refreshShopManageGroupUserSelect(document.getElementById('shopManageGroupUserSelect') ? document.getElementById('shopManageGroupUserSelect').value : ''); + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + items.forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + document.getElementById('btnFilterHistory').onclick = function () { loadHistory(1); }; + + // ========== 鏁版嵁鍘婚噸鎬绘暟鎹?========== + var dedupeTotalDataPage = 1, dedupeTotalDataPageSize = 15; + function buildDedupeTotalDataQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + dedupeTotalDataPageSize; + var keyword = (document.getElementById('searchDedupeTotalData').value || '').trim(); + if (keyword) q += '&keyword=' + encodeURIComponent(keyword); + return q; + } + function loadDedupeTotalData(page) { + dedupeTotalDataPage = page || 1; + fetch('/api/admin/dedupe-total-data?' + buildDedupeTotalDataQuery(dedupeTotalDataPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('dedupeTotalDataListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鎬绘暟鎹?/td>'; + } else { + tbody.innerHTML = items.map(function (item) { + return '' + item.id + '' + (item.data_value || '') + '' + (item.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('dedupeTotalDataPagination', res.total, res.page, res.page_size, loadDedupeTotalData); + bindDedupeTotalDataActions(); + }) + .catch(function () { + document.getElementById('dedupeTotalDataListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindDedupeTotalDataActions() { + document.querySelectorAll('[data-dedupe-total-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editDedupeTotalDataId').value = btn.dataset.dedupeTotalEdit || ''; + document.getElementById('editDedupeTotalDataValue').value = (btn.dataset.value || '').replace(/"/g, '"'); + document.getElementById('msgEditDedupeTotalData').textContent = ''; + document.getElementById('msgEditDedupeTotalData').className = 'msg'; + document.getElementById('editDedupeTotalDataModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-dedupe-total-delete]').forEach(function (btn) { + btn.onclick = function () { + var value = (btn.dataset.value || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鎬绘暟鎹€? + value + '鈥濆悧锛?)) return; + fetch('/api/admin/dedupe-total-data/' + btn.dataset.dedupeTotalDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadDedupeTotalData(dedupeTotalDataPage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnSearchDedupeTotalData').onclick = function () { loadDedupeTotalData(1); }; + var dedupeImportPollTimer = null; + var dedupeDeleteImportPollTimer = null; + function stopDedupeImportProgress() { + if (dedupeImportPollTimer) { + clearInterval(dedupeImportPollTimer); + dedupeImportPollTimer = null; + } + } + function stopDedupeDeleteImportProgress() { + if (dedupeDeleteImportPollTimer) { + clearInterval(dedupeDeleteImportPollTimer); + dedupeDeleteImportPollTimer = null; + } + } + function setDedupeImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataProgressWrap'); + var fill = document.getElementById('dedupeTotalDataProgressFill'); + var textEl = document.getElementById('dedupeTotalDataProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function setDedupeDeleteImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataDeleteProgressWrap'); + var fill = document.getElementById('dedupeTotalDataDeleteProgressFill'); + var textEl = document.getElementById('dedupeTotalDataDeleteProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function pollDedupeImport(importId) { + stopDedupeImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = res.error || '鏌ヨ瀵煎叆杩涘害澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeImportProgress(percent, '澶勭悊涓細宸插鐞?' + processedRows + ' / ' + totalRows + '锛屾柊澧?' + (progress.inserted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '瀵煎叆鎴愬姛锛氭€昏鏁?' + (progress.total_rows || 0) + '锛孉SIN 鏁伴噺 ' + (progress.asin_count || 0) + '锛屾柊澧?' + (progress.inserted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0); + document.getElementById('msgDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = progress.error_message || '瀵煎叆澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '鏌ヨ瀵煎叆杩涘害澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeImportPollTimer = setInterval(tick, 1000); + } + function pollDedupeDeleteImport(importId) { + stopDedupeDeleteImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/delete-import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = res.error || '鏌ヨ鍒犻櫎杩涘害澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeDeleteImportProgress(percent, '澶勭悊涓細宸插鐞?' + processedRows + ' / ' + totalRows + '锛屽垹闄?' + (progress.deleted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '鍒犻櫎鎴愬姛锛氭€昏鏁?' + (progress.total_rows || 0) + '锛孉SIN 鏁伴噺 ' + (progress.asin_count || 0) + '锛屽垹闄?' + (progress.deleted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0); + document.getElementById('msgDeleteDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = progress.error_message || '鍒犻櫎澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '鏌ヨ鍒犻櫎杩涘害澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeDeleteImportPollTimer = setInterval(tick, 1000); + } + + document.getElementById('btnAddDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataFile'); + var msgEl = document.getElementById('msgDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeImportProgress(); + document.getElementById('dedupeTotalDataProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 Excel 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '浠呮敮鎸?.xlsx 鎴?.xls 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeImportProgress(percent, '涓婁紶涓細' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '杩斿洖鏍煎紡閿欒' }; } + if (!res.success) { + msgEl.textContent = res.error || '瀵煎叆澶辫触'; + msgEl.className = 'msg err'; + return; + } + setDedupeImportProgress(100, '涓婁紶瀹屾垚锛屽悗绔鐞嗕腑...'); + pollDedupeImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnDeleteImportDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataDeleteFile'); + var msgEl = document.getElementById('msgDeleteDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeDeleteImportProgress(); + document.getElementById('dedupeTotalDataDeleteProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 Excel 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '浠呮敮鎸?.xlsx 鎴?.xls 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + if (!confirm('纭畾鎸?Excel 涓殑 ASIN 鎵归噺鍒犻櫎鍖归厤鐨勬€绘暟鎹悧锛?)) { + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/delete-import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeDeleteImportProgress(percent, '涓婁紶涓細' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '杩斿洖鏍煎紡閿欒' }; } + if (!res.success) { + msgEl.textContent = res.error || '鍒犻櫎澶辫触'; + msgEl.className = 'msg err'; + return; + } + setDedupeDeleteImportProgress(100, '涓婁紶瀹屾垚锛屽悗绔鐞嗕腑...'); + pollDedupeDeleteImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnSaveDedupeTotalData').onclick = function () { + var itemId = document.getElementById('editDedupeTotalDataId').value; + var value = (document.getElementById('editDedupeTotalDataValue').value || '').trim(); + var msgEl = document.getElementById('msgEditDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!value) { + msgEl.textContent = '璇峰~鍐欐€绘暟鎹€?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/dedupe-total-data/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data_value: value }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + loadDedupeTotalData(dedupeTotalDataPage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditDedupeTotalData').onclick = function () { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + }; + + // ========== 搴楅摵瀵嗛挜绠$悊 ========== + var shopKeyPage = 1, shopKeyPageSize = 15; + function buildShopKeyQuery(page) { + return 'page=' + (page || 1) + '&page_size=' + shopKeyPageSize; + } + function loadShopKeys(page) { + shopKeyPage = page || 1; + fetch('/api/admin/shop-keys?' + buildShopKeyQuery(shopKeyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopKeyListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤搴楅摵瀵嗛挜'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopKeyPage - 1) * shopKeyPageSize + index + 1; + return '' + rowNo + '' + (item.ziniao_account_name || '') + '' + (item.ziniao_token || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopKeyPagination', res.total, res.page, res.page_size, loadShopKeys); + bindShopKeyActions(); + }) + .catch(function () { + document.getElementById('shopKeyListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindShopKeyActions() { + document.querySelectorAll('[data-shop-key-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopKey || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopKeyId').value = item.id || ''; + document.getElementById('editShopKeyZiniaoAccountName').value = item.ziniao_account_name || ''; + document.getElementById('editShopKeyZiniaoToken').value = item.ziniao_token || ''; + document.getElementById('msgEditShopKey').textContent = ''; + document.getElementById('msgEditShopKey').className = 'msg'; + document.getElementById('editShopKeyModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-shop-key-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.ziniaoAccountName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎搴楅摵瀵嗛挜鈥? + name + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-key/' + btn.dataset.shopKeyDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopKeys(shopKeyPage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnCreateShopKey').onclick = function () { + var ziniaoAccountName = (document.getElementById('shopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('shopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '璇峰畬鏁村~鍐欑传楦熻处鍙峰悕绉般€佺传楦熶护鐗?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopKeyZiniaoAccountName').value = ''; + document.getElementById('shopKeyZiniaoToken').value = ''; + msgEl.textContent = res.msg || '鍒涘缓鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopKeys(1); + } else { + msgEl.textContent = res.error || '鍒涘缓澶辫触'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + document.getElementById('btnSaveShopKey').onclick = function () { + var itemId = document.getElementById('editShopKeyId').value; + var ziniaoAccountName = (document.getElementById('editShopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('editShopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgEditShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '璇峰畬鏁村~鍐欑传楦熻处鍙峰悕绉般€佺传楦熶护鐗?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopKeyModal').classList.remove('show'); + loadShopKeys(shopKeyPage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopKey').onclick = function () { + document.getElementById('editShopKeyModal').classList.remove('show'); + }; + + // ========== 搴楅摵绠$悊 ========== + var shopManagePage = 1, shopManagePageSize = 15; + var shopManageGroups = []; + + function buildShopManageQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + shopManagePageSize; + var groupId = (document.getElementById('shopManageFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('shopManageFilterShopName').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '鍔犺浇鍒嗙粍澶辫触'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function openShopManageGroupModal() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '鏆傛棤鍒嗙粍'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + document.getElementById('shopManageGroupInput').value = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鍒嗙粍鈥? + gname + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '鍒犻櫎澶辫触'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + function loadShopManage(page) { + shopManagePage = page || 1; + fetch('/api/admin/shop-manages?' + buildShopManageQuery(shopManagePage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopManageListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤搴楅摵'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopManagePage - 1) * shopManagePageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + (item.password || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopManagePagination', res.total, res.page, res.page_size, loadShopManage); + bindShopManageActions(); + }) + .catch(function () { + document.getElementById('shopManageListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + + function bindShopManageActions() { + document.querySelectorAll('[data-shop-manage-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopManage || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopManageId').value = item.id || ''; + document.getElementById('editShopManageShopName').value = item.shop_name || ''; + document.getElementById('editShopManageMallName').value = item.mall_name || ''; + document.getElementById('editShopManageAccount').value = item.account || ''; + document.getElementById('editShopManagePassword').value = item.password || ''; + document.getElementById('msgEditShopManage').textContent = ''; + document.getElementById('msgEditShopManage').className = 'msg'; + loadShopManageGroups(null, item.group_id).then(function () { + document.getElementById('editShopManageModal').classList.add('show'); + }); + }; + }); + document.querySelectorAll('[data-shop-manage-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.shopManageName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎搴楅摵鈥? + name + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage/' + btn.dataset.shopManageDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopManage(shopManagePage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnSearchShopManage').onclick = function () { + loadShopManage(1); + }; + document.getElementById('shopManageFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadShopManage(1); + } + }); + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = function () { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + }; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupName) { + msgEl.textContent = '璇疯緭鍏ュ垎缁勫悕绉?; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '鍔犺浇鍒嗙粍澶辫触'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function resetShopManageGroupForm() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + refreshShopManageGroupUserSelect(''); + } + + function openShopManageGroupModal() { + resetShopManageGroupForm(); + loadUserOptions() + .then(function () { return loadShopManageGroups(); }) + .then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '鏆傛棤鍒嗙粍'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.username || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + refreshShopManageGroupUserSelect(btn.dataset.shopGroupUserId || ''); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鍒嗙粍鈥? + gname + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '鍒犻櫎澶辫触'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + document.getElementById('shopManageGroupUserSelect').onchange = syncShopManageGroupNameWithUser; + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = resetShopManageGroupForm; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var userId = (document.getElementById('shopManageGroupUserSelect').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!userId || !groupName) { + msgEl.textContent = '璇烽€夋嫨鍏宠仈鐢ㄦ埛'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName, user_id: Number(userId) }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + resetShopManageGroupForm(); + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnCreateShopManage').onclick = function () { + var groupId = (document.getElementById('shopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('shopManageShopName').value || '').trim(); + var mallName = (document.getElementById('shopManageMallName').value || '').trim(); + var account = (document.getElementById('shopManageAccount').value || '').trim(); + var password = (document.getElementById('shopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸簵閾哄晢鍩庡悕銆佽处鍙枫€佸瘑鐮?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopManageGroupSelect').value = ''; + document.getElementById('shopManageShopName').value = ''; + document.getElementById('shopManageMallName').value = ''; + document.getElementById('shopManageAccount').value = ''; + document.getElementById('shopManagePassword').value = ''; + msgEl.textContent = res.msg || '鍒涘缓鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManage(1); + } else { + msgEl.textContent = res.error || '鍒涘缓澶辫触'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnSaveShopManage').onclick = function () { + var itemId = document.getElementById('editShopManageId').value; + var groupId = (document.getElementById('editShopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('editShopManageShopName').value || '').trim(); + var mallName = (document.getElementById('editShopManageMallName').value || '').trim(); + var account = (document.getElementById('editShopManageAccount').value || '').trim(); + var password = (document.getElementById('editShopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgEditShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸簵閾哄晢鍩庡悕銆佽处鍙枫€佸瘑鐮?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopManageModal').classList.remove('show'); + loadShopManage(shopManagePage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopManage').onclick = function () { + document.getElementById('editShopManageModal').classList.remove('show'); + }; + + // ========== 鐗堟湰绠$悊 ========== + // ========== 璺宠繃璺熶环 ASIN ========== + var skipPriceAsinPage = 1, skipPriceAsinPageSize = 15; + var chooseSkipPriceAsinShopPage = 1, chooseSkipPriceAsinShopPageSize = 10; + var skipPriceCountryColumns = [ + { code: 'DE', field: 'asin_de', label: '寰峰浗' }, + { code: 'UK', field: 'asin_uk', label: '鑻卞浗' }, + { code: 'FR', field: 'asin_fr', label: '娉曞浗' }, + { code: 'IT', field: 'asin_it', label: '鎰忓ぇ鍒? }, + { code: 'ES', field: 'asin_es', label: '瑗跨彮鐗? } + ]; + function buildChooseSkipPriceAsinShopQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + chooseSkipPriceAsinShopPageSize; + var groupId = (document.getElementById('chooseSkipPriceAsinShopGroupId').value || '').trim(); + var shopName = (document.getElementById('chooseSkipPriceAsinShopKeyword').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + function loadChooseSkipPriceAsinShops(page) { + chooseSkipPriceAsinShopPage = page || 1; + fetch('/api/admin/shop-manages?' + buildChooseSkipPriceAsinShopQuery(chooseSkipPriceAsinShopPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('chooseSkipPriceAsinShopListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (!items.length) { + tbody.innerHTML = '鏆傛棤搴楅摵'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (chooseSkipPriceAsinShopPage - 1) * chooseSkipPriceAsinShopPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + + '' + + ''; + }).join(''); + } + renderPagination('chooseSkipPriceAsinShopPagination', res.total, res.page, res.page_size, loadChooseSkipPriceAsinShops); + bindChooseSkipPriceAsinShopActions(); + }) + .catch(function () { + document.getElementById('chooseSkipPriceAsinShopListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindChooseSkipPriceAsinShopActions() { + document.querySelectorAll('[data-choose-skip-price-asin-shop]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('skipPriceAsinShopName').value = (btn.dataset.shopName || '').replace(/"/g, '"'); + if (!document.getElementById('skipPriceAsinGroupSelect').value && btn.dataset.groupId) { + document.getElementById('skipPriceAsinGroupSelect').value = btn.dataset.groupId; + } + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + }); + } + function openChooseSkipPriceAsinShopModal() { + var currentGroupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + if (currentGroupId) { + document.getElementById('chooseSkipPriceAsinShopGroupId').value = currentGroupId; + } + document.getElementById('chooseSkipPriceAsinShopKeyword').value = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + document.getElementById('chooseSkipPriceAsinShopModal').classList.add('show'); + loadChooseSkipPriceAsinShops(1); + } + function setupSkipPriceAsinShopPicker() { + var input = document.getElementById('skipPriceAsinShopName'); + var button = document.getElementById('btnChooseSkipPriceAsinShop'); + if (!input || !button) return; + var inputParent = input.parentNode; + if (inputParent && inputParent.style && inputParent.style.display === 'flex') return; + var legacyWrap = button.parentNode; + var wrapper = document.createElement('div'); + wrapper.style.display = 'flex'; + wrapper.style.gap = '8px'; + wrapper.style.alignItems = 'center'; + input.parentNode.insertBefore(wrapper, input); + wrapper.appendChild(input); + wrapper.appendChild(button); + button.style.whiteSpace = 'nowrap'; + button.style.marginTop = '0'; + if (legacyWrap && legacyWrap !== wrapper) { + legacyWrap.style.display = 'none'; + } + } + function getSelectedSkipPriceCountries() { + return Array.from(document.getElementById('skipPriceAsinCountries').selectedOptions).map(function (option) { + return option.value; + }); + } + function renderSkipPriceAsinInputs() { + var container = document.getElementById('skipPriceAsinInputs'); + var selectedCountries = getSelectedSkipPriceCountries(); + var existingValues = {}; + container.querySelectorAll('[data-skip-price-country-input]').forEach(function (input) { + existingValues[input.getAttribute('data-skip-price-country-input')] = input.value; + }); + if (!selectedCountries.length) { + container.innerHTML = '
璇烽€夋嫨鍥藉鍚庤緭鍏?ASIN
'; + return; + } + container.innerHTML = selectedCountries.map(function (countryCode) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + var value = existingValues[countryCode] || ''; + return '
' + + '' + label + '' + + '' + + '
'; + }).join(''); + } + function collectSkipPriceAsinMappings(countries) { + var mappings = {}; + for (var i = 0; i < countries.length; i++) { + var countryCode = countries[i]; + var input = document.querySelector('[data-skip-price-country-input="' + countryCode + '"]'); + var asin = input ? (input.value || '').trim().toUpperCase() : ''; + if (!asin) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + throw new Error(label + ' ASIN 涓嶈兘涓虹┖'); + } + mappings[countryCode] = asin; + } + return mappings; + } + function buildSkipPriceAsinQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + skipPriceAsinPageSize; + var groupId = (document.getElementById('skipPriceAsinFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinFilterShopName').value || '').trim(); + var asin = (document.getElementById('skipPriceAsinFilterAsin').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + if (asin) query += '&asin=' + encodeURIComponent(asin); + return query; + } + function renderSkipPriceAsinCell(item, country) { + var value = item[country.field] || ''; + 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, '"'); + var countryCode = btn.dataset.country || ''; + if (!confirm('纭畾鍒犻櫎搴楅摵鈥? + shopName + '鈥濆湪 ' + countryCode + ' 鐨?ASIN 鍚楋紵')) return; + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinDelete + '/country/' + countryCode, { + method: 'DELETE' + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '鍒犻櫎澶辫触'); + }); + }; + }); + } + function loadSkipPriceAsin(page) { + skipPriceAsinPage = page || 1; + fetch('/api/admin/skip-price-asins?' + buildSkipPriceAsinQuery(skipPriceAsinPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('skipPriceAsinListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鏁版嵁'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (skipPriceAsinPage - 1) * skipPriceAsinPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + + skipPriceCountryColumns.map(function (country) { + return '' + renderSkipPriceAsinCell(item, country) + ''; + }).join('') + + ''; + }).join(''); + } + renderPagination('skipPriceAsinPagination', res.total, res.page, res.page_size, loadSkipPriceAsin); + bindSkipPriceAsinActions(); + }) + .catch(function () { + document.getElementById('skipPriceAsinListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnChooseSkipPriceAsinShop').onclick = openChooseSkipPriceAsinShopModal; + document.getElementById('btnSearchChooseSkipPriceAsinShop').onclick = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopGroupId').onchange = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopKeyword').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadChooseSkipPriceAsinShops(1); + } + }); + document.getElementById('btnCloseChooseSkipPriceAsinShopModal').onclick = function () { + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + document.getElementById('skipPriceAsinCountries').addEventListener('change', renderSkipPriceAsinInputs); + document.getElementById('btnSearchSkipPriceAsin').onclick = function () { + loadSkipPriceAsin(1); + }; + document.getElementById('skipPriceAsinFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('skipPriceAsinFilterAsin').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('btnCreateSkipPriceAsin').onclick = function () { + var groupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + var countries = getSelectedSkipPriceCountries(); + var msgEl = document.getElementById('msgSkipPriceAsin'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !countries.length) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸浗瀹跺拰 ASIN'; + msgEl.className = 'msg err'; + return; + } + var asinMappings = {}; + try { + asinMappings = collectSkipPriceAsinMappings(countries); + } catch (err) { + msgEl.textContent = err.message || '璇疯緭鍏?ASIN'; + msgEl.className = 'msg err'; + return; + } + var fallbackAsin = ''; + Object.keys(asinMappings).some(function (countryCode) { + fallbackAsin = asinMappings[countryCode] || ''; + return !!fallbackAsin; + }); + fetch('/api/admin/skip-price-asin', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + group_id: Number(groupId), + shop_name: shopName, + countries: countries, + asin: fallbackAsin, + asin_mappings: asinMappings + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('skipPriceAsinGroupSelect').value = ''; + document.getElementById('skipPriceAsinShopName').value = ''; + Array.from(document.getElementById('skipPriceAsinCountries').options).forEach(function (option) { + option.selected = false; + }); + renderSkipPriceAsinInputs(); + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadSkipPriceAsin(1); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + setupSkipPriceAsinShopPicker(); + renderSkipPriceAsinInputs(); + function loadVersions() { + fetch('/api/admin/versions') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('versionListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鐗堟湰璁板綍'; + } else { + tbody.innerHTML = items.map(function (v) { + var url = (v.file_url || '').replace(/"/g, '"'); + return '' + (v.version || '') + '' + url + '' + (v.created_at || '') + '涓嬭浇'; + }).join(''); + } + }) + .catch(function () { + document.getElementById('versionListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + document.getElementById('btnUploadVersion').onclick = function () { + var version = (document.getElementById('versionNumber').value || '').trim(); + var fileInput = document.getElementById('versionZip'); + var msgEl = document.getElementById('msgVersion'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!version) { + msgEl.textContent = '璇峰~鍐欑増鏈彿'; + msgEl.classList.add('err'); + return; + } + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 zip 鍘嬬缉鍖?; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + if (!(file.name || '').toLowerCase().endsWith('.zip')) { + msgEl.textContent = '浠呮敮鎸?.zip 鏍煎紡'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('version', version); + formData.append('file', file); + msgEl.textContent = '涓婁紶涓?..'; + msgEl.classList.remove('err', 'ok'); + fetch('/api/admin/version', { + method: 'POST', + body: formData + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = '鍙戝竷鎴愬姛銆傜増鏈細' + res.version + '锛岄摼鎺ワ細' + (res.file_url || ''); + msgEl.classList.add('ok'); + document.getElementById('versionNumber').value = ''; + fileInput.value = ''; + loadVersions(); + } else { + msgEl.textContent = res.error || '涓婁紶澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + + // ========== 鏍忕洰鏉冮檺閰嶇疆 ========== + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '鏆傛棤鑿滃崟锛岃鍦ㄤ笂鏂规柊澧?/td>'; + } else { + tbody.innerHTML = allColumnsList.map(function (c) { + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + (c.created_at || '') + '' + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('纭畾鍒犻櫎鑿滃崟鈥? + (btn.dataset.name || '').replace(/"/g, '"') + '鈥濆悧锛?)) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '璇峰~鍐欒彍鍗曞悕绉?; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '璇峰~鍐欐爮鐩爣璇?; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '鏂板鎴愬姛'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { diff --git a/backend/web_source/admin.html b/backend/web_source/admin.html index 1fc9406..82837a5 100644 --- a/backend/web_source/admin.html +++ b/backend/web_source/admin.html @@ -1,20 +1,85 @@ - + + 管理后台 - 南日AI + - +

管理后台

-
+
+ 加载中... + + +
+ +
用户管理
栏目权限配置
数据去重总数据
@@ -120,22 +414,23 @@
-
+

创建用户

-

无注册入口,仅管理员可在此创建用户。层级:超级管理员 → 管理员 → 普通号。

+

+ 当前没有开放注册入口,仅管理员可在此创建用户。层级关系:超级管理员 -> 管理员 -> 普通账号。

- +
- +
@@ -146,7 +441,7 @@
- +
@@ -189,21 +484,32 @@
-

新增栏目

+

新增菜单

- - + +
-
+
- +
- +
+ + +
+
+ + +
+

@@ -213,8 +519,10 @@ ID - 栏目名 + 菜单名称 栏目标识 + 菜单类型 + 排序 菜单路由 创建时间 操作 @@ -271,7 +579,9 @@

@@ -286,7 +596,9 @@

@@ -299,7 +611,7 @@
- + @@ -325,11 +637,11 @@ -
+
- +

@@ -370,7 +682,7 @@ -
+
@@ -378,11 +690,11 @@
-
+
- +

@@ -439,8 +751,12 @@ -
+
+
+ + +
-
+
- +
+
请选择国家后输入对应 ASIN
+
@@ -544,13 +862,13 @@
- +
@@ -559,7 +877,7 @@
- +
@@ -580,7 +898,7 @@ -

+

@@ -594,10 +912,10 @@

编辑栏目

- - + +
-
+
@@ -605,6 +923,17 @@
+
+ + +
+
+ + +

@@ -619,9 +948,16 @@

分组管理

+
+ + +
- +
@@ -629,7 +965,14 @@

- + + + + + + + +
序号分组名称创建时间修改时间操作
序号分组名称关联用户创建时间修改时间操作
@@ -640,6 +983,44 @@ + +