diff --git a/app/.env b/app/.env index 8a4270d..991dfad 100644 --- a/app/.env +++ b/app/.env @@ -12,8 +12,8 @@ zn_username=%E8%87%AA%E5%8A%A8%E5%8C%96_Robot client_name=ShuFuAI -# java_api_base=http://47.111.163.154:18080 +java_api_base=http://47.111.163.154:18080 # java_api_base=http://127.0.0.1:18080 -java_api_base=http://8.136.19.173:18080 +# java_api_base=http://8.136.19.173:18080 diff --git a/app/__pycache__/config.cpython-312.pyc b/app/__pycache__/config.cpython-312.pyc index b3d22e5..ed70141 100644 Binary files a/app/__pycache__/config.cpython-312.pyc and b/app/__pycache__/config.cpython-312.pyc differ diff --git a/app/assets/delete-brand.js b/app/assets/delete-brand.js index d4d3a73..169f21a 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 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-ClWy2SbE.js";import{e as ds}from"./brand-DBpLCgAF.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"); +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-ClWy2SbE.js";import{e as ds}from"./brand-DBpLCgAF.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"},Es={class:"task-list-wrap"},Fs={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"},Ls={class:"files"},Us={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 $(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const A=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),P=y(!1),D=y(""),Q=y(!1),L=y(null),se=J(()=>A.value.slice(0,10)),E=J(()=>{const e=[];return i.value.forEach(s=>{e.push(...s.items)}),e});function Me(){try{const e=typeof window<"u"?window.localStorage.getItem($()):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($(),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($(),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=>!E.value.some(s=>M(s,e)))),qe=J(()=>E.value.length>0||X.value.length>0),Le=J(()=>E.value.filter(e=>Re(e)&&F(e)==="未入队"));function ne(){typeof window<"u"&&(i.value.length===0?window.localStorage.removeItem($()):window.localStorage.setItem($(),JSON.stringify(i.value)))}function R(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 x(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=R(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=R(s),o=F(e);if(a){const r=x(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 Ue(){fe.value=[...E.value,...X.value]}function N(){Ue(),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(R(s)){const u=x(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(`${R(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(R(s)){const r=x(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 U(){const e=new Set;return i.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function F(e){const s=e.taskId;if(!s||!ae(s))return"";const n=x(s,e),a=_e(s),o=g.value[s]?.line_progress,r=R(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||U();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&&N()}catch(t){const n=(t instanceof Error?t.message:String(t||"")).toLowerCase();["无法连接到后端服务","bad gateway","gateway timeout","network error","timeout","502","503","504"].some(o=>n.includes(o.toLowerCase()))&&P.value&&(b.value="当前任务运行中,正在等待后端服务恢复...")}}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=U();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&&N(),U().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;A.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}A.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),N(),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),N(),await re(),ue(!0)}catch(e){const s=(e instanceof Error?e.message:String(e||"")).toLowerCase();["无法连接到后端服务","bad gateway","gateway timeout","network error","timeout","502","503","504"].some(n=>s.includes(n.toLowerCase()))||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($(),JSON.stringify(i.value)),q.value=q.value.filter(t=>t.resultId!==e),N(),U().length===0&&be()}async function Ee(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 Fe(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(){L.value&&(window.clearTimeout(L.value),L.value=null)}function ze(e=3e3){ie(),L.value=window.setTimeout(()=>{L.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=F(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 E.value.find(e=>!Re(e)||K(e)===D.value||x(e.taskId,e)?._completed?!1:F(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=x(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,P.value=!0,ie();const s=await Ne(e);if(V.value=!1,!s.success){P.value=!1,D.value="";return}p.success("已开始按顺序推送到 Python 队列")}async function $e(){if(!P.value||Q.value){P.value,Q.value;return}if(Pe())return;const e=D.value;if(e){const t=E.value.find(n=>K(n)===e);if(t){const n=t.taskId,a=R(n);a&&(pe(n),F(t),void 0);const o=F(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(a){const r=x(n,t);if(r&&!r._completed){t.sourceFilename,r._pushed,r._completed;return}}}}const s=xe();if(!s){D.value="",P.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,P.value=!1}}finally{Q.value=!1}}return Ye(()=>{Me();const e=U();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&&N(),ue(!0)}):N(),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,[A.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)),A.value.length>se.value.length?(d(),f("span",ys," 还有 "+v(A.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||!Le.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",Es,[l("div",Fs,[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},[E.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(E.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",Ls,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",Us,"平台:"+v(t.platform),1)):h("",!0),F(t)?(d(),f("div",Os,"队列状态:"+v(F(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(Fe(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=>Ee(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(Fe(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=>Ee(t.resultId)}," 删除 ",8,_t)):h("",!0)])]))),128))])])):h("",!0)],64)):(d(),f("div",$s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),gt=us(yt,[["__scopeId","data-v-b6259516"]]);is(gt).use(cs).mount("#app"); diff --git a/app/main.py b/app/main.py index 08586b0..0286722 100644 --- a/app/main.py +++ b/app/main.py @@ -434,7 +434,7 @@ def main(): window.expose(api.close, api.minimize, api.maximize, api.toggle_maximize, generate_images, api.save_image, api.save_image_to_folder, api.select_folder, api.select_brand_xlsx_files, api.select_brand_folder, api.save_file_from_url, api.save_template_xlsx,api.save_template_zip,api.upload_file_to_java,api.open_external_url,api.enqueue_json,api.get_detail_del,api.save_file_from_url_new) webview.start( - debug=False, + debug=True, storage_path=cache_path, private_mode=False ) diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html index 630def6..1ed24f6 100644 --- a/app/new_web_source/delete-brand.html +++ b/app/new_web_source/delete-brand.html @@ -8,7 +8,7 @@ - +
diff --git a/app/version.txt b/app/version.txt index 52a718a..a0374f4 100644 --- a/app/version.txt +++ b/app/version.txt @@ -1 +1 @@ -{"version": "1.0.13"} \ No newline at end of file +{"version": "1.0.56"} \ No newline at end of file diff --git a/backend-java/aiimage-backend.log.2026-04-19.0.gz b/backend-java/aiimage-backend.log.2026-04-19.0.gz new file mode 100644 index 0000000..bb38944 Binary files /dev/null and b/backend-java/aiimage-backend.log.2026-04-19.0.gz differ 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 a003416..5b45afd 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 @@ -238,9 +238,10 @@ public class DeleteBrandStaleTaskService { runningTasks.size(), threshold, minutes, initialThreshold, initialMinutes); for (FileTaskEntity task : runningTasks) { long lastHeartbeatMillis = priceTrackTaskCacheService.getTaskHeartbeatMillis(task.getId()); + boolean hasUploadedPayload = priceTrackTaskCacheService.hasAnyShopMergedPayload(task.getId()); boolean hasFinishedRows = (task.getSuccessFileCount() != null && task.getSuccessFileCount() > 0) || (task.getFailedFileCount() != null && task.getFailedFileCount() > 0); - boolean hasStartedProgress = lastHeartbeatMillis > 0L || hasFinishedRows; + boolean hasStartedProgress = lastHeartbeatMillis > 0L || hasUploadedPayload || hasFinishedRows; if (lastHeartbeatMillis > 0L && nowMillis - lastHeartbeatMillis < staleTimeoutMillis) { stats.skippedTaskCount++; continue; 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 b766696..5482cd0 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 @@ -209,9 +209,20 @@ public class PriceTrackController { } @PostMapping("/tasks/{taskId}/result") - @Operation(summary = "Python 回传处理结果", description = "同一 taskId 可多次回传。成功时按 countries 生成结果文件,所有店铺进入终态后任务会变为 SUCCESS 或 FAILED。") + @Operation( + summary = "Python 回传处理结果", + description = "同一 taskId 支持多次回传。后端会先按店铺合并缓存,再在该店铺 success=true 时组装最终结果文件。" + + "未完成/处理中:本次只传增量行数据,shop.success 不传或传 null,后端仅合并缓存继续等待。" + + "已完成:传最后一批数据并设置 shop.success=true,后端会使用该店铺累计后的完整数据出结果。" + + "失败:传 shop.success=false 或传非空 shop.error。" + + "行级数据只保留表头字段:shopMallName、asin、price、recommendedPrice、minimumPrice、firstPlace、secondPlace、cartShopName、priceChangeStatus、modifyCount、status。" + ) public ApiResponse submitResult( - @Parameter(description = "任务主键,必须处于 RUNNING 状态", example = "200") @PathVariable Long taskId, + @Parameter( + description = "任务主键,必须处于 RUNNING 状态", + example = "200" + ) + @PathVariable Long taskId, @Valid @RequestBody PriceTrackSubmitResultRequest request) { priceTrackTaskService.submitResult(taskId, request); return ApiResponse.success(null); 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 37c5849..d850686 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,73 +7,91 @@ import java.util.List; import java.util.Map; @Data -@Schema(description = "Python submit payload for price track task results") +@Schema( + description = "跟价任务结果回传请求体。" + + "同一 taskId 支持多次回传。" + + "未完成的店铺可分批回传,shop.success 不传或传 null 即可;" + + "店铺最终完成时传 shop.success=true,后端会基于该店铺累计数据组装结果文件;" + + "店铺失败时传 shop.success=false 或传非空的 shop.error。" +) public class PriceTrackSubmitResultRequest { - @Schema(description = "Shop result list", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema( + description = "店铺结果列表。一次请求可以提交一个或多个店铺的数据。", + requiredMode = Schema.RequiredMode.REQUIRED + ) private List shops; @Data - @Schema(description = "Per-shop submit result") + @Schema( + description = "单个店铺的回传结果。" + + "处理中/未完成时,success 不传或传 null;" + + "店铺最终完成时传 success=true;" + + "店铺失败时传 success=false 或 error 非空。" + ) public static class ShopResult { - @Schema(description = "Shop name used to match task rows", example = "Test Shop A") + @Schema(description = "店铺名称,用于和任务中的店铺结果行进行匹配", example = "测试店铺A") private String shopName; - @Schema(description = "Rows grouped by country code, for example DE/UK/FR/IT/ES") + @Schema( + description = "按国家代码分组的结果行,例如 DE、UK、FR、IT、ES。" + + "每一行只允许保留最终表头中的字段。" + ) private Map> countries; - @Schema(description = "Failure message") + @Schema( + description = "失败信息。非空时后端会将该店铺标记为失败,并停止等待该店铺后续回传。", + example = "" + ) private String error; - @Schema(description = "Whether the shop finished successfully") + @Schema( + description = "店铺完成标记。" + + "不传或传 null 表示本次只是部分回传,后端仅合并缓存并继续等待;" + + "true 表示该店铺已全部完成,后端会组装最终结果文件;" + + "false 表示该店铺处理失败。", + example = "true" + ) private Boolean success; } @Data - @Schema(description = "Per-ASIN price track result row") + @Schema( + description = "单条 ASIN 跟价结果行。" + + "只保留最终表头字段。" + + "不要再传旧字段,如 currentPrice、competitorPrice、action、done。" + ) public static class AsinResult { - @Schema(description = "Shop mall name", example = "Amazon.de") + @Schema(description = "店铺商城名称", example = "Amazon.de") private String shopMallName; @Schema(description = "ASIN", example = "B0ABCDE123") private String asin; - @Schema(description = "Price", example = "19.99") + @Schema(description = "价格", example = "19.99") private String price; - @Schema(description = "Recommended price", example = "18.99") + @Schema(description = "推荐价", example = "18.99") private String recommendedPrice; - @Schema(description = "Lowest price", example = "18.50") + @Schema(description = "最低价", example = "18.50") private String minimumPrice; - @Schema(description = "First place", example = "Competitor A") + @Schema(description = "第一名", example = "竞对A") private String firstPlace; - @Schema(description = "Second place", example = "Competitor B") + @Schema(description = "第二名", example = "竞对B") private String secondPlace; - @Schema(description = "Buy box shop name", example = "Shop A") + @Schema(description = "购物车店铺名", example = "店铺A") private String cartShopName; - @Schema(description = "Price change status", example = "UPDATED") + @Schema(description = "改价情况", example = "UPDATED") private String priceChangeStatus; - @Schema(description = "Modify count", example = "2") + @Schema(description = "修改次数", example = "2") private String modifyCount; - @Schema(description = "Status", example = "SUCCESS") + @Schema(description = "状态", example = "SUCCESS") private String status; - - @Schema(description = "Legacy current price", example = "19.99") - private String currentPrice; - - @Schema(description = "Legacy competitor price", example = "18.50") - private String competitorPrice; - - @Schema(description = "Legacy action", example = "LOWER_PRICE") - private String action; - - @Schema(description = "Legacy done flag") - private Boolean done; } } 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 8e5a86c..6d220f0 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 @@ -27,6 +27,9 @@ public class PriceTrackMatchShopsVo { @Schema(description = "Shop name", example = "Demo Shop") private String shopName; + @Schema(description = "Shop mall name", example = "Amazon.de") + private String shopMallName; + @Schema(description = "Matched shop id") private Object shopId; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java index e97d76f..444e775 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackResultItemVo.java @@ -17,6 +17,9 @@ public class PriceTrackResultItemVo { @Schema(description = "店铺名称,详情页会尽量恢复创建任务时的展示名") private String shopName; + @Schema(description = "Shop mall name") + private String shopMallName; + @Schema(description = "店铺 ID(紫鸟)") private Object shopId; 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 4b4d03f..f1adb09 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 @@ -52,15 +52,15 @@ public class PriceTrackExcelAssemblyService { Row row = sheet.createRow(rowIdx++); 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(2).setCellValue(valueOf(item.getPrice())); row.createCell(3).setCellValue(valueOf(item.getRecommendedPrice())); - row.createCell(4).setCellValue(firstNonBlank(item.getMinimumPrice(), item.getCompetitorPrice())); + row.createCell(4).setCellValue(valueOf(item.getMinimumPrice())); 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(8).setCellValue(valueOf(item.getPriceChangeStatus())); row.createCell(9).setCellValue(valueOf(item.getModifyCount())); - row.createCell(10).setCellValue(firstNonBlank(item.getStatus(), item.getDone() == null ? null : String.valueOf(item.getDone()))); + row.createCell(10).setCellValue(valueOf(item.getStatus())); } for (int i = 0; i < RESULT_HEADER.length; i++) { sheet.autoSizeColumn(i); @@ -105,15 +105,4 @@ public class PriceTrackExcelAssemblyService { 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 9f0f285..3792c0a 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 @@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCandidateVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCountryPreferenceVo; import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo; import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; +import com.nanri.aiimage.modules.shopkey.service.ShopManageService; import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo; import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService; import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService; @@ -43,6 +44,7 @@ public class PriceTrackService { private final ZiniaoShopSwitchService ziniaoShopSwitchService; private final SkipPriceAsinService skipPriceAsinService; private final PriceTrackTaskService priceTrackTaskService; + private final ShopManageService shopManageService; public List listCandidates(Long userId) { if (userId == null || userId <= 0) { @@ -220,6 +222,7 @@ public class PriceTrackService { ) { PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem(); item.setShopName(shopName); + item.setShopMallName(resolveShopMallName(shopName)); item.setSkipAsins(skipAsins == null ? new LinkedHashMap<>() : new LinkedHashMap<>(skipAsins)); try { ZiniaoShopMatchResultVo match = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); @@ -247,6 +250,14 @@ public class PriceTrackService { return item; } + private String resolveShopMallName(String shopName) { + try { + return shopManageService.findMallNameByShopName(shopName); + } catch (Exception ignored) { + return null; + } + } + private static List sanitizeStoredCodes(List raw) { List parsed = parseValidCountryCodes(raw); if (parsed.isEmpty()) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java index 5116aea..20a0ce9 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskCacheService.java @@ -1,11 +1,16 @@ package com.nanri.aiimage.modules.pricetrack.service; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; @Service @RequiredArgsConstructor @@ -14,6 +19,7 @@ public class PriceTrackTaskCacheService { private static final long HEARTBEAT_TTL_HOURS = 24; private final StringRedisTemplate stringRedisTemplate; + private final ObjectMapper objectMapper; public void touchTaskHeartbeat(Long taskId) { if (taskId == null || taskId <= 0) { @@ -40,13 +46,80 @@ public class PriceTrackTaskCacheService { } } + public PriceTrackSubmitResultRequest.ShopResult getShopMergedPayload(Long taskId, String shopKey) { + if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { + return null; + } + Object raw = stringRedisTemplate.opsForHash().get(buildShopPayloadKey(taskId), shopKey); + if (!(raw instanceof String json) || json.isBlank()) { + return null; + } + try { + return objectMapper.readValue(json, PriceTrackSubmitResultRequest.ShopResult.class); + } catch (Exception ex) { + throw new BusinessException("read price-track cache failed"); + } + } + + public void saveShopMergedPayload(Long taskId, String shopKey, PriceTrackSubmitResultRequest.ShopResult payload) { + if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) { + return; + } + try { + stringRedisTemplate.opsForHash().put(buildShopPayloadKey(taskId), shopKey, objectMapper.writeValueAsString(payload)); + stringRedisTemplate.expire(buildShopPayloadKey(taskId), Duration.ofHours(HEARTBEAT_TTL_HOURS)); + touchTaskHeartbeat(taskId); + } catch (Exception ex) { + throw new BusinessException("save price-track cache failed"); + } + } + + public void removeShopMergedPayload(Long taskId, String shopKey) { + if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { + return; + } + stringRedisTemplate.opsForHash().delete(buildShopPayloadKey(taskId), shopKey); + } + + public Map getAllShopMergedPayload(Long taskId) { + try { + Map raw = stringRedisTemplate.opsForHash().entries(buildShopPayloadKey(taskId)); + if (raw == null || raw.isEmpty()) { + 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; + } + out.put(key, objectMapper.readValue(val, PriceTrackSubmitResultRequest.ShopResult.class)); + } + return out; + } catch (Exception ex) { + throw new BusinessException("read price-track cache failed"); + } + } + + public boolean hasAnyShopMergedPayload(Long taskId) { + if (taskId == null || taskId <= 0) { + return false; + } + Long size = stringRedisTemplate.opsForHash().size(buildShopPayloadKey(taskId)); + return size != null && size > 0; + } + public void deleteTaskCache(Long taskId) { if (taskId == null || taskId <= 0) { return; } + stringRedisTemplate.delete(buildShopPayloadKey(taskId)); stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId)); } + private String buildShopPayloadKey(Long taskId) { + return "price-track:task:shop-payload:" + taskId; + } + private String buildTaskHeartbeatKey(Long taskId) { return "price-track:task:heartbeat:" + taskId; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java index 87e4999..b66815a 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 @@ -323,49 +323,63 @@ public class PriceTrackTaskService { log.warn("[price-track] submitResult rejected taskId={} status={}", taskId, task.getStatus()); throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } - priceTrackTaskCacheService.touchTaskHeartbeat(taskId); List resultRows = fileResultMapper.selectList( new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) .eq(FileResultEntity::getModuleType, MODULE_TYPE) .orderByAsc(FileResultEntity::getId)); - Map payloadByShop = new LinkedHashMap<>(); for (PriceTrackSubmitResultRequest.ShopResult sr : request.getShops()) { if (sr == null) continue; String key = ziniaoShopSwitchService.normalizeShopName(sr.getShopName()); if (!key.isBlank()) payloadByShop.put(key, sr); } - + log.info("[price-track] submitResult received taskId={} payloadShopCount={} payloadKeys={}", + taskId, payloadByShop.size(), payloadByShop.keySet()); + boolean changed = false; for (FileResultEntity fr : resultRows) { String shopKey = fr.getSourceFilename(); PriceTrackSubmitResultRequest.ShopResult payload = shopKey == null ? null : payloadByShop.get(shopKey); if (payload == null) { - // 当前批次没有该店铺的 payload,保持待处理 continue; } + changed = true; if (payload.getError() != null && !payload.getError().isBlank()) { markResultFailed(fr, payload.getError()); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); continue; } if (Boolean.FALSE.equals(payload.getSuccess())) { - markResultFailed(fr, "店铺处理失败"); + markResultFailed(fr, "shop processing failed"); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); + continue; + } + PriceTrackSubmitResultRequest.ShopResult merged = mergeShopPayload(taskId, shopKey, payload); + if (!Boolean.TRUE.equals(merged.getSuccess())) { + continue; + } + if (countPayloadRows(merged) <= 0) { + markResultFailed(fr, "no usable price-track rows received"); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); continue; } try { - assembleShopResult(fr, shopKey, payload); + assembleShopResult(fr, shopKey, merged); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); } catch (Exception ex) { - markResultFailed(fr, ex.getMessage() == null ? "组装结果失败" : ex.getMessage()); + markResultFailed(fr, ex.getMessage() == null ? "assemble price-track result failed" : ex.getMessage()); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); } } - + if (!changed) { + return; + } List latest = fileResultMapper.selectList( new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) .eq(FileResultEntity::getModuleType, MODULE_TYPE) .orderByAsc(FileResultEntity::getId)); - updateTaskStatusFromLatestRows(task, latest); } @@ -380,7 +394,6 @@ public class PriceTrackTaskService { cleanupTaskCacheIfTerminal(taskId, task.getStatus()); return false; } - List latest = fileResultMapper.selectList( new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) @@ -388,28 +401,61 @@ public class PriceTrackTaskService { .orderByAsc(FileResultEntity::getId)); if (latest.isEmpty()) { task.setStatus("FAILED"); - task.setErrorMessage("任务明细缺失,无法自动收尾"); + task.setErrorMessage("task details missing, cannot finalize automatically"); task.setUpdatedAt(LocalDateTime.now()); task.setFinishedAt(LocalDateTime.now()); fileTaskMapper.updateById(task); cleanupTaskCacheIfTerminal(taskId, task.getStatus()); return true; } - + Map cachedPayloadByShop = + priceTrackTaskCacheService.getAllShopMergedPayload(taskId); boolean changed = false; for (FileResultEntity fr : latest) { boolean success = fr.getSuccess() != null && fr.getSuccess() == 1; boolean failed = fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank(); if (success || failed) continue; - markResultFailed(fr, "Python interrupted before this shop finished uploading results"); - changed = true; - log.warn("[price-track] stale finalize failed taskId={} shop={} fromCompensation={}", - taskId, fr.getSourceFilename(), fromCompensation); + String shopKey = fr.getSourceFilename(); + PriceTrackSubmitResultRequest.ShopResult cachedPayload = shopKey == null ? null : cachedPayloadByShop.get(shopKey); + if (cachedPayload == null) { + markResultFailed(fr, "Python interrupted before this shop finished uploading results"); + changed = true; + log.warn("[price-track] stale finalize failed without cache taskId={} shop={} fromCompensation={}", + taskId, shopKey, fromCompensation); + continue; + } + if (cachedPayload.getError() != null && !cachedPayload.getError().isBlank()) { + markResultFailed(fr, cachedPayload.getError()); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); + changed = true; + continue; + } + if (countPayloadRows(cachedPayload) <= 0) { + markResultFailed(fr, "no usable price-track rows received before interruption"); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); + changed = true; + log.warn("[price-track] stale finalize finished without data taskId={} shop={} fromCompensation={}", + taskId, shopKey, fromCompensation); + continue; + } + try { + assembleShopResult(fr, shopKey, cachedPayload); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); + changed = true; + log.warn("[price-track] stale finalize assembled taskId={} shop={} fromCompensation={} completedFlag={} rowCount={}", + taskId, shopKey, fromCompensation, Boolean.TRUE.equals(cachedPayload.getSuccess()), countPayloadRows(cachedPayload)); + } catch (Exception ex) { + String message = ex.getMessage() == null ? "assemble price-track result failed" : ex.getMessage(); + markResultFailed(fr, message); + priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey); + changed = true; + log.warn("[price-track] stale finalize assemble failed taskId={} shop={} msg={}", + taskId, shopKey, message); + } } - if (!changed) { + if (!changed && cachedPayloadByShop.isEmpty()) { return false; } - List refreshed = fileResultMapper.selectList( new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) @@ -723,6 +769,7 @@ public class PriceTrackTaskService { vo.setResultId(fr.getId()); vo.setTaskId(fr.getTaskId()); vo.setShopName(item.getShopName()); + vo.setShopMallName(item.getShopMallName()); vo.setShopId(item.getShopId()); vo.setPlatform(item.getPlatform()); vo.setCompanyName(item.getCompanyName()); @@ -799,6 +846,7 @@ public class PriceTrackTaskService { if (item == null) continue; if (key.equals(ziniaoShopSwitchService.normalizeShopName(item.getShopName()))) { vo.setShopName(item.getShopName()); + vo.setShopMallName(item.getShopMallName()); vo.setShopId(item.getShopId()); vo.setPlatform(item.getPlatform()); vo.setCompanyName(item.getCompanyName()); @@ -852,6 +900,113 @@ public class PriceTrackTaskService { return s.replaceAll("[\\\\/:*?\"<>|]", "_"); } + private PriceTrackSubmitResultRequest.ShopResult mergeShopPayload(Long taskId, + String shopKey, + PriceTrackSubmitResultRequest.ShopResult incoming) { + PriceTrackSubmitResultRequest.ShopResult merged = priceTrackTaskCacheService.getShopMergedPayload(taskId, shopKey); + if (merged == null) { + merged = new PriceTrackSubmitResultRequest.ShopResult(); + } + if (incoming.getShopName() != null && !incoming.getShopName().isBlank()) { + merged.setShopName(incoming.getShopName().trim()); + } else if (merged.getShopName() == null || merged.getShopName().isBlank()) { + merged.setShopName(shopKey); + } + if (incoming.getError() != null && !incoming.getError().isBlank()) { + merged.setError(incoming.getError().trim()); + } + if (incoming.getSuccess() != null) { + merged.setSuccess(incoming.getSuccess()); + } + Map> nextCountries = + merged.getCountries() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(merged.getCountries()); + if (incoming.getCountries() != null && !incoming.getCountries().isEmpty()) { + for (Map.Entry> entry : incoming.getCountries().entrySet()) { + String countryCode = entry.getKey(); + List incomingRows = entry.getValue(); + if (countryCode == null || countryCode.isBlank() || incomingRows == null || incomingRows.isEmpty()) { + continue; + } + nextCountries.put(countryCode, mergeCountryRows(nextCountries.get(countryCode), incomingRows)); + } + } + merged.setCountries(nextCountries); + priceTrackTaskCacheService.saveShopMergedPayload(taskId, shopKey, merged); + return merged; + } + private List mergeCountryRows( + List existingRows, + List incomingRows) { + LinkedHashMap byKey = new LinkedHashMap<>(); + if (existingRows != null) { + for (PriceTrackSubmitResultRequest.AsinResult row : existingRows) { + if (row != null) { + byKey.put(buildRowKey(row), cloneRow(row)); + } + } + } + for (PriceTrackSubmitResultRequest.AsinResult row : incomingRows) { + if (row == null) { + continue; + } + String key = buildRowKey(row); + byKey.put(key, mergeRow(byKey.get(key), row)); + } + return new ArrayList<>(byKey.values()); + } + private String buildRowKey(PriceTrackSubmitResultRequest.AsinResult row) { + String asin = row == null || row.getAsin() == null ? "" : row.getAsin().trim().toUpperCase(Locale.ROOT); + return asin.isBlank() ? "row:" + java.util.UUID.randomUUID() : "asin:" + asin; + } + private PriceTrackSubmitResultRequest.AsinResult mergeRow(PriceTrackSubmitResultRequest.AsinResult previous, + PriceTrackSubmitResultRequest.AsinResult incoming) { + if (previous == null) { + return cloneRow(incoming); + } + PriceTrackSubmitResultRequest.AsinResult merged = cloneRow(previous); + merged.setShopMallName(firstNonBlank(incoming.getShopMallName(), merged.getShopMallName())); + merged.setAsin(firstNonBlank(incoming.getAsin(), merged.getAsin())); + merged.setPrice(firstNonBlank(incoming.getPrice(), merged.getPrice())); + merged.setRecommendedPrice(firstNonBlank(incoming.getRecommendedPrice(), merged.getRecommendedPrice())); + merged.setMinimumPrice(firstNonBlank(incoming.getMinimumPrice(), merged.getMinimumPrice())); + merged.setFirstPlace(firstNonBlank(incoming.getFirstPlace(), merged.getFirstPlace())); + merged.setSecondPlace(firstNonBlank(incoming.getSecondPlace(), merged.getSecondPlace())); + merged.setCartShopName(firstNonBlank(incoming.getCartShopName(), merged.getCartShopName())); + merged.setPriceChangeStatus(firstNonBlank(incoming.getPriceChangeStatus(), merged.getPriceChangeStatus())); + merged.setModifyCount(firstNonBlank(incoming.getModifyCount(), merged.getModifyCount())); + merged.setStatus(firstNonBlank(incoming.getStatus(), merged.getStatus())); + return merged; + } + private PriceTrackSubmitResultRequest.AsinResult cloneRow(PriceTrackSubmitResultRequest.AsinResult row) { + PriceTrackSubmitResultRequest.AsinResult out = new PriceTrackSubmitResultRequest.AsinResult(); + if (row == null) { + return out; + } + out.setShopMallName(row.getShopMallName()); + out.setAsin(row.getAsin()); + out.setPrice(row.getPrice()); + out.setRecommendedPrice(row.getRecommendedPrice()); + out.setMinimumPrice(row.getMinimumPrice()); + out.setFirstPlace(row.getFirstPlace()); + out.setSecondPlace(row.getSecondPlace()); + out.setCartShopName(row.getCartShopName()); + out.setPriceChangeStatus(row.getPriceChangeStatus()); + out.setModifyCount(row.getModifyCount()); + out.setStatus(row.getStatus()); + return out; + } + private int countPayloadRows(PriceTrackSubmitResultRequest.ShopResult payload) { + if (payload == null) { + return 0; + } + return excelAssemblyService.countRows(excelAssemblyService.normalizeCountriesMap(payload.getCountries())); + } + private String firstNonBlank(String preferred, String fallback) { + if (preferred != null && !preferred.isBlank()) { + return preferred; + } + return fallback; + } private static String fmt(LocalDateTime t) { return t == null ? null : t.toString(); } 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 4f72fb6..c994cde 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 @@ -142,6 +142,15 @@ public class ShopManageService { return vo; } + public String findMallNameByShopName(String shopName) { + String normalizedShopName = normalizeRequired(shopName, "shopName required"); + ShopManageEntity entity = shopManageMapper.selectOne(new LambdaQueryWrapper() + .select(ShopManageEntity::getMallName) + .eq(ShopManageEntity::getShopName, normalizedShopName) + .last("limit 1")); + return entity == null ? null : entity.getMallName(); + } + private ShopManageEntity getById(Long id) { ShopManageEntity entity = shopManageMapper.selectById(id); if (entity == null) { diff --git a/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue b/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue index d1534ef..0817eee 100644 --- a/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandDeleteBrandTab.vue @@ -871,8 +871,12 @@ async function refreshTaskDetails(taskIds?: number[]) { if (changed) { syncResultState() } - } catch { - // ignore polling failures + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + if (transient && chainStarted.value) { + queuePushResult.value = '当前任务运行中,正在等待后端服务恢复...' + } } } @@ -1102,7 +1106,11 @@ async function loadHistory() { await refreshTaskDetails() ensurePolling(true) } catch (err) { - console.error('loadHistory error:', err) + const message = (err instanceof Error ? err.message : String(err || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + if (!transient) { + console.error('loadHistory error:', err) + } } } diff --git a/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue b/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue index d0bc95e..783f089 100644 --- a/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandPriceTrackTab.vue @@ -261,7 +261,7 @@ import { ElMessage } from 'element-plus' import BrandTopBar from '@/pages/brand/components/BrandTopBar.vue' import { LISTING_FILTER_OPTIONS, type ListingFilterValue } from '@/pages/brand/components/listingFilters' import { expandBrandFolderRecursive } from '@/shared/api/brand' -import { getPywebviewApi } from '@/shared/bridges/pywebview' +import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview' import { addPriceTrackCandidate, completePriceTrackLoopChild, @@ -327,6 +327,7 @@ const asinModeEnabled = ref(false) // 按指定ASIN文档(自定义) // 上传文件 const asinFiles = ref([]) // ASIN文档 +const asinUploadedFiles = ref([]) // 是否有有效模式 const hasValidMode = computed(() => statusModeEnabled.value || asinModeEnabled.value) @@ -499,6 +500,7 @@ async function selectAsinFile() { }) if (result?.paths?.length) { asinFiles.value = result.paths + asinUploadedFiles.value = await uploadAsinPathsToJava(result.paths) ElMessage.success(`已选择 ${result.paths.length} 个ASIN文件`) } return @@ -507,6 +509,7 @@ async function selectAsinFile() { const paths = await api.select_brand_xlsx_files() if (!paths?.length) return asinFiles.value = paths + asinUploadedFiles.value = await uploadAsinPathsToJava(paths) ElMessage.success(`已选择 ${paths.length} 个ASIN文件`) return } @@ -527,7 +530,8 @@ async function selectAsinFolder() { ElMessage.warning(result.error || '该文件夹下没有可用的 xlsx 文件') return } - asinFiles.value = result.items.map((item) => item.absolutePath) + asinFiles.value = result.items.map((item) => item.relativePath || item.absolutePath) + asinUploadedFiles.value = await uploadAsinPathsToJava(result.items) ElMessage.success(`已选择文件夹内 ${result.items.length} 个ASIN文件`) } catch (error) { ElMessage.error(error instanceof Error ? error.message : '选择失败') @@ -537,6 +541,31 @@ async function selectAsinFolder() { // ========== 国家顺序相关 ========== +async function uploadAsinPathsToJava(paths: Array) { + const api = getPywebviewApi() + if (!api?.upload_file_to_java) { + return [] + } + const uploaded: UploadedJavaFile[] = [] + for (const item of paths) { + const filePath = typeof item === 'string' ? item : item.absolutePath + const relativePath = typeof item === 'string' ? undefined : item.relativePath + const result = await api.upload_file_to_java(filePath, relativePath) + if (!result?.success || !result.data) { + throw new Error(result?.error || result?.message || `上传失败:${filePath}`) + } + uploaded.push(result.data) + } + return uploaded +} + +function resolveAsinRequestPaths() { + if (asinUploadedFiles.value.length) { + return asinUploadedFiles.value.map((item) => item.localPath).filter((path) => !!path) + } + return asinFiles.value +} + function selectMode(mode: 'status' | 'asin') { statusModeEnabled.value = mode === 'status' asinModeEnabled.value = mode === 'asin' @@ -744,7 +773,7 @@ async function runMatch() { matching.value = true try { const res = await matchPriceTrackShops(names, { - asinFiles: asinModeEnabled.value ? asinFiles.value : [], + asinFiles: asinModeEnabled.value ? resolveAsinRequestPaths() : [], countryCodes: [...orderedCountryCodes.value], }) const batch = res.items || [] @@ -846,7 +875,7 @@ async function pushToPythonQueueLegacy() { statusMode: statusModeEnabled.value, asinMode: asinModeEnabled.value, items: matchedRows as unknown as Record[], - asinFiles: asinFiles.value, + asinFiles: resolveAsinRequestPaths(), countryCodes: [...orderedCountryCodes.value], } const taskVo = await createPriceTrackTask(taskReq) @@ -906,6 +935,7 @@ function buildQueuePayload(taskVo: PriceTrackCreateTaskVo, row: PriceTrackShopQu task_id: taskVo.taskId, shop_name: shopName, shop_id: row.shopId ?? null, + shop_mall_name: row.shopMallName || '', country_codes: [...orderedCountryCodes.value], mode: statusModeEnabled.value ? 'status' : 'asin', skip_asins: skipAsinsByCountry, @@ -918,32 +948,51 @@ function buildQueuePayload(taskVo: PriceTrackCreateTaskVo, row: PriceTrackShopQu } async function waitForTaskTerminal(taskId: number) { + let transientErrorCount = 0 + const maxTransientErrors = 30 while (true) { - const batch = await getPriceTrackTaskProgressBatch([taskId]) - if ((batch.missingTaskIds || []).includes(taskId)) { - removePollingTask(taskId) - await loadHistory() - await loadDashboard() - syncPollingIdsWithHistory() - return 'FAILED' - } - const detail = (batch.items || []).find((item) => item.task?.id === taskId) - const status = detail?.task?.status || '' - if (detail) { - const prev = taskSnapshots.value[taskId] - taskSnapshots.value = { ...taskSnapshots.value, [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail } - saveTaskSnapshotsToStorage() - } - if (status) { - taskDetails.value = { ...taskDetails.value, [taskId]: status } - saveTaskDetailsToStorage() - } - if (status === 'SUCCESS' || status === 'FAILED') { - removePollingTask(taskId) - await loadHistory() - await loadDashboard() - syncPollingIdsWithHistory() - return status + try { + const batch = await getPriceTrackTaskProgressBatch([taskId]) + transientErrorCount = 0 + if ((batch.missingTaskIds || []).includes(taskId)) { + removePollingTask(taskId) + await loadHistory() + await loadDashboard() + syncPollingIdsWithHistory() + return 'FAILED' + } + const detail = (batch.items || []).find((item) => item.task?.id === taskId) + const status = detail?.task?.status || '' + if (detail) { + const prev = taskSnapshots.value[taskId] + taskSnapshots.value = { ...taskSnapshots.value, [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail } + saveTaskSnapshotsToStorage() + } + if (status) { + taskDetails.value = { ...taskDetails.value, [taskId]: status } + saveTaskDetailsToStorage() + } + if (status === 'SUCCESS' || status === 'FAILED') { + removePollingTask(taskId) + await loadHistory() + await loadDashboard() + syncPollingIdsWithHistory() + return status + } + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + if (!transient) throw error + transientErrorCount += 1 + if (transientErrorCount >= maxTransientErrors) { + throw new Error(`任务 ${taskId} 等待后端恢复超时,请稍后手动刷新查看状态`) + } + queuePushResult.value = `任务 ${taskId} 运行中,正在等待后端服务恢复(${transientErrorCount}/${maxTransientErrors})...` + if (transientErrorCount === 1 || transientErrorCount % 5 === 0) { + ElMessage.warning(`任务 ${taskId} 运行中,后端服务暂时不可用,正在自动重试`) + } + await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) + continue } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } @@ -973,14 +1022,28 @@ async function pushToPythonQueue() { try { for (let index = 0; index < matchedRows.length; index += 1) { const row = matchedRows[index] - const taskVo = await createPriceTrackTask({ - userId: 0, - statusMode: statusModeEnabled.value, - asinMode: asinModeEnabled.value, - items: [row] as unknown as Record[], - asinFiles: asinFiles.value, - countryCodes: [...orderedCountryCodes.value], - }) + let attempt = 0 + const taskVo = await (async () => { + while (true) { + try { + return await createPriceTrackTask({ + userId: 0, + statusMode: statusModeEnabled.value, + asinMode: asinModeEnabled.value, + items: [row] as unknown as Record[], + asinFiles: resolveAsinRequestPaths(), + countryCodes: [...orderedCountryCodes.value], + }) + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + attempt += 1 + if (!transient || attempt >= 10) throw error + queuePushResult.value = `后端服务暂时不可用,正在重试创建任务(${attempt}/10)...` + await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) + } + } + })() taskSnapshots.value = { ...taskSnapshots.value, [taskVo.taskId]: { @@ -1050,7 +1113,10 @@ async function syncActiveLoopRun() { setLoopRun(loop) clearLoopRunIfTerminal() return activeLoopRun.value - } catch { + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + if (transient) return activeLoopRun.value activeLoopRun.value = null activeLoopRunId.value = null saveActiveLoopRunId() @@ -1107,10 +1173,25 @@ async function runLoopExecution(loopId?: number) { if (!loop || loop.status === 'SUCCESS' || loop.status === 'FAILED' || loop.status === 'STOPPED') break if (loop.activeTaskId) { - addPollingTask(loop.activeTaskId) + const activeTaskId = loop.activeTaskId + addPollingTask(activeTaskId) scheduleNextPoll(true) - const finalStatus = await waitForTaskTerminal(loop.activeTaskId) - const updatedLoop = await completePriceTrackLoopChild(loop.id, loop.activeTaskId) + const finalStatus = await waitForTaskTerminal(activeTaskId) + let completeAttempt = 0 + const updatedLoop = await (async () => { + while (true) { + try { + return await completePriceTrackLoopChild(loop.id, activeTaskId) + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + completeAttempt += 1 + if (!transient || completeAttempt >= 10) throw error + queuePushResult.value = `循环任务 ${loop.id} 等待后端恢复后确认子任务完成(${completeAttempt}/10)...` + await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) + } + } + })() setLoopRun(updatedLoop) await loadHistory() await loadDashboard() @@ -1122,15 +1203,44 @@ async function runLoopExecution(loopId?: number) { continue } - const dispatch = await dispatchNextPriceTrackLoopRun(loop.id) + let dispatchAttempt = 0 + const dispatch = await (async () => { + while (true) { + try { + return await dispatchNextPriceTrackLoopRun(loop.id) + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + dispatchAttempt += 1 + if (!transient || dispatchAttempt >= 10) throw error + queuePushResult.value = `循环任务 ${loop.id} 等待后端恢复后继续派发(${dispatchAttempt}/10)...` + await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) + } + } + })() setLoopRun(dispatch.loopRun || loop) if (!dispatch.childTaskRequest) { clearLoopRunIfTerminal() break } - const row = dispatch.childTaskRequest.items?.[0] + const childTaskRequest = dispatch.childTaskRequest + const row = childTaskRequest.items?.[0] if (!row) throw new Error('循环任务缺少待执行店铺') - const taskVo = await createPriceTrackTask(dispatch.childTaskRequest) + let createAttempt = 0 + const taskVo = await (async () => { + while (true) { + try { + return await createPriceTrackTask(childTaskRequest) + } catch (error) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + const transient = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase())) + createAttempt += 1 + if (!transient || createAttempt >= 10) throw error + queuePushResult.value = `循环任务 ${loop.id} 等待后端恢复后重试创建子任务(${createAttempt}/10)...` + await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) + } + } + })() recordCreatedTask(taskVo) const queuePayload = buildQueuePayload(taskVo, row) queuePayloadText.value = JSON.stringify(queuePayload, null, 2) @@ -1185,7 +1295,7 @@ async function pushToPythonLoopQueue() { statusMode: statusModeEnabled.value, asinMode: asinModeEnabled.value, items: matchedRows, - asinFiles: asinFiles.value, + asinFiles: resolveAsinRequestPaths(), countryCodes: [...orderedCountryCodes.value], executionMode: executionMode.value, targetRounds: executionMode.value === 'FINITE' ? Math.max(1, Number(roundCount.value) || 1) : undefined, diff --git a/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue b/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue index c31bc29..5a832f6 100644 --- a/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandProductRiskTab.vue @@ -638,6 +638,44 @@ const historySectionItems = computed(() => const hasVisibleList = computed(() => currentSectionItems.value.length > 0 || historySectionItems.value.length > 0) +const TRANSIENT_BACKEND_ERROR_PATTERNS = [ + '无法连接到后端服务', + 'bad gateway', + 'gateway timeout', + 'network error', + 'timeout', + '502', + '503', + '504', +] as const + +function sleep(ms: number) { + return new Promise((resolve) => { + window.setTimeout(() => resolve(), ms) + }) +} + +function isTransientBackendError(error: unknown) { + const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase() + return TRANSIENT_BACKEND_ERROR_PATTERNS.some((pattern) => message.includes(pattern.toLowerCase())) +} + +async function createProductRiskTaskWithRetry(items: ProductRiskShopQueueItem[], maxAttempts = 10) { + let attempt = 0 + while (true) { + try { + return await createProductRiskTask(items) + } catch (error) { + attempt += 1 + if (!isTransientBackendError(error) || attempt >= maxAttempts) { + throw error + } + queuePushResult.value = `后端服务暂时不可用,正在重试创建任务(${attempt}/${maxAttempts})...` + await sleep(getPollIntervalMs()) + } + } +} + async function refreshTaskBatch() { const ids = pollingTaskIds.value.filter((id) => id > 0) if (!ids.length) return @@ -718,34 +756,50 @@ function stopPolling() { } async function waitForTaskTerminal(taskId: number) { + let transientErrorCount = 0 + const maxTransientErrors = 30 while (true) { - const batch = await getProductRiskTaskProgressBatch([taskId]) - const detail = (batch.items || []).find((d) => d.task?.id === taskId) - const status = detail?.task?.status || '' + try { + const batch = await getProductRiskTaskProgressBatch([taskId]) + transientErrorCount = 0 + const detail = (batch.items || []).find((d) => d.task?.id === taskId) + const status = detail?.task?.status || '' - if (detail) { - const prev = taskSnapshots.value[taskId] - taskSnapshots.value = { - ...taskSnapshots.value, - [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail, + if (detail) { + const prev = taskSnapshots.value[taskId] + taskSnapshots.value = { + ...taskSnapshots.value, + [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail, + } + saveTaskSnapshotsToStorage() + } + if (status) { + taskDetails.value[taskId] = status + saveTaskDetailsToStorage() } - saveTaskSnapshotsToStorage() - } - if (status) { - taskDetails.value[taskId] = status - saveTaskDetailsToStorage() - } - if (status === 'SUCCESS' || status === 'FAILED') { - removePollingTask(taskId) - await loadHistory() - await loadDashboard() - return status + if (status === 'SUCCESS' || status === 'FAILED') { + removePollingTask(taskId) + await loadHistory() + await loadDashboard() + return status + } + } catch (error) { + if (!isTransientBackendError(error)) { + throw error + } + transientErrorCount += 1 + if (transientErrorCount >= maxTransientErrors) { + throw new Error(`任务 ${taskId} 等待后端恢复超时,请稍后手动刷新查看状态`) + } + queuePushResult.value = `任务 ${taskId} 运行中,正在等待后端服务恢复(${transientErrorCount}/${maxTransientErrors})...` + if (transientErrorCount === 1 || transientErrorCount % 5 === 0) { + ElMessage.warning(`任务 ${taskId} 运行中,后端服务暂时不可用,正在自动重试`) + } + await sleep(getPollIntervalMs()) + continue } - - await new Promise((resolve) => { - window.setTimeout(() => resolve(), getPollIntervalMs()) - }) + await sleep(getPollIntervalMs()) } } @@ -943,7 +997,7 @@ async function pushToPythonQueue() { try { for (let i = 0; i < toPush.length; i++) { const item = toPush[i] - const created = await createProductRiskTask([item]) + const created = await createProductRiskTaskWithRetry([item]) const taskId = created.taskId taskSnapshots.value = { ...taskSnapshots.value, diff --git a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue index d7c0249..7a4ab49 100644 --- a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue @@ -246,7 +246,7 @@ function removeMatchedRowsLocally(rows: ShopMatchHistoryItem[] | ShopMatchShopQu function parseScheduleValues() { if (!scheduleEnabled.value) return undefined; const values = schedulePickerValues.value.map((item) => item.trim()).filter(Boolean); if (!values.length) throw new Error('请至少选择一个执行时间'); const withTime = values.map((value) => { const date = parseScheduleDateTime(value); if (!date) throw new Error(`时间格式无效: ${value}`); return { raw: formatScheduleDateTime(date), time: date.getTime() } }).sort((a, b) => a.time - b.time); for (let i = 1; i < withTime.length; i += 1) if (withTime[i].time === withTime[i - 1].time) throw new Error('执行时间不能重复'); return withTime.map((item) => item.raw) } function buildQueuePayload(taskId: number, item: Pick, countryCodes: string[], stageIndex?: number, finalStage = true) { return { type: 'shop-match-run', ts: Date.now(), data: { taskId, user_id: currentUserId(), items: [{ shopName: item.shopName, shopId: item.shopId, platform: item.platform, companyName: item.companyName, matched: true, matchStatus: item.matchStatus, matchMessage: item.matchMessage }], country_codes: [...countryCodes], risk_listing_filter: shopMatchListingFilter.value, stage_index: stageIndex, final_stage: finalStage } } } function nextScheduleStage(taskId: number) { const task = taskSnapshots.value[taskId]?.task; const stages = task?.scheduleStages || []; const currentStageIndex = task?.currentStageIndex; if (typeof currentStageIndex !== 'number') return null; const stage = stages.find((item) => item.stageIndex === currentStageIndex); if (!stage?.scheduledAt) return null; return { stageIndex: currentStageIndex, scheduledAt: stage.scheduledAt, finalStage: currentStageIndex === stages.length - 1 } } -async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await activateShopMatchTask(taskId, stage.stageIndex); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; if (snapshot?.task) taskSnapshots.value = { ...taskSnapshots.value, [taskId]: { ...snapshot, task: { ...snapshot.task, status: 'RUNNING', activeStageIndex: stage.stageIndex } } }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已推送第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) } +async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await withTransientRetry(() => activateShopMatchTask(taskId, stage.stageIndex), (attempt, maxAttempts) => { queuePushResult.value = `任务 ${taskId} 等待后端恢复后再激活执行(${attempt}/${maxAttempts})...` }); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; if (snapshot?.task) taskSnapshots.value = { ...taskSnapshots.value, [taskId]: { ...snapshot, task: { ...snapshot.task, status: 'RUNNING', activeStageIndex: stage.stageIndex } } }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已推送第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) } function hasRunningTask() { return Object.values(taskDetails.value).some((status) => status === 'RUNNING') || Object.values(taskSnapshots.value).some((detail) => detail.task?.status === 'RUNNING') } function scheduledTimestamp(value?: string) { const date = parseScheduleDateTime(value); return date ? date.getTime() : Number.NaN } function findNextReadyScheduledTask() { const taskIds = new Set(pollingTaskIds.value); for (const key of Object.keys(taskSnapshots.value)) { const id = normalizeTaskId(key); if (id > 0) taskIds.add(id) } for (const item of historyItems.value) { const id = normalizeTaskId(item.taskId); if (id > 0) taskIds.add(id) } const ready = Array.from(taskIds).map((taskId) => { const snapshot = taskSnapshots.value[taskId]; const taskStatus = taskDetails.value[taskId] || snapshot?.task?.status; const item = snapshot?.items?.[0] || historyItems.value.find((row) => normalizeTaskId(row.taskId) === taskId); const stage = nextScheduleStage(taskId); if (taskStatus !== 'SCHEDULED' || !item || !stage?.scheduledAt) return null; const scheduledTime = scheduledTimestamp(stage.scheduledAt); if (!Number.isFinite(scheduledTime) || scheduledTime > Date.now()) return null; return { taskId, item, scheduledTime } }).filter((item): item is { taskId: number; item: ShopMatchHistoryItem; scheduledTime: number } => !!item); ready.sort((a, b) => a.scheduledTime - b.scheduledTime || a.taskId - b.taskId); return ready[0] || null } @@ -256,12 +256,16 @@ function restoreScheduledDispatches() { const taskIds = new Set(pollingT function startScheduleHeartbeat() { if (scheduleHeartbeatTimer) return; scheduleHeartbeatTimer = window.setInterval(() => { void pumpScheduledQueue() }, 1000) } function stopScheduleHeartbeat() { if (!scheduleHeartbeatTimer) return; window.clearInterval(scheduleHeartbeatTimer); scheduleHeartbeatTimer = null } function handleScheduleRecovery() { restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) } +const TRANSIENT_BACKEND_ERROR_PATTERNS = ['无法连接到后端服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'] as const +function sleep(ms: number) { return new Promise((resolve) => { window.setTimeout(() => resolve(), ms) }) } +function isTransientBackendError(error: unknown) { const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase(); return TRANSIENT_BACKEND_ERROR_PATTERNS.some((pattern) => message.includes(pattern.toLowerCase())) } +async function withTransientRetry(action: () => Promise, onRetry: (attempt: number, maxAttempts: number) => void, maxAttempts = 10) { let attempt = 0; while (true) { try { return await action() } catch (error) { attempt += 1; if (!isTransientBackendError(error) || attempt >= maxAttempts) throw error; onRetry(attempt, maxAttempts); await sleep(getPollIntervalMs()) } } } async function refreshTaskBatch() { if (!pollingTaskIds.value.length) return { settledTaskIds: [] as number[] }; try { const batch = await getShopMatchTaskProgressBatch(pollingTaskIds.value); const nextSnapshots = { ...taskSnapshots.value }; const settledTaskIds = new Set(); for (const missingId of batch.missingTaskIds || []) { removeTaskLocally(missingId); delete nextSnapshots[missingId]; settledTaskIds.add(missingId) } for (const detail of batch.items || []) { const taskId = detail.task?.id; if (!taskId) continue; const prev = nextSnapshots[taskId]; nextSnapshots[taskId] = prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail; const status = detail.task?.status || ''; if (!status) continue; taskDetails.value[taskId] = status; if (isTaskTerminalStatus(status)) { removePollingTask(taskId); settledTaskIds.add(taskId); continue } if (status === 'SCHEDULED') { stopPollingTask(taskId); settledTaskIds.add(taskId) } } taskSnapshots.value = nextSnapshots; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); restoreScheduledDispatches(); return { settledTaskIds: Array.from(settledTaskIds) } } catch { return { settledTaskIds: [] as number[] } } } function getPollIntervalMs() { return document.visibilityState === 'visible' ? 6000 : 20000 } function scheduleNextPoll(immediate = false) { if (pollTimer.value) { if (!immediate) return; window.clearTimeout(pollTimer.value); pollTimer.value = null } const run = async () => { pollTimer.value = null; if (pollingInFlight.value || !pollingTaskIds.value.length) { if (pollingTaskIds.value.length) scheduleNextPoll(); return } pollingInFlight.value = true; try { const { settledTaskIds } = await refreshTaskBatch(); if (settledTaskIds.length) await Promise.allSettled([loadHistory(), loadDashboard()]) } finally { pollingInFlight.value = false } if (pollingTaskIds.value.length) pollTimer.value = window.setTimeout(run, getPollIntervalMs()) }; if (immediate) void run(); else pollTimer.value = window.setTimeout(run, getPollIntervalMs()) } function ensurePolling(immediate = false) { scheduleNextPoll(immediate) } function stopPolling() { if (pollTimer.value) { window.clearTimeout(pollTimer.value); pollTimer.value = null } } -async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTaskProgressBatch([taskId]); if ((batch.missingTaskIds || []).includes(taskId)) { removeTaskLocally(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return 'FAILED' } const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { const prev = taskSnapshots.value[taskId]; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } } +async function waitForTaskTerminal(taskId: number) { let transientErrorCount = 0; const maxTransientErrors = 30; while (true) { try { const batch = await getShopMatchTaskProgressBatch([taskId]); transientErrorCount = 0; if ((batch.missingTaskIds || []).includes(taskId)) { removeTaskLocally(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return 'FAILED' } const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { const prev = taskSnapshots.value[taskId]; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: prev ? { ...prev, task: { ...(prev.task || {}), ...(detail.task || {}) } } : detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await refreshTaskViewsBestEffort(); restoreScheduledDispatches(); return status } } catch (error) { if (!isTransientBackendError(error)) throw error; transientErrorCount += 1; if (transientErrorCount >= maxTransientErrors) throw new Error(`任务 ${taskId} 等待后端恢复超时,请稍后手动刷新查看状态`); queuePushResult.value = `任务 ${taskId} 运行中,正在等待后端服务恢复(${transientErrorCount}/${maxTransientErrors})...`; if (transientErrorCount === 1 || transientErrorCount % 5 === 0) ElMessage.warning(`任务 ${taskId} 运行中,后端服务暂时不可用,正在自动重试`); await sleep(getPollIntervalMs()); continue } await sleep(getPollIntervalMs()) } } function resolvedTaskStatus(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); if (!taskId) return item.taskStatus || ''; return taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status || item.taskStatus || '' } function taskSnapshotOf(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); return taskId ? taskSnapshots.value[taskId] : undefined } function currentTaskStageText(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (!stages.length) return ''; const total = stages.length; const activeIndex = typeof task?.activeStageIndex === 'number' ? task.activeStageIndex : undefined; const currentIndex = typeof task?.currentStageIndex === 'number' ? task.currentStageIndex : undefined; if (typeof activeIndex === 'number') return `执行进度: 第 ${activeIndex + 1}/${total} 次执行中`; if (typeof currentIndex === 'number') return `执行进度: 等待第 ${currentIndex + 1}/${total} 次`; return `执行进度: 共 ${total} 次`} @@ -298,7 +302,7 @@ async function deleteTaskRecord(item: ShopMatchHistoryItem) { } function formatMatchStatus(status?: string) { const value = (status || '').trim(); return { MATCHED: '已匹配', PENDING: '待匹配', CONFLICT: '需人工确认', INDEX_STALE: '索引过期' }[value] || value || '—' } function formatMatchRemark(row: ShopMatchShopQueueItem) { const message = (row.matchMessage || '').trim(); if (message) return message; if (row.matched && row.matchStatus === 'MATCHED') return '紫鸟索引已命中,可推送队列'; if (row.matched) return '已关联索引,请结合状态列查看是否可推送'; return '未命中或未就绪,请检查店铺名与索引刷新' } -async function pushToPythonQueue() { const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } pushing.value = true; queuePayloadText.value = ''; try { for (let index = 0; index < matched.length; index += 1) { const item = matched[index]; const created = await createShopMatchTask([item], orderedCountryCodes.value, scheduleValues); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) continue; if (scheduleValues?.length) { restoreScheduledDispatches(); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = matched.length > 1 ? `任务 ${taskId} 已入队,等待完成后继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已入队,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { throw new Error(`任务 ${taskId} 执行失败,已停止后续店铺推送`) } queuePushResult.value = index + 1 < matched.length ? `任务 ${taskId} 已完成,继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已完成` } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); ElMessage.success(scheduleValues?.length ? '定时任务已创建,后续会按时间串行推入 Python 队列' : `已按顺序完成 ${matched.length} 条店铺推送`) } catch (error) { const message = error instanceof Error ? error.message : '推送失败'; queuePushResult.value = message; ElMessage.error(message) } finally { pushing.value = false } } +async function pushToPythonQueue() { const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } pushing.value = true; queuePayloadText.value = ''; try { for (let index = 0; index < matched.length; index += 1) { const item = matched[index]; const created = await withTransientRetry(() => createShopMatchTask([item], orderedCountryCodes.value, scheduleValues), (attempt, maxAttempts) => { queuePushResult.value = `后端服务暂时不可用,正在重试创建任务(${attempt}/${maxAttempts})...` }); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) continue; if (scheduleValues?.length) { restoreScheduledDispatches(); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 推送失败`); addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = matched.length > 1 ? `任务 ${taskId} 已入队,等待完成后继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已入队,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { throw new Error(`任务 ${taskId} 执行失败,已停止后续店铺推送`) } queuePushResult.value = index + 1 < matched.length ? `任务 ${taskId} 已完成,继续推送下一条(${index + 1}/${matched.length})` : `任务 ${taskId} 已完成` } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); ElMessage.success(scheduleValues?.length ? '定时任务已创建,后续会按时间串行推入 Python 队列' : `已按顺序完成 ${matched.length} 条店铺推送`) } catch (error) { const message = error instanceof Error ? error.message : '推送失败'; queuePushResult.value = message; ElMessage.error(message) } finally { pushing.value = false } } onMounted(async () => { loadPollingIdsFromStorage(); loadTaskDetailsFromStorage(); loadTaskSnapshotsFromStorage(); loadMatchedItemsFromStorage(); syncPollingIdsWithTaskState(); await Promise.allSettled([loadCandidates(), loadCountryPreference(), loadHistory(), loadDashboard()]); startScheduleHeartbeat(); window.addEventListener('focus', handleScheduleRecovery); document.addEventListener('visibilitychange', handleScheduleRecovery); restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) }) onUnmounted(() => { stopPolling(); stopScheduleHeartbeat(); window.removeEventListener('focus', handleScheduleRecovery); document.removeEventListener('visibilitychange', handleScheduleRecovery); if (countryPrefSaveTimer) clearTimeout(countryPrefSaveTimer); for (const timer of dispatchTimers.values()) window.clearTimeout(timer); dispatchTimers.clear() }) diff --git a/frontend-vue/src/shared/api/java-modules.ts b/frontend-vue/src/shared/api/java-modules.ts index 85a2dac..9717bc8 100644 --- a/frontend-vue/src/shared/api/java-modules.ts +++ b/frontend-vue/src/shared/api/java-modules.ts @@ -925,6 +925,7 @@ export interface PriceTrackCandidateVo { export interface PriceTrackShopQueueItem { shopName?: string; + shopMallName?: string; shopId?: number | string | null; matched?: boolean; matchStatus?: string; @@ -958,6 +959,7 @@ export interface PriceTrackHistoryItem { loopRunId?: number; roundIndex?: number; shopName?: string; + shopMallName?: string; shopId?: number | string | null; platform?: string; companyName?: string;