diff --git a/app/amazon/__pycache__/approve.cpython-312.pyc b/app/amazon/__pycache__/approve.cpython-312.pyc index 99830ef..af79784 100644 Binary files a/app/amazon/__pycache__/approve.cpython-312.pyc and b/app/amazon/__pycache__/approve.cpython-312.pyc differ diff --git a/app/amazon/__pycache__/del_brand.cpython-312.pyc b/app/amazon/__pycache__/del_brand.cpython-312.pyc index b1eb189..eabb299 100644 Binary files a/app/amazon/__pycache__/del_brand.cpython-312.pyc and b/app/amazon/__pycache__/del_brand.cpython-312.pyc differ diff --git a/app/amazon/__pycache__/main.cpython-312.pyc b/app/amazon/__pycache__/main.cpython-312.pyc index 3d9cbe0..1a9e82f 100644 Binary files a/app/amazon/__pycache__/main.cpython-312.pyc and b/app/amazon/__pycache__/main.cpython-312.pyc differ diff --git a/app/amazon/__pycache__/match_action.cpython-312.pyc b/app/amazon/__pycache__/match_action.cpython-312.pyc index 4aa5da0..6555d3d 100644 Binary files a/app/amazon/__pycache__/match_action.cpython-312.pyc and b/app/amazon/__pycache__/match_action.cpython-312.pyc differ diff --git a/app/amazon/__pycache__/tool.cpython-312.pyc b/app/amazon/__pycache__/tool.cpython-312.pyc index f2537c6..eceb0cd 100644 Binary files a/app/amazon/__pycache__/tool.cpython-312.pyc and b/app/amazon/__pycache__/tool.cpython-312.pyc differ diff --git a/app/assets/delete-brand.js b/app/assets/delete-brand.js index 9097ae7..84bdd87 100644 --- a/app/assets/delete-brand.js +++ b/app/assets/delete-brand.js @@ -1 +1 @@ -import { d as We, o as Ye, I as Ze, a as d, c as f, b as es, B as ss, e as l, F as H, r as de, t as v, f as h, J as ts, K as Ae, n as De, g as y, h as J, L as ns, i as G, E as p, M as as, N as ls, O as rs, P as os, _ as us, p as is, q as cs } from "./pywebview-D808cNhy.js"; import { e as ds } from "./brand-DRn3N4FA.js"; const fs = { class: "page-shell module-page" }, vs = { class: "main-content" }, hs = { class: "left-panel" }, ps = { class: "upload-zone" }, _s = { class: "selected-files clean-placeholder split-selected-files" }, ys = { key: 0, class: "more-line" }, gs = { key: 1 }, ms = { class: "run-row" }, ks = ["disabled"], ws = ["disabled"], Is = { class: "loading-msg" }, bs = { key: 0, class: "queue-debug-card" }, Ss = { key: 0, class: "queue-debug-line" }, Ts = { key: 1, class: "queue-debug-payload" }, Cs = { class: "right-panel" }, Fs = { class: "task-list-wrap" }, Es = { class: "clean-result-summary" }, Ps = { class: "summary-card" }, Rs = { class: "summary-card" }, xs = { class: "summary-card" }, Ns = { class: "result-list-wrap" }, $s = { key: 0, class: "empty-tasks" }, As = { key: 0, class: "result-subsection" }, Ds = { class: "task-list clean-result-list" }, Ms = { class: "left split-result-main" }, Bs = ["title"], qs = { class: "files" }, Us = { class: "files" }, Ls = { key: 0, class: "files" }, Os = { key: 1, class: "files" }, Ks = { key: 2, class: "files" }, Hs = { key: 3, class: "time" }, Js = { key: 4, class: "delete-brand-progress-block" }, Gs = { class: "delete-brand-progress-header" }, js = { class: "delete-brand-progress-bar" }, zs = { class: "files delete-brand-progress" }, Vs = { key: 5, class: "files split-entry-list delete-brand-preview" }, Qs = { key: 6, class: "files" }, Xs = { class: "task-right split-result-actions" }, Ws = ["onClick"], Ys = ["onClick"], Zs = { key: 1, class: "result-subsection" }, et = { class: "task-list clean-result-list" }, st = { class: "left split-result-main" }, tt = ["title"], nt = { class: "files" }, at = { class: "files" }, lt = { key: 0, class: "files" }, rt = { key: 1, class: "files" }, ot = { key: 2, class: "time" }, ut = { key: 3, class: "delete-brand-progress-block" }, it = { class: "delete-brand-progress-header" }, ct = { class: "delete-brand-progress-bar" }, dt = { class: "files delete-brand-progress" }, ft = { key: 4, class: "files split-entry-list delete-brand-preview" }, vt = { key: 5, class: "files" }, ht = { class: "task-right split-result-actions" }, pt = ["onClick"], _t = ["onClick"], yt = We({ __name: "BrandDeleteBrandTab", setup(mt) { function N() { return `delete-brand:current-tasks:${typeof window < "u" && window.localStorage.getItem("uid") || "0"}` } const $ = y([]), j = y([]), B = y(!1), fe = y([]), i = y([]), q = y([]), z = y({ total: 0, successCount: 0, failedCount: 0, items: [] }), b = y(""), S = y(""), g = y({}), T = y(null), ee = y(!1), V = y(!1), A = y(!1), D = y(""), Q = y(!1), U = y(null), se = J(() => $.value.slice(0, 10)), F = J(() => { const e = []; return i.value.forEach(s => { e.push(...s.items) }), e }); function Me() { try { const e = typeof window < "u" ? window.localStorage.getItem(N()) : null; if (e) { if (i.value = JSON.parse(e), i.value.length > 0) { const s = i.value[i.value.length - 1]; b.value = s.queuePushResult || "", S.value = s.queuePayloadText || "" } } else i.value = [] } catch { i.value = [] } } function te(e, s, t, n) { if (!s?.length) return; const a = i.value.findIndex(c => c.taskId === e), o = a >= 0 ? i.value[a] : null, r = s.map(c => { const _ = o?.items.find(Xe => M(Xe, c)), k = Array.isArray(c.countries) ? c.countries : void 0, m = Array.isArray(_?.countries) ? _?.countries : void 0, w = k && k.length > 0 ? k : m && m.length > 0 ? m : k ?? m, I = Array.isArray(c.previewRows) ? c.previewRows : void 0, C = Array.isArray(_?.previewRows) ? _?.previewRows : void 0, ce = I && I.length > 0 ? I : C && C.length > 0 ? C : I ?? C; return { ...c, countries: w, previewRows: ce, _pushed: _?._pushed ?? c._pushed ?? !1, _completed: _?._completed ?? c._completed ?? !1 } }), u = { taskId: e, items: r, createdAt: o?.createdAt || Date.now(), queuePushResult: t ?? o?.queuePushResult, queuePayloadText: n ?? o?.queuePayloadText }; a >= 0 ? i.value[a] = u : i.value.push(u), typeof window < "u" && window.localStorage.setItem(N(), JSON.stringify(i.value)) } function ve(e) { const s = i.value.length; i.value = i.value.filter(t => t.taskId !== e), i.value.length !== s && typeof window < "u" && window.localStorage.setItem(N(), JSON.stringify(i.value)) } function he(e) { return e === "SUCCESS" || e === "FAILED" || e === "COMPLETED" } function Be(e) { if (!e?.length) return !1; const s = new Set; if (e.forEach(n => { n.taskId && he(n.taskStatus) && s.add(n.taskId) }), !s.size) return !1; const t = i.value.length; return i.value = i.value.filter(n => !s.has(n.taskId)), i.value.length !== t ? (ne(), !0) : !1 } const X = J(() => q.value.filter(e => !F.value.some(s => M(s, e)))), qe = J(() => F.value.length > 0 || X.value.length > 0), Ue = J(() => F.value.filter(e => Re(e) && E(e) === "未入队")); function ne() { typeof window < "u" && (i.value.length === 0 ? window.localStorage.removeItem(N()) : window.localStorage.setItem(N(), JSON.stringify(i.value))) } function P(e) { return e ? (i.value.find(t => t.taskId === e)?.items.length || 0) > 1 : !1 } function ae(e) { return e && i.value.find(s => s.taskId === e) || null } function M(e, s) { return !e || !s ? !1 : e.resultId != null && s.resultId != null ? e.resultId === s.resultId : e.fileKey && s.fileKey ? e.fileKey === s.fileKey : e.sourceFilename === s.sourceFilename } function R(e, s) { const t = ae(e); return t && t.items.find(n => M(n, s)) || null } function pe(e) { if (!e) return !1; const s = ae(e); if (!s) return !1; let t = !1; const n = g.value[e]?.line_progress?.info, a = P(e); if (n?.file_name && n.current_line != null && n.total_lines != null && n.total_lines > 0 && n.current_line >= n.total_lines) { const o = s.items.find(r => r.sourceFilename === n.file_name); o && !o._completed && (o._completed = !0, t = !0) } if (!a) { const o = g.value[e]?.task?.status; if ((o === "SUCCESS" || o === "FAILED") && s.items.length === 1) { const r = s.items[0]; r && !r._completed && (r._completed = !0, t = !0) } } return t && ne(), t } function _e(e) { return e && g.value[e]?.task?.status || "" } function W(e) { if (e.error) return e.error; if (e.matchStatus && e.matchStatus !== "MATCHED") return e.matchMessage || ""; const s = e.taskId; return s && g.value[s]?.task?.errorMessage || "" } function ye(e) { const s = e.taskId; if (!s) return !1; const t = g.value[s]?.line_progress, n = _e(s), a = P(s), o = E(e); if (a) { const r = R(s, e), u = K(e) === D.value, c = !!(t?.has_progress && t?.info?.file_name === e.sourceFilename); return u || c || r?._pushed || (n === "RUNNING" || n === "PENDING" || !n) && r?._completed ? !0 : { success: !1, retryable: !0 } } return o === "本文件解析完毕" || o === "已被全局判定为终态" ? !1 : t?.has_progress || t?.info ? !0 : o === "已入队" || o === "处理中" } function ge(e) { return e.map(s => s.matchStatus === "MATCHED" ? { ...s, _pushed: !1, _completed: !1 } : { ...s, matched: !1, openStoreUrl: void 0, error: s.error || void 0, _pushed: !1, _completed: !1 }) } function me(e) { return e.matchStatus === "MATCHED" ? `已匹配 ${e.shopId || ""}`.trim() : e.matchMessage ? e.matchMessage : e.matchStatus === "CONFLICT" ? "存在多个同名店铺,请人工确认" : e.matchStatus === "PENDING" || e.matchStatus === "INDEX_STALE" ? "店铺索引暂未就绪" : e.matchStatus ? e.matchStatus : e.matched ? `已匹配 ${e.shopId || ""}`.trim() : "待匹配" } function Le() { fe.value = [...F.value, ...X.value] } function x() { Le(), Oe(fe.value) } function Oe(e) { z.value = { total: e.length, successCount: e.filter(s => s.success).length, failedCount: e.filter(s => !s.success).length, items: e } } function le(e) { const s = e.taskId; return s && (g.value[s]?.fileProgress || []).find(a => a.fileKey && e.fileKey ? a.fileKey === e.fileKey : a.sourceFilename && e.sourceFilename ? a.sourceFilename === e.sourceFilename : !1) || null } function ke(e) { const s = e.taskId; if (!s) return ""; const t = g.value[s], n = t?.line_progress?.info, a = le(e); if (P(s)) { const u = R(s, e), c = t?.task?.status, _ = !!(n?.file_name && n.file_name === e.sourceFilename); let k = u?._completed ? "COMPLETED" : (u?._pushed, "PENDING"), m = 0, w = Math.max(0, e.totalRows ?? a?.totalRows ?? 0); c === "SUCCESS" || c === "FAILED" && u?._completed ? (k = "COMPLETED", m = w) : _ ? (k = "RUNNING", m = Math.max(0, Math.min(w || Number.MAX_SAFE_INTEGER, n?.current_line ?? 0)), !w && n?.total_lines && n.total_lines > 0 && (w = n.total_lines)) : u?._completed ? (k = "COMPLETED", m = w) : u?._pushed && (k = "PENDING", m = 0); const I = []; if (I.push(`文件状态:${k}`), I.push(`文件进度:${m}/${w}`), n?.finished_files != null) { const C = n.file_total && n.file_total > 0 ? `/${n.file_total}` : ""; I.push(`已完成文件:${n.finished_files}${C}`) } return n?.phase && I.push(`阶段:${n.phase}`), I.join("|") } if (a) { const u = [], c = a.processedRows ?? 0, _ = a.totalRows ?? 0; if (a.status && u.push(`文件状态:${a.status}`), u.push(`文件进度:${c}/${_}`), n?.finished_files != null) { const k = n.file_total && n.file_total > 0 ? `/${n.file_total}` : ""; u.push(`已完成文件:${n.finished_files}${k}`) } return n?.phase && u.push(`阶段:${n.phase}`), u.join("|") } if (!t?.line_progress?.has_progress || !n) { const u = t?.task?.status; return u ? `任务状态:${u}` : "" } const r = []; if (n.phase && r.push(`阶段:${n.phase}`), n.file_index && n.file_total && r.push(`文件:${n.file_index}/${n.file_total}`), n.file_name && r.push(`当前文件:${n.file_name}`), n.current_line != null && n.total_lines != null && r.push(`${P(s) ? "当前文件进度" : "进度"}:${n.current_line}/${n.total_lines}`), n.current_country && r.push(`国家:${n.current_country}`), n.current_asin && r.push(`ASIN:${n.current_asin}`), n.finished_files != null) { const u = n.file_total && n.file_total > 0 ? `/${n.file_total}` : ""; r.push(`已完成文件:${n.finished_files}${u}`) } return r.join("|") } function Y(e) { const s = e.taskId; if (!s) return 0; const t = g.value[s]?.line_progress?.info; if (P(s)) { const r = R(s, e); if (g.value[s]?.task?.status === "SUCCESS" || r?._completed) return 100; const c = Math.max(0, e.totalRows ?? le(e)?.totalRows ?? 0); if (!!(t?.file_name && t.file_name === e.sourceFilename)) { if (t?.current_line != null && t?.total_lines && t.total_lines > 0) return Math.max(0, Math.min(100, Math.round(t.current_line / t.total_lines * 100))); if (t?.current_line != null && c > 0) return Math.max(0, Math.min(100, Math.round(t.current_line / c * 100))) } return 0 } const a = le(e); return a ? Math.max(0, Math.min(100, a.percent ?? 0)) : t ? t.current_line != null && t.total_lines && t.total_lines > 0 ? Math.max(0, Math.min(100, Math.round(t.current_line / t.total_lines * 100))) : t.finished_files != null && t.file_total && t.file_total > 0 ? Math.max(0, Math.min(100, Math.round(t.finished_files / t.file_total * 100))) : g.value[s]?.task?.status === "SUCCESS" ? 100 : 0 : 0 } function we(e) { const s = g.value[e]?.task?.status; return he(s) } function L() { const e = new Set; return i.value.forEach(s => { s.items.some(t => t._pushed) && e.add(s.taskId) }), Array.from(e) } function E(e) { const s = e.taskId; if (!s || !ae(s)) return ""; const n = R(s, e), a = _e(s), o = g.value[s]?.line_progress, r = P(s); if (!r && (a === "SUCCESS" || a === "FAILED" || e.taskStatus === "SUCCESS" || e.taskStatus === "FAILED")) return "已被全局判定为终态"; if (n?._completed) return "本文件解析完毕"; if (a === "RUNNING" && o?.has_progress && o?.info?.file_name === e.sourceFilename) return "处理中"; if (r && !n?._pushed && !n?._completed) return "未入队"; if (r && a === "SUCCESS") return "本文件解析完毕"; if (!r) { const u = g.value[s]; if (u?.items && u.items.find(_ => M(_, e)) && a === "SUCCESS") return "本文件解析完毕" } return n?._pushed ? "已入队" : "未入队" } function Ie(e) { if (e.downloadUrl) return !0; const s = e.taskId; return s ? g.value[s]?.task?.status === "SUCCESS" : { success: !1, retryable: !1 } } function Ke(e) { const s = e?.task?.id; if (!s) return !1; const t = i.value.find(r => r.taskId === s); if (!t) return { success: !1, retryable: !1 }; const n = e?.items || []; let a = !1; const o = t.items.map(r => { const u = n.find(ce => M(ce, r)); if (!u) return r; const c = Array.isArray(u.countries) ? u.countries : void 0, _ = Array.isArray(r.countries) ? r.countries : void 0, k = c && c.length > 0 ? c : _ && _.length > 0 ? _ : c ?? _, m = Array.isArray(u.previewRows) ? u.previewRows : void 0, w = Array.isArray(r.previewRows) ? r.previewRows : void 0, I = m && m.length > 0 ? m : w && w.length > 0 ? w : m ?? w, C = { ...r, ...u, countries: k, previewRows: I, _pushed: r._pushed, _completed: r._completed }; return JSON.stringify(C) !== JSON.stringify(r) && (a = !0), C }); for (const r of n) o.some(u => M(u, r)) || (o.push({ ...r, _pushed: !1, _completed: !1 }), a = !0); return JSON.stringify(o) !== JSON.stringify(t.items) && (t.items = o, a = !0), a && ne(), a } async function re(e) { const s = e || L(); if (s.length) try { const t = await ns(s); let n = !1; for (const a of t.items || []) { const o = a?.task?.id; typeof o == "number" && o > 0 && (g.value[o] = a, Ke(a) && (n = !0), pe(o) && (n = !0)) } n && x() } catch { } } function He() { return document.visibilityState === "visible" ? 4500 : 1e4 } function oe(e = !1) { if (T.value) { if (!e) return; clearTimeout(T.value), T.value = null } const s = async () => { if (T.value = null, ee.value) { oe(); return } const t = L(); if (!t.length) return; ee.value = !0; let n = !1, a = !1; try { await re(t), await $e(); for (const o of t) we(o) && (ve(o), n = !0, a = !0) } finally { ee.value = !1 } a ? await O() : n && x(), L().length > 0 && oe() }; e ? s() : T.value = window.setTimeout(s, He()) } function ue(e = !1) { T.value && !e || oe(e) } function Z(e) { const s = e.taskId ? g.value[e.taskId]?.task?.status : null; return s === "SUCCESS" ? { className: "success", text: "已完成" } : s === "FAILED" ? { className: "failed", text: "失败" } : s === "RUNNING" ? { className: "running", text: "执行中" } : e.taskStatus === "SUCCESS" ? { className: "success", text: "已完成" } : e.taskStatus === "FAILED" ? { className: "failed", text: "失败" } : e.taskStatus === "RUNNING" ? { className: "running", text: "执行中" } : e.success ? { className: "success", text: "已完成" } : { className: "failed", text: "失败" } } function be() { T.value && (window.clearTimeout(T.value), T.value = null), ie() } async function Se(e) { const s = G(); if (!s?.upload_file_to_java) throw new Error("当前桌面端未提供文件上传桥接能力"); const t = []; for (const n of e) { const a = typeof n == "string" ? n : n.absolutePath, o = typeof n == "string" ? void 0 : n.relativePath, r = await s.upload_file_to_java(a, o); if (!r?.success || !r.data) throw new Error(r?.error || r?.message || `上传失败:${a}`); t.push(r.data) } return t } async function Je() { const e = G(); if (!e?.select_brand_xlsx_files) { p.warning("当前环境不支持文件选择,请在本机客户端中打开"); return } try { const s = await e.select_brand_xlsx_files(); if (!s?.length) return; $.value = s, j.value = await Se(s), p.success(`已选择 ${s.length} 个删除品牌文件`) } catch (s) { p.error(s instanceof Error ? s.message : "选择失败") } } async function Ge() { const e = G(); if (!e?.select_brand_folder) { p.warning("当前环境不支持文件夹选择,请在本机客户端中打开"); return } try { const s = await e.select_brand_folder(); if (!s) return; const t = await ds(s); if (!t.success || !t.items?.length) { p.warning(t.error || "该文件夹下没有 xlsx 文件"); return } $.value = t.items.map(n => n.relativePath || n.absolutePath), j.value = await Se(t.items), p.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`) } catch (s) { p.error(s instanceof Error ? s.message : "选择失败") } } async function je() { if (!j.value.length) { p.warning("请先选择待处理文件"); return } try { B.value = !0; const e = await as({ files: j.value.map(a => ({ fileKey: a.fileKey, originalFilename: a.originalFilename, relativePath: a.relativePath })) }), s = ge(e.items || []), t = s.some(a => a.matchStatus === "MATCHED"), n = s.some(a => a.matchStatus && a.matchStatus !== "MATCHED"); b.value = t ? "解析完成,可在左侧点击“推送到 Python 队列”开始串行处理" : "解析完成,当前没有可推送的已匹配文件", S.value = "", s.length && s[0].taskId && te(s[0].taskId, s, b.value, S.value), x(), n ? p.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。") : t ? p.success("删除品牌解析完成,请在左侧推送到 Python 队列") : p.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"), await O() } catch (e) { p.error(e instanceof Error ? e.message : "执行失败") } finally { B.value = !1 } } async function Te(e) { const s = e.taskId; if (!s) { p.warning("未找到任务ID"); return } const t = G(), n = ls(s), a = e.outputFilename || e.sourceFilename || `delete-brand_${s}.xlsx`; if (t?.save_file_from_url_new) { const o = await t.save_file_from_url_new(n, a); o.success ? p.success(`已保存:${o.path || a}`) : o.error && o.error !== "用户取消" && p.error(o.error); return } } async function O() { try { const e = await rs(); q.value = ge(e.items || []), Be(q.value), x(), await re(), ue(!0) } catch (e) { console.error("loadHistory error:", e) } } function Ce(e) { i.value.forEach(t => { t.items = t.items.filter(n => n.resultId !== e) }); const s = i.value.length; i.value = i.value.filter(t => t.items.length > 0), i.value.length !== s && typeof window < "u" && window.localStorage.setItem(N(), JSON.stringify(i.value)), q.value = q.value.filter(t => t.resultId !== e), x(), L().length === 0 && be() } async function Fe(e) { try { await os(e), Ce(e), await O(), p.success("已删除") } catch (s) { const t = s instanceof Error ? s.message : "删除失败"; if (typeof t == "string" && t.includes("记录不存在")) { Ce(e), p.success("已删除"); return } p.error(t) } } function Ee(e) { const s = e.slice(0, 5).map(n => `${n.country}:${n.asin}${n.status ? `(${n.status})` : ""}`); return e.length - s.length > 0 ? `${s.join("、")} 等 ${e.length} 条` : s.join("、") } function kt(e, s) { } function ie() { U.value && (window.clearTimeout(U.value), U.value = null) } function ze(e = 3e3) { ie(), U.value = window.setTimeout(() => { U.value = null, $e().catch(() => { }) }, e) } function Ve(e) { return e.includes("当前店铺正在执行中") } function Pe() { for (const e of i.value) for (const s of e.items) { const t = E(s); if (t === "已入队" || t === "处理中") return !0 } return !1 } function K(e) { return e.resultId != null ? `result:${e.resultId}` : `task:${e.taskId || 0}:${e.sourceFilename || ""}` } function Re(e) { return !!(e.taskId && (e.matchStatus === "MATCHED" || e.matched)) } function xe() { return F.value.find(e => !Re(e) || K(e) === D.value || R(e.taskId, e)?._completed ? !1 : E(e) === "未入队") } async function Ne(e, s) { if (s?.auto && Pe()) return e.taskId, e.sourceFilename, { success: !1, retryable: !0 }; const t = G(), n = e.taskId; if (!n) return { success: !1, retryable: !1 }; const a = i.value.find(c => c.taskId === n); if (!a) return { success: !1, retryable: !1 }; if (!t?.enqueue_json) return p.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"), { success: !1, retryable: !1 }; const o = { type: "delete-brand-run", ts: Date.now(), data: { taskId: n, items: [e] } }; S.value = JSON.stringify(o, null, 2); const r = await t.enqueue_json(o); let u = ""; if (r?.success) { u = `已推送文件 ${e.sourceFilename},当前队列长度:${r.queue_size ?? "-"}`; const c = R(n, e); return c && (c._pushed = !0, c._completed = !1), D.value = K(e), te(n, a.items, u, S.value), ue(!0), b.value = u, { success: !0, retryable: !1 } } else { const c = r?.error || "未知错误"; if (u = `推送到 Python 队列失败:${c}`, b.value = u, te(n, a.items, u, S.value), s?.auto && Ve(c)) return { success: !1, retryable: !0 } } return b.value = u, { success: !1, retryable: !1 } } async function Qe() { const e = xe(); if (!e) { p.warning("当前没有可推送的已匹配文件"); return } V.value = !0, A.value = !0, ie(); const s = await Ne(e); if (V.value = !1, !s.success) { A.value = !1, D.value = ""; return } p.success("已开始按顺序推送到 Python 队列") } async function $e() { if (!A.value || Q.value) { A.value, Q.value; return } if (Pe()) return; const e = D.value; if (e) { const t = F.value.find(n => K(n) === e); if (t) { const n = t.taskId, a = P(n); a && (pe(n), E(t), void 0); const o = E(t); if (o === "已入队" || o === "处理中") { t.sourceFilename; return } if (a) { const r = R(n, t); if (r && !r._completed) { t.sourceFilename, r._pushed, r._completed; return } } } } const s = xe(); if (!s) { D.value = "", A.value = !1; return } Q.value = !0; try { s.taskId, s.sourceFilename, K(s); const t = await Ne(s, { auto: !0 }); if (!t.success) { if (t.retryable) { s.taskId, s.sourceFilename, ze(); return } s.taskId, s.sourceFilename, A.value = !1 } } finally { Q.value = !1 } } return Ye(() => { Me(); const e = L(); e.length > 0 ? re(e).then(async () => { let s = !1, t = !1; for (const n of e) we(n) && (ve(n), s = !0, t = !0); t ? await O() : s && x(), ue(!0) }) : x(), O().catch(() => { }) }), Ze(() => { be() }), (e, s) => (d(), f("div", fs, [es(ss, { active: "delete-brand" }), l("div", vs, [l("aside", hs, [s[2] || (s[2] = l("div", { class: "section-title" }, "选择文件", -1)), l("div", ps, [s[0] || (s[0] = l("div", { class: "hint" }, "上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。", -1)), l("div", { class: "btns" }, [l("button", { type: "button", class: "opt-btn", onClick: Je }, "选择 Excel 文件"), l("button", { type: "button", class: "opt-btn", onClick: Ge }, "选择文件夹")]), l("div", _s, [$.value.length ? (d(), f(H, { key: 0 }, [(d(!0), f(H, null, de(se.value, t => (d(), f("span", { key: t }, v(t), 1))), 128)), $.value.length > se.value.length ? (d(), f("span", ys, " 还有 " + v($.value.length - se.value.length) + " 个文件未展开显示 ", 1)) : h("", !0)], 64)) : (d(), f("span", gs, "暂未选择删除品牌文件"))])]), s[3] || (s[3] = ts('
执行说明
', 2)), l("div", ms, [l("button", { type: "button", class: "btn-run", disabled: B.value, onClick: je }, v(B.value ? "解析中..." : "开始解析"), 9, ks), l("button", { type: "button", class: "btn-run btn-queue", disabled: V.value || !Ue.value.length, onClick: Qe }, v(V.value ? "推送中..." : "推送到 Python 队列"), 9, ws), l("span", Is, v(B.value ? "正在读取删除品牌数据,请稍候…" : "解析后会在右侧展示按国家分组的去重结果"), 1)]), b.value || S.value ? (d(), f("div", bs, [s[1] || (s[1] = l("div", { class: "section-title queue-debug-title" }, "Python 队列推送结果", -1)), b.value ? (d(), f("div", Ss, v(b.value), 1)) : h("", !0), S.value ? (d(), f("pre", Ts, v(S.value), 1)) : h("", !0)])) : h("", !0)]), l("section", Cs, [s[12] || (s[12] = l("div", { class: "panel-header" }, "删除品牌结果", -1)), l("div", Fs, [l("div", Es, [l("div", Ps, [s[4] || (s[4] = l("span", { class: "summary-label" }, "已处理文件", -1)), l("strong", null, v(z.value.total), 1)]), l("div", Rs, [s[5] || (s[5] = l("span", { class: "summary-label" }, "成功结果", -1)), l("strong", null, v(z.value.successCount), 1)]), l("div", xs, [s[6] || (s[6] = l("span", { class: "summary-label" }, "失败文件", -1)), l("strong", null, v(z.value.failedCount), 1)])]), l("div", Ns, [s[11] || (s[11] = l("div", { class: "result-list-header" }, [l("span", null, "删除品牌结果列表")], -1)), qe.value ? (d(), f(H, { key: 1 }, [F.value.length ? (d(), f("div", As, [s[8] || (s[8] = l("div", { class: "result-subsection-title" }, "当前任务", -1)), l("ul", Ds, [(d(!0), f(H, null, de(F.value, t => (d(), f("li", { key: `current-${t.taskId || t.resultId || t.sourceFilename}`, class: "task-item split-result-item" }, [l("div", Ms, [l("span", { class: "id", title: t.sourceFilename }, v(t.sourceFilename || "-"), 9, Bs), l("div", qs, "店铺名:" + v(t.shopName || "-"), 1), l("div", Us, "匹配结果:" + v(me(t)), 1), t.platform ? (d(), f("div", Ls, "平台:" + v(t.platform), 1)) : h("", !0), E(t) ? (d(), f("div", Os, "队列状态:" + v(E(t)), 1)) : h("", !0), t.countryCount !== void 0 && t.matched ? (d(), f("div", Ks, "国家数:" + v(t.countryCount), 1)) : h("", !0), t.totalRows !== void 0 && t.matched ? (d(), f("div", Hs, "去重后 " + v(t.totalRows) + " 条 ", 1)) : h("", !0), ye(t) ? (d(), f("div", Js, [l("div", Gs, [s[7] || (s[7] = l("span", null, "任务进度", -1)), l("span", null, v(Y(t)) + "%", 1)]), l("div", js, [l("div", { class: "delete-brand-progress-bar-fill", style: Ae({ width: `${Y(t)}%` }) }, null, 4)]), l("div", zs, v(ke(t)), 1)])) : h("", !0), t.previewRows?.length ? (d(), f("div", Vs, v(Ee(t.previewRows)), 1)) : h("", !0), W(t) ? (d(), f("div", Qs, "错误信息:" + v(W(t)), 1)) : h("", !0)]), l("div", Xs, [l("span", { class: De(["status", Z(t).className]) }, v(Z(t).text), 3), Ie(t) ? (d(), f("button", { key: 0, type: "button", class: "download", onClick: n => Te(t) }, " 下载 ", 8, Ws)) : h("", !0), t.resultId ? (d(), f("button", { key: 1, type: "button", class: "btn-delete", onClick: n => Fe(t.resultId) }, " 删除 ", 8, Ys)) : h("", !0)])]))), 128))])])) : h("", !0), X.value.length ? (d(), f("div", Zs, [s[10] || (s[10] = l("div", { class: "result-subsection-title" }, "历史记录", -1)), l("ul", et, [(d(!0), f(H, null, de(X.value, t => (d(), f("li", { key: `history-${t.taskId || t.resultId || t.sourceFilename}`, class: "task-item split-result-item" }, [l("div", st, [l("span", { class: "id", title: t.sourceFilename }, v(t.sourceFilename || "-"), 9, tt), l("div", nt, "店铺名:" + v(t.shopName || "-"), 1), l("div", at, "匹配结果:" + v(me(t)), 1), t.platform ? (d(), f("div", lt, "平台:" + v(t.platform), 1)) : h("", !0), t.countryCount !== void 0 && t.matched ? (d(), f("div", rt, "国家数:" + v(t.countryCount), 1)) : h("", !0), t.totalRows !== void 0 && t.matched ? (d(), f("div", ot, "去重后 " + v(t.totalRows) + " 条 ", 1)) : h("", !0), ye(t) ? (d(), f("div", ut, [l("div", it, [s[9] || (s[9] = l("span", null, "任务进度", -1)), l("span", null, v(Y(t)) + "%", 1)]), l("div", ct, [l("div", { class: "delete-brand-progress-bar-fill", style: Ae({ width: `${Y(t)}%` }) }, null, 4)]), l("div", dt, v(ke(t)), 1)])) : h("", !0), t.previewRows?.length ? (d(), f("div", ft, v(Ee(t.previewRows)), 1)) : h("", !0), W(t) ? (d(), f("div", vt, "错误信息:" + v(W(t)), 1)) : h("", !0)]), l("div", ht, [l("span", { class: De(["status", Z(t).className]) }, v(Z(t).text), 3), Ie(t) ? (d(), f("button", { key: 0, type: "button", class: "download", onClick: n => Te(t) }, " 下载 ", 8, pt)) : h("", !0), t.resultId ? (d(), f("button", { key: 1, type: "button", class: "btn-delete", onClick: n => Fe(t.resultId) }, " 删除 ", 8, _t)) : h("", !0)])]))), 128))])])) : h("", !0)], 64)) : (d(), f("div", $s, " 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])])) } }), gt = us(yt, [["__scopeId", "data-v-04852f65"]]); is(gt).use(cs).mount("#app"); +import{d as We,o as Ye,I as Ze,a as d,c as f,b as es,B as ss,e as l,F as H,r as de,t as v,f as h,J as ts,K as Ae,n as De,g as y,h as J,L as ns,i as G,E as p,M as as,N as ls,O as rs,P as os,_ as us,p as is,q as cs}from"./pywebview-D808cNhy.js";import{e as ds}from"./brand-DRn3N4FA.js";const fs={class:"page-shell module-page"},vs={class:"main-content"},hs={class:"left-panel"},ps={class:"upload-zone"},_s={class:"selected-files clean-placeholder split-selected-files"},ys={key:0,class:"more-line"},gs={key:1},ms={class:"run-row"},ks=["disabled"],ws=["disabled"],Is={class:"loading-msg"},bs={key:0,class:"queue-debug-card"},Ss={key:0,class:"queue-debug-line"},Ts={key:1,class:"queue-debug-payload"},Cs={class:"right-panel"},Fs={class:"task-list-wrap"},Es={class:"clean-result-summary"},Ps={class:"summary-card"},Rs={class:"summary-card"},xs={class:"summary-card"},Ns={class:"result-list-wrap"},$s={key:0,class:"empty-tasks"},As={key:0,class:"result-subsection"},Ds={class:"task-list clean-result-list"},Ms={class:"left split-result-main"},Bs=["title"],qs={class:"files"},Us={class:"files"},Ls={key:0,class:"files"},Os={key:1,class:"files"},Ks={key:2,class:"files"},Hs={key:3,class:"time"},Js={key:4,class:"delete-brand-progress-block"},Gs={class:"delete-brand-progress-header"},js={class:"delete-brand-progress-bar"},zs={class:"files delete-brand-progress"},Vs={key:5,class:"files split-entry-list delete-brand-preview"},Qs={key:6,class:"files"},Xs={class:"task-right split-result-actions"},Ws=["onClick"],Ys=["onClick"],Zs={key:1,class:"result-subsection"},et={class:"task-list clean-result-list"},st={class:"left split-result-main"},tt=["title"],nt={class:"files"},at={class:"files"},lt={key:0,class:"files"},rt={key:1,class:"files"},ot={key:2,class:"time"},ut={key:3,class:"delete-brand-progress-block"},it={class:"delete-brand-progress-header"},ct={class:"delete-brand-progress-bar"},dt={class:"files delete-brand-progress"},ft={key:4,class:"files split-entry-list delete-brand-preview"},vt={key:5,class:"files"},ht={class:"task-right split-result-actions"},pt=["onClick"],_t=["onClick"],yt=We({__name:"BrandDeleteBrandTab",setup(mt){function N(){return`delete-brand:current-tasks:${typeof window<"u"&&window.localStorage.getItem("uid")||"0"}`}const $=y([]),j=y([]),B=y(!1),fe=y([]),i=y([]),q=y([]),z=y({total:0,successCount:0,failedCount:0,items:[]}),b=y(""),S=y(""),g=y({}),T=y(null),ee=y(!1),V=y(!1),A=y(!1),D=y(""),Q=y(!1),U=y(null),se=J(()=>$.value.slice(0,10)),F=J(()=>{const e=[];return i.value.forEach(s=>{e.push(...s.items)}),e});function Me(){try{const e=typeof window<"u"?window.localStorage.getItem(N()):null;if(e){if(i.value=JSON.parse(e),i.value.length>0){const s=i.value[i.value.length-1];b.value=s.queuePushResult||"",S.value=s.queuePayloadText||""}}else i.value=[]}catch{i.value=[]}}function te(e,s,t,n){if(!s?.length)return;const a=i.value.findIndex(c=>c.taskId===e),o=a>=0?i.value[a]:null,r=s.map(c=>{const _=o?.items.find(Xe=>M(Xe,c)),k=Array.isArray(c.countries)?c.countries:void 0,m=Array.isArray(_?.countries)?_?.countries:void 0,w=k&&k.length>0?k:m&&m.length>0?m:k??m,I=Array.isArray(c.previewRows)?c.previewRows:void 0,C=Array.isArray(_?.previewRows)?_?.previewRows:void 0,ce=I&&I.length>0?I:C&&C.length>0?C:I??C;return{...c,countries:w,previewRows:ce,_pushed:_?._pushed??c._pushed??!1,_completed:_?._completed??c._completed??!1}}),u={taskId:e,items:r,createdAt:o?.createdAt||Date.now(),queuePushResult:t??o?.queuePushResult,queuePayloadText:n??o?.queuePayloadText};a>=0?i.value[a]=u:i.value.push(u),typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function ve(e){const s=i.value.length;i.value=i.value.filter(t=>t.taskId!==e),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value))}function he(e){return e==="SUCCESS"||e==="FAILED"||e==="COMPLETED"}function Be(e){if(!e?.length)return!1;const s=new Set;if(e.forEach(n=>{n.taskId&&he(n.taskStatus)&&s.add(n.taskId)}),!s.size)return!1;const t=i.value.length;return i.value=i.value.filter(n=>!s.has(n.taskId)),i.value.length!==t?(ne(),!0):!1}const X=J(()=>q.value.filter(e=>!F.value.some(s=>M(s,e)))),qe=J(()=>F.value.length>0||X.value.length>0),Ue=J(()=>F.value.filter(e=>Re(e)&&E(e)==="未入队"));function ne(){typeof window<"u"&&(i.value.length===0?window.localStorage.removeItem(N()):window.localStorage.setItem(N(),JSON.stringify(i.value)))}function P(e){return e?(i.value.find(t=>t.taskId===e)?.items.length||0)>1:!1}function ae(e){return e&&i.value.find(s=>s.taskId===e)||null}function M(e,s){return!e||!s?!1:e.resultId!=null&&s.resultId!=null?e.resultId===s.resultId:e.fileKey&&s.fileKey?e.fileKey===s.fileKey:e.sourceFilename===s.sourceFilename}function R(e,s){const t=ae(e);return t&&t.items.find(n=>M(n,s))||null}function pe(e){if(!e)return!1;const s=ae(e);if(!s)return!1;let t=!1;const n=g.value[e]?.line_progress?.info,a=P(e);if(n?.file_name&&n.current_line!=null&&n.total_lines!=null&&n.total_lines>0&&n.current_line>=n.total_lines){const o=s.items.find(r=>r.sourceFilename===n.file_name);o&&!o._completed&&(o._completed=!0,t=!0)}if(!a){const o=g.value[e]?.task?.status;if((o==="SUCCESS"||o==="FAILED")&&s.items.length===1){const r=s.items[0];r&&!r._completed&&(r._completed=!0,t=!0)}}return t&&ne(),t}function _e(e){return e&&g.value[e]?.task?.status||""}function W(e){if(e.error)return e.error;if(e.matchStatus&&e.matchStatus!=="MATCHED")return e.matchMessage||"";const s=e.taskId;return s&&g.value[s]?.task?.errorMessage||""}function ye(e){const s=e.taskId;if(!s)return!1;const t=g.value[s]?.line_progress,n=_e(s),a=P(s),o=E(e);if(a){const r=R(s,e),u=K(e)===D.value,c=!!(t?.has_progress&&t?.info?.file_name===e.sourceFilename);return u||c||r?._pushed||(n==="RUNNING"||n==="PENDING"||!n)&&r?._completed?!0:{success:!1,retryable:!0}}return o==="本文件解析完毕"||o==="已被全局判定为终态"?!1:t?.has_progress||t?.info?!0:o==="已入队"||o==="处理中"}function ge(e){return e.map(s=>s.matchStatus==="MATCHED"?{...s,_pushed:!1,_completed:!1}:{...s,matched:!1,openStoreUrl:void 0,error:s.error||void 0,_pushed:!1,_completed:!1})}function me(e){return e.matchStatus==="MATCHED"?`已匹配 ${e.shopId||""}`.trim():e.matchMessage?e.matchMessage:e.matchStatus==="CONFLICT"?"存在多个同名店铺,请人工确认":e.matchStatus==="PENDING"||e.matchStatus==="INDEX_STALE"?"店铺索引暂未就绪":e.matchStatus?e.matchStatus:e.matched?`已匹配 ${e.shopId||""}`.trim():"待匹配"}function Le(){fe.value=[...F.value,...X.value]}function x(){Le(),Oe(fe.value)}function Oe(e){z.value={total:e.length,successCount:e.filter(s=>s.success).length,failedCount:e.filter(s=>!s.success).length,items:e}}function le(e){const s=e.taskId;return s&&(g.value[s]?.fileProgress||[]).find(a=>a.fileKey&&e.fileKey?a.fileKey===e.fileKey:a.sourceFilename&&e.sourceFilename?a.sourceFilename===e.sourceFilename:!1)||null}function ke(e){const s=e.taskId;if(!s)return"";const t=g.value[s],n=t?.line_progress?.info,a=le(e);if(P(s)){const u=R(s,e),c=t?.task?.status,_=!!(n?.file_name&&n.file_name===e.sourceFilename);let k=u?._completed?"COMPLETED":(u?._pushed,"PENDING"),m=0,w=Math.max(0,e.totalRows??a?.totalRows??0);c==="SUCCESS"||c==="FAILED"&&u?._completed?(k="COMPLETED",m=w):_?(k="RUNNING",m=Math.max(0,Math.min(w||Number.MAX_SAFE_INTEGER,n?.current_line??0)),!w&&n?.total_lines&&n.total_lines>0&&(w=n.total_lines)):u?._completed?(k="COMPLETED",m=w):u?._pushed&&(k="PENDING",m=0);const I=[];if(I.push(`文件状态:${k}`),I.push(`文件进度:${m}/${w}`),n?.finished_files!=null){const C=n.file_total&&n.file_total>0?`/${n.file_total}`:"";I.push(`已完成文件:${n.finished_files}${C}`)}return n?.phase&&I.push(`阶段:${n.phase}`),I.join("|")}if(a){const u=[],c=a.processedRows??0,_=a.totalRows??0;if(a.status&&u.push(`文件状态:${a.status}`),u.push(`文件进度:${c}/${_}`),n?.finished_files!=null){const k=n.file_total&&n.file_total>0?`/${n.file_total}`:"";u.push(`已完成文件:${n.finished_files}${k}`)}return n?.phase&&u.push(`阶段:${n.phase}`),u.join("|")}if(!t?.line_progress?.has_progress||!n){const u=t?.task?.status;return u?`任务状态:${u}`:""}const r=[];if(n.phase&&r.push(`阶段:${n.phase}`),n.file_index&&n.file_total&&r.push(`文件:${n.file_index}/${n.file_total}`),n.file_name&&r.push(`当前文件:${n.file_name}`),n.current_line!=null&&n.total_lines!=null&&r.push(`${P(s)?"当前文件进度":"进度"}:${n.current_line}/${n.total_lines}`),n.current_country&&r.push(`国家:${n.current_country}`),n.current_asin&&r.push(`ASIN:${n.current_asin}`),n.finished_files!=null){const u=n.file_total&&n.file_total>0?`/${n.file_total}`:"";r.push(`已完成文件:${n.finished_files}${u}`)}return r.join("|")}function Y(e){const s=e.taskId;if(!s)return 0;const t=g.value[s]?.line_progress?.info;if(P(s)){const r=R(s,e);if(g.value[s]?.task?.status==="SUCCESS"||r?._completed)return 100;const c=Math.max(0,e.totalRows??le(e)?.totalRows??0);if(!!(t?.file_name&&t.file_name===e.sourceFilename)){if(t?.current_line!=null&&t?.total_lines&&t.total_lines>0)return Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100)));if(t?.current_line!=null&&c>0)return Math.max(0,Math.min(100,Math.round(t.current_line/c*100)))}return 0}const a=le(e);return a?Math.max(0,Math.min(100,a.percent??0)):t?t.current_line!=null&&t.total_lines&&t.total_lines>0?Math.max(0,Math.min(100,Math.round(t.current_line/t.total_lines*100))):t.finished_files!=null&&t.file_total&&t.file_total>0?Math.max(0,Math.min(100,Math.round(t.finished_files/t.file_total*100))):g.value[s]?.task?.status==="SUCCESS"?100:0:0}function we(e){const s=g.value[e]?.task?.status;return he(s)}function L(){const e=new Set;return i.value.forEach(s=>{s.items.some(t=>t._pushed)&&e.add(s.taskId)}),Array.from(e)}function E(e){const s=e.taskId;if(!s||!ae(s))return"";const n=R(s,e),a=_e(s),o=g.value[s]?.line_progress,r=P(s);if(!r&&(a==="SUCCESS"||a==="FAILED"||e.taskStatus==="SUCCESS"||e.taskStatus==="FAILED"))return"已被全局判定为终态";if(n?._completed)return"本文件解析完毕";if(a==="RUNNING"&&o?.has_progress&&o?.info?.file_name===e.sourceFilename)return"处理中";if(r&&!n?._pushed&&!n?._completed)return"未入队";if(r&&a==="SUCCESS")return"本文件解析完毕";if(!r){const u=g.value[s];if(u?.items&&u.items.find(_=>M(_,e))&&a==="SUCCESS")return"本文件解析完毕"}return n?._pushed?"已入队":"未入队"}function Ie(e){if(e.downloadUrl)return!0;const s=e.taskId;return s?g.value[s]?.task?.status==="SUCCESS":{success:!1,retryable:!1}}function Ke(e){const s=e?.task?.id;if(!s)return!1;const t=i.value.find(r=>r.taskId===s);if(!t)return{success:!1,retryable:!1};const n=e?.items||[];let a=!1;const o=t.items.map(r=>{const u=n.find(ce=>M(ce,r));if(!u)return r;const c=Array.isArray(u.countries)?u.countries:void 0,_=Array.isArray(r.countries)?r.countries:void 0,k=c&&c.length>0?c:_&&_.length>0?_:c??_,m=Array.isArray(u.previewRows)?u.previewRows:void 0,w=Array.isArray(r.previewRows)?r.previewRows:void 0,I=m&&m.length>0?m:w&&w.length>0?w:m??w,C={...r,...u,countries:k,previewRows:I,_pushed:r._pushed,_completed:r._completed};return JSON.stringify(C)!==JSON.stringify(r)&&(a=!0),C});for(const r of n)o.some(u=>M(u,r))||(o.push({...r,_pushed:!1,_completed:!1}),a=!0);return JSON.stringify(o)!==JSON.stringify(t.items)&&(t.items=o,a=!0),a&&ne(),a}async function re(e){const s=e||L();if(s.length)try{const t=await ns(s);let n=!1;for(const a of t.items||[]){const o=a?.task?.id;typeof o=="number"&&o>0&&(g.value[o]=a,Ke(a)&&(n=!0),pe(o)&&(n=!0))}n&&x()}catch{}}function He(){return document.visibilityState==="visible"?4500:1e4}function oe(e=!1){if(T.value){if(!e)return;clearTimeout(T.value),T.value=null}const s=async()=>{if(T.value=null,ee.value){oe();return}const t=L();if(!t.length)return;ee.value=!0;let n=!1,a=!1;try{await re(t),await $e();for(const o of t)we(o)&&(ve(o),n=!0,a=!0)}finally{ee.value=!1}a?await O():n&&x(),L().length>0&&oe()};e?s():T.value=window.setTimeout(s,He())}function ue(e=!1){T.value&&!e||oe(e)}function Z(e){const s=e.taskId?g.value[e.taskId]?.task?.status:null;return s==="SUCCESS"?{className:"success",text:"已完成"}:s==="FAILED"?{className:"failed",text:"失败"}:s==="RUNNING"?{className:"running",text:"执行中"}:e.taskStatus==="SUCCESS"?{className:"success",text:"已完成"}:e.taskStatus==="FAILED"?{className:"failed",text:"失败"}:e.taskStatus==="RUNNING"?{className:"running",text:"执行中"}:e.success?{className:"success",text:"已完成"}:{className:"failed",text:"失败"}}function be(){T.value&&(window.clearTimeout(T.value),T.value=null),ie()}async function Se(e){const s=G();if(!s?.upload_file_to_java)throw new Error("当前桌面端未提供文件上传桥接能力");const t=[];for(const n of e){const a=typeof n=="string"?n:n.absolutePath,o=typeof n=="string"?void 0:n.relativePath,r=await s.upload_file_to_java(a,o);if(!r?.success||!r.data)throw new Error(r?.error||r?.message||`上传失败:${a}`);t.push(r.data)}return t}async function Je(){const e=G();if(!e?.select_brand_xlsx_files){p.warning("当前环境不支持文件选择,请在本机客户端中打开");return}try{const s=await e.select_brand_xlsx_files();if(!s?.length)return;$.value=s,j.value=await Se(s),p.success(`已选择 ${s.length} 个删除品牌文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function Ge(){const e=G();if(!e?.select_brand_folder){p.warning("当前环境不支持文件夹选择,请在本机客户端中打开");return}try{const s=await e.select_brand_folder();if(!s)return;const t=await ds(s);if(!t.success||!t.items?.length){p.warning(t.error||"该文件夹下没有 xlsx 文件");return}$.value=t.items.map(n=>n.relativePath||n.absolutePath),j.value=await Se(t.items),p.success(`已选择文件夹内 ${t.items.length} 个 xlsx 文件`)}catch(s){p.error(s instanceof Error?s.message:"选择失败")}}async function je(){if(!j.value.length){p.warning("请先选择待处理文件");return}try{B.value=!0;const e=await as({files:j.value.map(a=>({fileKey:a.fileKey,originalFilename:a.originalFilename,relativePath:a.relativePath}))}),s=ge(e.items||[]),t=s.some(a=>a.matchStatus==="MATCHED"),n=s.some(a=>a.matchStatus&&a.matchStatus!=="MATCHED");b.value=t?"解析完成,可在左侧点击“推送到 Python 队列”开始串行处理":"解析完成,当前没有可推送的已匹配文件",S.value="",s.length&&s[0].taskId&&te(s[0].taskId,s,b.value,S.value),x(),n?p.warning("部分文件尚未命中可用店铺索引,已保留状态信息,请等待后台刷新后重试。"):t?p.success("删除品牌解析完成,请在左侧推送到 Python 队列"):p.warning("当前没有可推送的已匹配文件,请先等待店铺索引刷新。"),await O()}catch(e){p.error(e instanceof Error?e.message:"执行失败")}finally{B.value=!1}}async function Te(e){const s=e.taskId;if(!s){p.warning("未找到任务ID");return}const t=G(),n=ls(s),a=e.outputFilename||e.sourceFilename||`delete-brand_${s}.xlsx`;if(t?.save_file_from_url_new){const o=await t.save_file_from_url_new(n,a);o.success?p.success(`已保存:${o.path||a}`):o.error&&o.error!=="用户取消"&&p.error(o.error);return}}async function O(){try{const e=await rs();q.value=ge(e.items||[]),Be(q.value),x(),await re(),ue(!0)}catch(e){console.error("loadHistory error:",e)}}function Ce(e){i.value.forEach(t=>{t.items=t.items.filter(n=>n.resultId!==e)});const s=i.value.length;i.value=i.value.filter(t=>t.items.length>0),i.value.length!==s&&typeof window<"u"&&window.localStorage.setItem(N(),JSON.stringify(i.value)),q.value=q.value.filter(t=>t.resultId!==e),x(),L().length===0&&be()}async function Fe(e){try{await os(e),Ce(e),await O(),p.success("已删除")}catch(s){const t=s instanceof Error?s.message:"删除失败";if(typeof t=="string"&&t.includes("记录不存在")){Ce(e),p.success("已删除");return}p.error(t)}}function Ee(e){const s=e.slice(0,5).map(n=>`${n.country}:${n.asin}${n.status?`(${n.status})`:""}`);return e.length-s.length>0?`${s.join("、")} 等 ${e.length} 条`:s.join("、")}function kt(e,s){}function ie(){U.value&&(window.clearTimeout(U.value),U.value=null)}function ze(e=3e3){ie(),U.value=window.setTimeout(()=>{U.value=null,$e().catch(()=>{})},e)}function Ve(e){return e.includes("当前店铺正在执行中")}function Pe(){for(const e of i.value)for(const s of e.items){const t=E(s);if(t==="已入队"||t==="处理中")return!0}return!1}function K(e){return e.resultId!=null?`result:${e.resultId}`:`task:${e.taskId||0}:${e.sourceFilename||""}`}function Re(e){return!!(e.taskId&&(e.matchStatus==="MATCHED"||e.matched))}function xe(){return F.value.find(e=>!Re(e)||K(e)===D.value||R(e.taskId,e)?._completed?!1:E(e)==="未入队")}async function Ne(e,s){if(s?.auto&&Pe())return e.taskId,e.sourceFilename,{success:!1,retryable:!0};const t=G(),n=e.taskId;if(!n)return{success:!1,retryable:!1};const a=i.value.find(c=>c.taskId===n);if(!a)return{success:!1,retryable:!1};if(!t?.enqueue_json)return p.error("当前环境未启用 pywebview enqueue_json(浏览器环境不会推送)"),{success:!1,retryable:!1};const o={type:"delete-brand-run",ts:Date.now(),data:{taskId:n,items:[e]}};S.value=JSON.stringify(o,null,2);const r=await t.enqueue_json(o);let u="";if(r?.success){u=`已推送文件 ${e.sourceFilename},当前队列长度:${r.queue_size??"-"}`;const c=R(n,e);return c&&(c._pushed=!0,c._completed=!1),D.value=K(e),te(n,a.items,u,S.value),ue(!0),b.value=u,{success:!0,retryable:!1}}else{const c=r?.error||"未知错误";if(u=`推送到 Python 队列失败:${c}`,b.value=u,te(n,a.items,u,S.value),s?.auto&&Ve(c))return{success:!1,retryable:!0}}return b.value=u,{success:!1,retryable:!1}}async function Qe(){const e=xe();if(!e){p.warning("当前没有可推送的已匹配文件");return}V.value=!0,A.value=!0,ie();const s=await Ne(e);if(V.value=!1,!s.success){A.value=!1,D.value="";return}p.success("已开始按顺序推送到 Python 队列")}async function $e(){if(!A.value||Q.value){A.value,Q.value;return}if(Pe())return;const e=D.value;if(e){const t=F.value.find(n=>K(n)===e);if(t){const n=t.taskId,a=P(n);a&&(pe(n),E(t),void 0);const o=E(t);if(o==="已入队"||o==="处理中"){t.sourceFilename;return}if(a){const r=R(n,t);if(r&&!r._completed){t.sourceFilename,r._pushed,r._completed;return}}}}const s=xe();if(!s){D.value="",A.value=!1;return}Q.value=!0;try{s.taskId,s.sourceFilename,K(s);const t=await Ne(s,{auto:!0});if(!t.success){if(t.retryable){s.taskId,s.sourceFilename,ze();return}s.taskId,s.sourceFilename,A.value=!1}}finally{Q.value=!1}}return Ye(()=>{Me();const e=L();e.length>0?re(e).then(async()=>{let s=!1,t=!1;for(const n of e)we(n)&&(ve(n),s=!0,t=!0);t?await O():s&&x(),ue(!0)}):x(),O().catch(()=>{})}),Ze(()=>{be()}),(e,s)=>(d(),f("div",fs,[es(ss,{active:"delete-brand"}),l("div",vs,[l("aside",hs,[s[2]||(s[2]=l("div",{class:"section-title"},"选择文件",-1)),l("div",ps,[s[0]||(s[0]=l("div",{class:"hint"},"上传删除品牌 Excel;无论是直接上传文件还是上传文件夹批量导入,都会按每个 Excel 文件名作为店铺名。",-1)),l("div",{class:"btns"},[l("button",{type:"button",class:"opt-btn",onClick:Je},"选择 Excel 文件"),l("button",{type:"button",class:"opt-btn",onClick:Ge},"选择文件夹")]),l("div",_s,[$.value.length?(d(),f(H,{key:0},[(d(!0),f(H,null,de(se.value,t=>(d(),f("span",{key:t},v(t),1))),128)),$.value.length>se.value.length?(d(),f("span",ys," 还有 "+v($.value.length-se.value.length)+" 个文件未展开显示 ",1)):h("",!0)],64)):(d(),f("span",gs,"暂未选择删除品牌文件"))])]),s[3]||(s[3]=ts('
执行说明
',2)),l("div",ms,[l("button",{type:"button",class:"btn-run",disabled:B.value,onClick:je},v(B.value?"解析中...":"开始解析"),9,ks),l("button",{type:"button",class:"btn-run btn-queue",disabled:V.value||!Ue.value.length,onClick:Qe},v(V.value?"推送中...":"推送到 Python 队列"),9,ws),l("span",Is,v(B.value?"正在读取删除品牌数据,请稍候…":"解析后会在右侧展示按国家分组的去重结果"),1)]),b.value||S.value?(d(),f("div",bs,[s[1]||(s[1]=l("div",{class:"section-title queue-debug-title"},"Python 队列推送结果",-1)),b.value?(d(),f("div",Ss,v(b.value),1)):h("",!0),S.value?(d(),f("pre",Ts,v(S.value),1)):h("",!0)])):h("",!0)]),l("section",Cs,[s[12]||(s[12]=l("div",{class:"panel-header"},"删除品牌结果",-1)),l("div",Fs,[l("div",Es,[l("div",Ps,[s[4]||(s[4]=l("span",{class:"summary-label"},"已处理文件",-1)),l("strong",null,v(z.value.total),1)]),l("div",Rs,[s[5]||(s[5]=l("span",{class:"summary-label"},"成功结果",-1)),l("strong",null,v(z.value.successCount),1)]),l("div",xs,[s[6]||(s[6]=l("span",{class:"summary-label"},"失败文件",-1)),l("strong",null,v(z.value.failedCount),1)])]),l("div",Ns,[s[11]||(s[11]=l("div",{class:"result-list-header"},[l("span",null,"删除品牌结果列表")],-1)),qe.value?(d(),f(H,{key:1},[F.value.length?(d(),f("div",As,[s[8]||(s[8]=l("div",{class:"result-subsection-title"},"当前任务",-1)),l("ul",Ds,[(d(!0),f(H,null,de(F.value,t=>(d(),f("li",{key:`current-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",Ms,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,Bs),l("div",qs,"店铺名:"+v(t.shopName||"-"),1),l("div",Us,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",Ls,"平台:"+v(t.platform),1)):h("",!0),E(t)?(d(),f("div",Os,"队列状态:"+v(E(t)),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",Ks,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",Hs,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",Js,[l("div",Gs,[s[7]||(s[7]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",js,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",zs,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",Vs,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",Qs,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",Xs,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,Ws)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,Ys)):h("",!0)])]))),128))])])):h("",!0),X.value.length?(d(),f("div",Zs,[s[10]||(s[10]=l("div",{class:"result-subsection-title"},"历史记录",-1)),l("ul",et,[(d(!0),f(H,null,de(X.value,t=>(d(),f("li",{key:`history-${t.taskId||t.resultId||t.sourceFilename}`,class:"task-item split-result-item"},[l("div",st,[l("span",{class:"id",title:t.sourceFilename},v(t.sourceFilename||"-"),9,tt),l("div",nt,"店铺名:"+v(t.shopName||"-"),1),l("div",at,"匹配结果:"+v(me(t)),1),t.platform?(d(),f("div",lt,"平台:"+v(t.platform),1)):h("",!0),t.countryCount!==void 0&&t.matched?(d(),f("div",rt,"国家数:"+v(t.countryCount),1)):h("",!0),t.totalRows!==void 0&&t.matched?(d(),f("div",ot,"去重后 "+v(t.totalRows)+" 条 ",1)):h("",!0),ye(t)?(d(),f("div",ut,[l("div",it,[s[9]||(s[9]=l("span",null,"任务进度",-1)),l("span",null,v(Y(t))+"%",1)]),l("div",ct,[l("div",{class:"delete-brand-progress-bar-fill",style:Ae({width:`${Y(t)}%`})},null,4)]),l("div",dt,v(ke(t)),1)])):h("",!0),t.previewRows?.length?(d(),f("div",ft,v(Ee(t.previewRows)),1)):h("",!0),W(t)?(d(),f("div",vt,"错误信息:"+v(W(t)),1)):h("",!0)]),l("div",ht,[l("span",{class:De(["status",Z(t).className])},v(Z(t).text),3),Ie(t)?(d(),f("button",{key:0,type:"button",class:"download",onClick:n=>Te(t)}," 下载 ",8,pt)):h("",!0),t.resultId?(d(),f("button",{key:1,type:"button",class:"btn-delete",onClick:n=>Fe(t.resultId)}," 删除 ",8,_t)):h("",!0)])]))),128))])])):h("",!0)],64)):(d(),f("div",$s," 暂无删除品牌结果,完成解析后会在这里展示按国家分组的去重结果 "))])])])])]))}}),gt=us(yt,[["__scopeId","data-v-04852f65"]]);is(gt).use(cs).mount("#app"); diff --git a/app/new_web_source/delete-brand.html b/app/new_web_source/delete-brand.html index 0da4abe..e210015 100644 --- a/app/new_web_source/delete-brand.html +++ b/app/new_web_source/delete-brand.html @@ -1,19 +1,16 @@ - - - - - 删除品牌 - 数富AI - - - - - - - - -
- - - \ No newline at end of file + + + + 删除品牌 - 数富AI + + + + + + + +
+ + diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java index bf00c99..3645a2e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java @@ -6,12 +6,19 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; +import java.util.List; + @Component @RequiredArgsConstructor @Slf4j public class PermissionMenuSchemaInitializer { private final JdbcTemplate jdbcTemplate; + private static final List DEFAULT_ADMIN_MENUS = List.of( + new DefaultAdminMenu("数据去重总数据", "admin_dedupe_total_data", "dedupe-total-data"), + new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage"), + new DefaultAdminMenu("跳过跟价ASIN", "admin_skip_price_asin", "skip-price-asin") + ); @PostConstruct public void initialize() { @@ -27,6 +34,7 @@ public class PermissionMenuSchemaInitializer { executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key"); executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type"); executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''"); + ensureDefaultAdminMenus(); executeQuietly(""" INSERT INTO columns (name, column_key, menu_type, route_path) SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage' @@ -45,6 +53,18 @@ public class PermissionMenuSchemaInitializer { """); } + private void ensureDefaultAdminMenus() { + for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) { + executeQuietly(""" + INSERT INTO columns (name, column_key, menu_type, route_path) + SELECT '%s', '%s', 'admin', '%s' + WHERE NOT EXISTS ( + SELECT 1 FROM columns WHERE column_key = '%s' + ) + """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.columnKey())); + } + } + private void executeQuietly(String sql) { try { jdbcTemplate.execute(sql); @@ -52,4 +72,7 @@ public class PermissionMenuSchemaInitializer { log.debug("[permission-menu] schema init skipped: {}", ex.getMessage()); } } + + private record DefaultAdminMenu(String name, String columnKey, String routePath) { + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java new file mode 100644 index 0000000..fadfbe9 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java @@ -0,0 +1,55 @@ +package com.nanri.aiimage.modules.shopkey.controller; + +import com.nanri.aiimage.common.api.ApiResponse; +import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCreateRequest; +import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinItemVo; +import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinPageVo; +import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/admin/skip-price-asins") +@Tag(name = "跳过跟价 ASIN", description = "维护店铺按国家跳过跟价的 ASIN") +public class SkipPriceAsinController { + + private final SkipPriceAsinService skipPriceAsinService; + + @GetMapping + @Operation(summary = "分页查询跳过跟价 ASIN") + public ApiResponse page( + @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page, + @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, + @Parameter(description = "分组ID") @RequestParam(required = false) Long groupId, + @Parameter(description = "店铺名") @RequestParam(required = false) String shopName, + @Parameter(description = "ASIN") @RequestParam(required = false) String asin) { + return ApiResponse.success(skipPriceAsinService.page(page, pageSize, groupId, shopName, asin)); + } + + @PostMapping + @Operation(summary = "新增或覆盖跳过跟价 ASIN") + public ApiResponse create(@Valid @RequestBody SkipPriceAsinCreateRequest request) { + return ApiResponse.success("保存成功", skipPriceAsinService.createOrUpdate(request)); + } + + @DeleteMapping("/{id}/countries/{country}") + @Operation(summary = "删除指定国家的跳过跟价 ASIN") + public ApiResponse deleteCountry( + @Parameter(description = "主键ID", required = true) @PathVariable Long id, + @Parameter(description = "国家编码", required = true) @PathVariable String country) { + skipPriceAsinService.deleteCountry(id, country); + return ApiResponse.success("删除成功", null); + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/mapper/SkipPriceAsinMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/mapper/SkipPriceAsinMapper.java new file mode 100644 index 0000000..6274f42 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/mapper/SkipPriceAsinMapper.java @@ -0,0 +1,9 @@ +package com.nanri.aiimage.modules.shopkey.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.nanri.aiimage.modules.shopkey.model.entity.SkipPriceAsinEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SkipPriceAsinMapper extends BaseMapper { +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java new file mode 100644 index 0000000..537d03e --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java @@ -0,0 +1,24 @@ +package com.nanri.aiimage.modules.shopkey.model.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.List; + +@Data +public class SkipPriceAsinCreateRequest { + + @NotNull(message = "分组不能为空") + private Long groupId; + + @NotBlank(message = "店铺名不能为空") + private String shopName; + + @NotEmpty(message = "请至少选择一个国家") + private List countries; + + @NotBlank(message = "ASIN 不能为空") + private String asin; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/SkipPriceAsinEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/SkipPriceAsinEntity.java new file mode 100644 index 0000000..63cc68d --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/SkipPriceAsinEntity.java @@ -0,0 +1,44 @@ +package com.nanri.aiimage.modules.shopkey.model.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("biz_skip_price_asin") +public class SkipPriceAsinEntity { + + @TableId(type = IdType.AUTO) + private Long id; + + @TableField("group_id") + private Long groupId; + + @TableField("shop_name") + private String shopName; + + @TableField("asin_de") + private String asinDe; + + @TableField("asin_uk") + private String asinUk; + + @TableField("asin_fr") + private String asinFr; + + @TableField("asin_it") + private String asinIt; + + @TableField("asin_es") + private String asinEs; + + @TableField("created_at") + private LocalDateTime createdAt; + + @TableField("updated_at") + private LocalDateTime updatedAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinItemVo.java new file mode 100644 index 0000000..963db9a --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinItemVo.java @@ -0,0 +1,21 @@ +package com.nanri.aiimage.modules.shopkey.model.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class SkipPriceAsinItemVo { + + private Long id; + private Long groupId; + private String groupName; + private String shopName; + private String asinDe; + private String asinUk; + private String asinFr; + private String asinIt; + private String asinEs; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinPageVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinPageVo.java new file mode 100644 index 0000000..71de8ff --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/SkipPriceAsinPageVo.java @@ -0,0 +1,15 @@ +package com.nanri.aiimage.modules.shopkey.model.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class SkipPriceAsinPageVo { + + private List items = new ArrayList<>(); + private Long total = 0L; + private Long page = 1L; + private Long pageSize = 15L; +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java new file mode 100644 index 0000000..199c2fb --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java @@ -0,0 +1,212 @@ +package com.nanri.aiimage.modules.shopkey.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.shopkey.mapper.SkipPriceAsinMapper; +import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCreateRequest; +import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity; +import com.nanri.aiimage.modules.shopkey.model.entity.SkipPriceAsinEntity; +import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinItemVo; +import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinPageVo; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class SkipPriceAsinService { + + private static final List SUPPORTED_COUNTRIES = List.of("DE", "UK", "FR", "IT", "ES"); + + private final SkipPriceAsinMapper skipPriceAsinMapper; + private final ShopManageGroupService shopManageGroupService; + + public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin) { + long safePage = Math.max(page, 1); + long safePageSize = Math.min(Math.max(pageSize, 1), 100); + String safeShopName = normalizeBlank(shopName); + String safeAsin = normalizeBlank(asin); + + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId) + .like(!safeShopName.isEmpty(), SkipPriceAsinEntity::getShopName, safeShopName) + .and(!safeAsin.isEmpty(), wrapper -> wrapper + .like(SkipPriceAsinEntity::getAsinDe, safeAsin) + .or().like(SkipPriceAsinEntity::getAsinUk, safeAsin) + .or().like(SkipPriceAsinEntity::getAsinFr, safeAsin) + .or().like(SkipPriceAsinEntity::getAsinIt, safeAsin) + .or().like(SkipPriceAsinEntity::getAsinEs, safeAsin)) + .orderByDesc(SkipPriceAsinEntity::getId); + + Long total = skipPriceAsinMapper.selectCount(query); + List rows = skipPriceAsinMapper + .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); + + Map groupNameById = buildGroupNameMap(rows.stream() + .map(SkipPriceAsinEntity::getGroupId) + .filter(id -> id != null && id > 0) + .distinct() + .toList()); + + SkipPriceAsinPageVo vo = new SkipPriceAsinPageVo(); + vo.setItems(rows.stream().map(row -> toItemVo(row, groupNameById.get(row.getGroupId()))).toList()); + vo.setTotal(total); + vo.setPage(safePage); + vo.setPageSize(safePageSize); + return vo; + } + + @Transactional + public SkipPriceAsinItemVo createOrUpdate(SkipPriceAsinCreateRequest request) { + ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId()); + String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空"); + String asin = normalizeAsin(request.getAsin()); + Set countries = normalizeCountries(request.getCountries()); + + SkipPriceAsinEntity entity = skipPriceAsinMapper.selectOne(new LambdaQueryWrapper() + .eq(SkipPriceAsinEntity::getGroupId, group.getId()) + .eq(SkipPriceAsinEntity::getShopName, shopName) + .last("LIMIT 1")); + if (entity == null) { + entity = new SkipPriceAsinEntity(); + entity.setGroupId(group.getId()); + entity.setShopName(shopName); + } + + for (String country : countries) { + setCountryAsin(entity, country, asin); + } + + if (entity.getId() == null) { + skipPriceAsinMapper.insert(entity); + } else { + skipPriceAsinMapper.updateById(entity); + } + SkipPriceAsinEntity saved = getById(entity.getId()); + return toItemVo(saved, group.getGroupName()); + } + + @Transactional + public void deleteCountry(Long id, String country) { + SkipPriceAsinEntity entity = getById(id); + String normalizedCountry = normalizeCountry(country); + setCountryAsin(entity, normalizedCountry, ""); + if (isEmptyRow(entity)) { + skipPriceAsinMapper.deleteById(entity.getId()); + return; + } + skipPriceAsinMapper.updateById(entity); + } + + private SkipPriceAsinEntity getById(Long id) { + SkipPriceAsinEntity entity = skipPriceAsinMapper.selectById(id); + if (entity == null) { + throw new BusinessException("记录不存在"); + } + return entity; + } + + private SkipPriceAsinItemVo toItemVo(SkipPriceAsinEntity entity, String groupName) { + SkipPriceAsinItemVo vo = new SkipPriceAsinItemVo(); + vo.setId(entity.getId()); + vo.setGroupId(entity.getGroupId()); + vo.setGroupName(groupName == null ? "" : groupName); + vo.setShopName(entity.getShopName()); + vo.setAsinDe(blankToEmpty(entity.getAsinDe())); + vo.setAsinUk(blankToEmpty(entity.getAsinUk())); + vo.setAsinFr(blankToEmpty(entity.getAsinFr())); + vo.setAsinIt(blankToEmpty(entity.getAsinIt())); + vo.setAsinEs(blankToEmpty(entity.getAsinEs())); + vo.setCreatedAt(entity.getCreatedAt()); + vo.setUpdatedAt(entity.getUpdatedAt()); + return vo; + } + + private Map buildGroupNameMap(List groupIds) { + if (groupIds == null || groupIds.isEmpty()) { + return Map.of(); + } + LinkedHashMap map = new LinkedHashMap<>(); + for (Long groupId : groupIds) { + try { + ShopManageGroupEntity group = shopManageGroupService.getById(groupId); + map.put(groupId, group.getGroupName()); + } catch (Exception ignored) { + map.put(groupId, ""); + } + } + return map; + } + + private Set normalizeCountries(List countries) { + LinkedHashSet normalized = new LinkedHashSet<>(); + if (countries != null) { + for (String country : countries) { + normalized.add(normalizeCountry(country)); + } + } + if (normalized.isEmpty()) { + throw new BusinessException("请至少选择一个国家"); + } + return normalized; + } + + private String normalizeCountry(String country) { + String normalized = normalizeBlank(country).toUpperCase(Locale.ROOT); + if (!SUPPORTED_COUNTRIES.contains(normalized)) { + throw new BusinessException("国家参数不支持: " + country); + } + return normalized; + } + + private String normalizeAsin(String asin) { + String normalized = normalizeRequired(asin, "ASIN 不能为空").toUpperCase(Locale.ROOT); + if (normalized.length() > 64) { + throw new BusinessException("ASIN 长度不能超过 64"); + } + return normalized; + } + + private String normalizeRequired(String value, String message) { + String normalized = normalizeBlank(value); + if (normalized.isEmpty()) { + throw new BusinessException(message); + } + return normalized; + } + + private String normalizeBlank(String value) { + return value == null ? "" : value.trim(); + } + + private String blankToEmpty(String value) { + return value == null ? "" : value; + } + + private void setCountryAsin(SkipPriceAsinEntity entity, String country, String asin) { + String value = normalizeBlank(asin); + switch (country) { + case "DE" -> entity.setAsinDe(value); + case "UK" -> entity.setAsinUk(value); + case "FR" -> entity.setAsinFr(value); + case "IT" -> entity.setAsinIt(value); + case "ES" -> entity.setAsinEs(value); + default -> throw new BusinessException("国家参数不支持: " + country); + } + } + + private boolean isEmptyRow(SkipPriceAsinEntity entity) { + return normalizeBlank(entity.getAsinDe()).isEmpty() + && normalizeBlank(entity.getAsinUk()).isEmpty() + && normalizeBlank(entity.getAsinFr()).isEmpty() + && normalizeBlank(entity.getAsinIt()).isEmpty() + && normalizeBlank(entity.getAsinEs()).isEmpty(); + } +} diff --git a/backend-java/src/main/resources/db/V21__skip_price_asin_and_admin_menu_defaults.sql b/backend-java/src/main/resources/db/V21__skip_price_asin_and_admin_menu_defaults.sql new file mode 100644 index 0000000..4b224e7 --- /dev/null +++ b/backend-java/src/main/resources/db/V21__skip_price_asin_and_admin_menu_defaults.sql @@ -0,0 +1,33 @@ +CREATE TABLE IF NOT EXISTS biz_skip_price_asin ( + id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键', + group_id BIGINT NOT NULL COMMENT '分组ID', + shop_name VARCHAR(128) NOT NULL COMMENT '店铺名', + asin_de VARCHAR(64) NOT NULL DEFAULT '' COMMENT '德国 ASIN', + asin_uk VARCHAR(64) NOT NULL DEFAULT '' COMMENT '英国 ASIN', + asin_fr VARCHAR(64) NOT NULL DEFAULT '' COMMENT '法国 ASIN', + asin_it VARCHAR(64) NOT NULL DEFAULT '' COMMENT '意大利 ASIN', + asin_es VARCHAR(64) NOT NULL DEFAULT '' COMMENT '西班牙 ASIN', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + UNIQUE KEY uk_group_shop_name (group_id, shop_name), + KEY idx_shop_name (shop_name), + KEY idx_created_at (created_at) +) COMMENT='跳过跟价 ASIN'; + +INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`) +SELECT '数据去重总数据', 'admin_dedupe_total_data', 'admin', 'dedupe-total-data' +WHERE NOT EXISTS ( + SELECT 1 FROM `columns` WHERE `column_key` = 'admin_dedupe_total_data' +); + +INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`) +SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage' +WHERE NOT EXISTS ( + SELECT 1 FROM `columns` WHERE `column_key` = 'admin_shop_manage' +); + +INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`) +SELECT '跳过跟价ASIN', 'admin_skip_price_asin', 'admin', 'skip-price-asin' +WHERE NOT EXISTS ( + SELECT 1 FROM `columns` WHERE `column_key` = 'admin_skip_price_asin' +); diff --git a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc index df04bc0..df68f2e 100644 Binary files a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc and b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc differ diff --git a/backend/blueprints/admin_api.py b/backend/blueprints/admin_api.py index 00694bb..2988c8e 100644 --- a/backend/blueprints/admin_api.py +++ b/backend/blueprints/admin_api.py @@ -19,6 +19,8 @@ ALLOWED_DEDUPE_TOTAL_DATA_ADMIN_USERNAMES = {'刘丽泓'} def _can_access_dedupe_total_data(role, current_row): + _, _, denied = _ensure_admin_menu_access('dedupe-total-data') + return denied is None if role == 'super_admin': return True if role != 'admin' or not current_row: @@ -27,6 +29,7 @@ def _can_access_dedupe_total_data(role, current_row): def _ensure_dedupe_total_data_access(): + return _ensure_admin_menu_access('dedupe-total-data') role, current_row = get_current_admin_role() if not _can_access_dedupe_total_data(role, current_row): return None, None, (jsonify({'success': False, 'error': '无权限访问数据去重总数据'}), 403) @@ -41,6 +44,24 @@ except ImportError: admin_api = Blueprint('admin_api', __name__, url_prefix='/api/admin') +ADMIN_MENU_ACCESS_CONFIG = { + 'dedupe-total-data': { + 'column_key': 'admin_dedupe_total_data', + 'route_path': 'dedupe-total-data', + 'error': '鏃犳潈闄愯闂暟鎹幓閲嶆€绘暟鎹?', + }, + 'shop-manage': { + 'column_key': 'admin_shop_manage', + 'route_path': 'shop-manage', + 'error': '鏃犳潈闄愯闂簵閾虹鐞嗘ā鍧?', + }, + 'skip-price-asin': { + 'column_key': 'admin_skip_price_asin', + 'route_path': 'skip-price-asin', + 'error': '鏃犳潈闄愯闂烦杩囪窡浠稟SIN 妯″潡', + }, +} + def _safe_version_key(version): """将版本号转为安全的 OSS 对象名部分""" @@ -90,6 +111,47 @@ def _sync_user_column_permissions(user_id, column_ids): return error_response, status +def _get_current_admin_permission_sets(): + user_id = session.get('user_id') + if not user_id: + return set(), set() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute( + """SELECT c.column_key, c.route_path + FROM user_column_permission ucp + INNER JOIN columns c ON c.id = ucp.column_id + WHERE ucp.user_id = %s AND c.menu_type = 'admin'""", + (user_id,), + ) + rows = cur.fetchall() + finally: + conn.close() + key_set = {(row.get('column_key') or '').strip() for row in rows if (row.get('column_key') or '').strip()} + route_set = {(row.get('route_path') or '').strip() for row in rows if (row.get('route_path') or '').strip()} + return key_set, route_set + + +def _ensure_admin_menu_access(*menu_names): + role, current_row = get_current_admin_role() + if role == 'super_admin': + return role, current_row, None + if role != 'admin' or not current_row: + return role, current_row, (jsonify({'success': False, 'error': '闇€瑕佺鐞嗗憳鏉冮檺'}), 403) + key_set, route_set = _get_current_admin_permission_sets() + for menu_name in menu_names: + config = ADMIN_MENU_ACCESS_CONFIG.get(menu_name) or {} + column_key = (config.get('column_key') or '').strip() + route_path = (config.get('route_path') or '').strip() + if (column_key and column_key in key_set) or (route_path and route_path in route_set): + return role, current_row, None + fallback_menu = menu_names[0] if menu_names else '' + fallback_config = ADMIN_MENU_ACCESS_CONFIG.get(fallback_menu) or {} + error_message = fallback_config.get('error') or '鏃犳潈闄愯闂綋鍓嶆ā鍧?' + return role, current_row, (jsonify({'success': False, 'error': error_message}), 403) + + # ---------- 用户管理 ---------- @admin_api.route('/users') @@ -936,6 +998,9 @@ def delete_dedupe_total_data(item_id): @admin_api.route('/shop-manages') @admin_required def list_shop_manages(): + _, _, denied = _ensure_admin_menu_access('shop-manage') + if denied: + return denied page = max(1, int(request.args.get('page', 1))) page_size = min(100, max(1, int(request.args.get('page_size', 15)))) group_id_raw = (request.args.get('group_id') or '').strip() @@ -986,6 +1051,9 @@ def list_shop_manages(): @admin_api.route('/shop-manage', methods=['POST']) @admin_required def create_shop_manage(): + _, _, denied = _ensure_admin_menu_access('shop-manage') + if denied: + return denied data = request.get_json() or {} payload = { 'groupId': data.get('group_id'), @@ -1022,6 +1090,9 @@ def create_shop_manage(): @admin_api.route('/shop-manage/', methods=['PUT']) @admin_required def update_shop_manage(item_id): + _, _, denied = _ensure_admin_menu_access('shop-manage') + if denied: + return denied data = request.get_json() or {} payload = { 'groupId': data.get('group_id'), @@ -1057,6 +1128,9 @@ def update_shop_manage(item_id): @admin_api.route('/shop-manage/', methods=['DELETE']) @admin_required def delete_shop_manage(item_id): + _, _, denied = _ensure_admin_menu_access('shop-manage') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-manages/{item_id}', @@ -1072,6 +1146,9 @@ def delete_shop_manage(item_id): @admin_api.route('/shop-manage-groups') @admin_required def list_shop_manage_groups(): + _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'GET', '/api/admin/shop-manages/groups', @@ -1093,6 +1170,9 @@ def list_shop_manage_groups(): @admin_api.route('/shop-manage-group', methods=['POST']) @admin_required def create_shop_manage_group(): + _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + if denied: + return denied data = request.get_json() or {} payload = {'groupName': (data.get('group_name') or '').strip()} result, error_response, status = _proxy_backend_java( @@ -1118,6 +1198,9 @@ def create_shop_manage_group(): @admin_api.route('/shop-manage-group/', methods=['PUT']) @admin_required def update_shop_manage_group(item_id): + _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + if denied: + return denied data = request.get_json() or {} payload = {'groupName': (data.get('group_name') or '').strip()} result, error_response, status = _proxy_backend_java( @@ -1140,9 +1223,123 @@ def update_shop_manage_group(item_id): }) +@admin_api.route('/skip-price-asins') +@admin_required +def list_skip_price_asins(): + _, _, denied = _ensure_admin_menu_access('skip-price-asin') + if denied: + return denied + page = max(1, int(request.args.get('page', 1))) + page_size = min(100, max(1, int(request.args.get('page_size', 15)))) + group_id_raw = (request.args.get('group_id') or '').strip() + shop_name = (request.args.get('shop_name') or '').strip() + asin = (request.args.get('asin') or '').strip() + params = {'page': page, 'pageSize': page_size} + if group_id_raw: + try: + group_id = int(group_id_raw) + if group_id > 0: + params['groupId'] = group_id + except (TypeError, ValueError): + pass + if shop_name: + params['shopName'] = shop_name + if asin: + params['asin'] = asin + result, error_response, status = _proxy_backend_java( + 'GET', + '/api/admin/skip-price-asins', + params=params, + ) + if error_response is not None: + return error_response, status + payload = result.get('data') or {} + items = [ + { + 'id': item.get('id'), + 'group_id': item.get('groupId'), + 'group_name': item.get('groupName') or '', + 'shop_name': item.get('shopName') or '', + 'asin_de': item.get('asinDe') or '', + 'asin_uk': item.get('asinUk') or '', + 'asin_fr': item.get('asinFr') or '', + 'asin_it': item.get('asinIt') or '', + 'asin_es': item.get('asinEs') or '', + 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], + 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], + } + for item in (payload.get('items') or []) + ] + return jsonify({ + 'success': True, + 'items': items, + 'total': payload.get('total') or 0, + 'page': payload.get('page') or page, + 'page_size': payload.get('pageSize') or page_size, + }) + + +@admin_api.route('/skip-price-asin', methods=['POST']) +@admin_required +def create_skip_price_asin(): + _, _, denied = _ensure_admin_menu_access('skip-price-asin') + if denied: + return denied + data = request.get_json() or {} + payload = { + 'groupId': data.get('group_id'), + 'shopName': (data.get('shop_name') or '').strip(), + 'countries': data.get('countries') or [], + 'asin': (data.get('asin') or '').strip(), + } + result, error_response, status = _proxy_backend_java( + 'POST', + '/api/admin/skip-price-asins', + json_data=payload, + ) + if error_response is not None: + return error_response, status + item = result.get('data') or {} + return jsonify({ + 'success': True, + 'msg': result.get('message') or '淇濆瓨鎴愬姛', + 'item': { + 'id': item.get('id'), + 'group_id': item.get('groupId'), + 'group_name': item.get('groupName') or '', + 'shop_name': item.get('shopName') or '', + 'asin_de': item.get('asinDe') or '', + 'asin_uk': item.get('asinUk') or '', + 'asin_fr': item.get('asinFr') or '', + 'asin_it': item.get('asinIt') or '', + 'asin_es': item.get('asinEs') or '', + 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], + 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], + }, + }) + + +@admin_api.route('/skip-price-asin//country/', methods=['DELETE']) +@admin_required +def delete_skip_price_asin_country(item_id, country): + _, _, denied = _ensure_admin_menu_access('skip-price-asin') + if denied: + return denied + result, error_response, status = _proxy_backend_java( + 'DELETE', + f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + ) + if error_response is not None: + return error_response, status + return jsonify({'success': True, 'msg': result.get('message') or '鍒犻櫎鎴愬姛'}) + + @admin_api.route('/shop-manage-group/', methods=['DELETE']) @admin_required def delete_shop_manage_group(item_id): + _, _, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-manages/groups/{item_id}', diff --git a/backend/web_source/admin.html b/backend/web_source/admin.html index 3092098..d450729 100644 --- a/backend/web_source/admin.html +++ b/backend/web_source/admin.html @@ -114,6 +114,7 @@
数据去重总数据
店铺密钥管理
店铺管理
+
跳过跟价 ASIN
查看生成记录
版本管理
@@ -421,6 +422,79 @@ +
+
+

新增 ASIN

+
+
+ +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+ +
+

+
+
+

店铺列表

+
+
+ + +
+
+ + +
+
+ + +
+ +
+ + + + + + + + + + + + + + +
序号分组店铺名德国英国法国意大利西班牙
+ +
+
+

筛选条件

@@ -627,6 +701,23 @@ diff --git a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue index 691d605..9df24a1 100644 --- a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue @@ -181,10 +181,27 @@ function loadTaskSnapshotsFromStorage() { try { const raw = window.localStorage. function saveTaskSnapshotsToStorage() { setStorageJson(taskSnapshotsStorageKey(), taskSnapshots.value, Object.keys(taskSnapshots.value).length === 0) } function loadMatchedItemsFromStorage() { try { const raw = window.localStorage.getItem(matchedItemsStorageKey()); matchedItems.value = raw ? JSON.parse(raw) : [] } catch { matchedItems.value = [] } } function saveMatchedItemsToStorage() { setStorageJson(matchedItemsStorageKey(), matchedItems.value, matchedItems.value.length === 0) } +function isTaskMissingError(error: unknown) { const message = error instanceof Error ? error.message : String(error || ''); return message.includes('任务不存在') } function syncPollingIdsWithTaskState() { const nextIds = pollingTaskIds.value.filter((taskId) => (taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status) === 'RUNNING'); if (nextIds.length === pollingTaskIds.value.length) return; pollingTaskIds.value = nextIds; savePollingIds() } function addPollingTask(taskId: number) { if (!pollingTaskIds.value.includes(taskId)) { pollingTaskIds.value = [...pollingTaskIds.value, taskId]; savePollingIds() } } function clearDispatchTimer(taskId: number) { const timer = dispatchTimers.get(taskId); if (timer) { window.clearTimeout(timer); dispatchTimers.delete(taskId) } } -function removePollingTask(taskId: number) { clearDispatchTimer(taskId); pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId); delete taskDetails.value[taskId]; savePollingIds(); saveTaskDetailsToStorage() } +function removePollingTask(taskId: number) { + clearDispatchTimer(taskId) + pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId) + delete taskDetails.value[taskId] + if (taskSnapshots.value[taskId]) { + const nextSnapshots = { ...taskSnapshots.value } + delete nextSnapshots[taskId] + taskSnapshots.value = nextSnapshots + saveTaskSnapshotsToStorage() + } + savePollingIds() + saveTaskDetailsToStorage() +} +function removeTaskLocally(taskId: number) { + removePollingTask(taskId) + historyItems.value = historyItems.value.filter((row) => normalizeTaskId(row.taskId) !== taskId) +} function stopPollingTask(taskId: number, keepStatus = true) { pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId); if (!keepStatus) delete taskDetails.value[taskId]; savePollingIds(); saveTaskDetailsToStorage() } function isTaskTerminalStatus(status?: string) { return status === 'SUCCESS' || status === 'FAILED' || status === 'COMPLETED' } function isTaskTerminalById(taskId?: number) { if (!taskId) return false; const status = taskDetails.value[taskId] || taskSnapshots.value[taskId]?.task?.status; return isTaskTerminalStatus(status) } @@ -230,12 +247,12 @@ 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) } -async function refreshTaskBatch() { if (!pollingTaskIds.value.length) return { settledTaskIds: [] as number[] }; try { const batch = await getShopMatchTasksBatch(pollingTaskIds.value); const nextSnapshots = { ...taskSnapshots.value }; const settledTaskIds = new Set(); for (const missingId of batch.missingTaskIds || []) { removePollingTask(missingId); delete nextSnapshots[missingId] } for (const detail of batch.items || []) { const taskId = detail.task?.id; if (!taskId) continue; nextSnapshots[taskId] = detail; const status = detail.task?.status || ''; if (!status) continue; taskDetails.value[taskId] = status; if (isTaskTerminalStatus(status)) { removePollingTask(taskId); settledTaskIds.add(taskId); continue } if (status === 'SCHEDULED') { stopPollingTask(taskId); settledTaskIds.add(taskId) } } taskSnapshots.value = nextSnapshots; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); restoreScheduledDispatches(); return { settledTaskIds: Array.from(settledTaskIds) } } catch { return { settledTaskIds: [] as number[] } } } +async function refreshTaskBatch() { if (!pollingTaskIds.value.length) return { settledTaskIds: [] as number[] }; try { const batch = await getShopMatchTasksBatch(pollingTaskIds.value); const nextSnapshots = { ...taskSnapshots.value }; const settledTaskIds = new Set(); for (const missingId of batch.missingTaskIds || []) { removeTaskLocally(missingId); delete nextSnapshots[missingId]; settledTaskIds.add(missingId) } for (const detail of batch.items || []) { const taskId = detail.task?.id; if (!taskId) continue; nextSnapshots[taskId] = detail; const status = detail.task?.status || ''; if (!status) continue; taskDetails.value[taskId] = status; if (isTaskTerminalStatus(status)) { removePollingTask(taskId); settledTaskIds.add(taskId); continue } if (status === 'SCHEDULED') { stopPollingTask(taskId); settledTaskIds.add(taskId) } } taskSnapshots.value = nextSnapshots; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); restoreScheduledDispatches(); return { settledTaskIds: Array.from(settledTaskIds) } } catch { return { settledTaskIds: [] as number[] } } } function getPollIntervalMs() { return document.visibilityState === 'visible' ? 4000 : 10000 } function scheduleNextPoll(immediate = false) { if (pollTimer.value) { if (!immediate) return; window.clearTimeout(pollTimer.value); pollTimer.value = null } const run = async () => { pollTimer.value = null; if (pollingInFlight.value || !pollingTaskIds.value.length) { if (pollingTaskIds.value.length) scheduleNextPoll(); return } pollingInFlight.value = true; try { const { settledTaskIds } = await refreshTaskBatch(); if (settledTaskIds.length) await Promise.allSettled([loadHistory(), loadDashboard()]) } finally { pollingInFlight.value = false } if (pollingTaskIds.value.length) pollTimer.value = window.setTimeout(run, getPollIntervalMs()) }; if (immediate) void run(); else pollTimer.value = window.setTimeout(run, getPollIntervalMs()) } function ensurePolling(immediate = false) { scheduleNextPoll(immediate) } function stopPolling() { if (pollTimer.value) { window.clearTimeout(pollTimer.value); pollTimer.value = null } } -async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } } +async function waitForTaskTerminal(taskId: number) { while (true) { const batch = await getShopMatchTasksBatch([taskId]); if ((batch.missingTaskIds || []).includes(taskId)) { removeTaskLocally(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return 'FAILED' } const detail = (batch.items || []).find((item) => item.task?.id === taskId); const status = detail?.task?.status || ''; if (detail) { taskSnapshots.value = { ...taskSnapshots.value, [taskId]: detail }; saveTaskSnapshotsToStorage() } if (status) { taskDetails.value[taskId] = status; saveTaskDetailsToStorage() } if (isTaskTerminalStatus(status)) { removePollingTask(taskId); await loadHistory(); await loadDashboard(); restoreScheduledDispatches(); return status } await new Promise((resolve) => { window.setTimeout(() => resolve(), getPollIntervalMs()) }) } } 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} 次`} @@ -250,10 +267,7 @@ async function deleteTaskRecord(item: ShopMatchHistoryItem) { try { if (taskId > 0) { await deleteShopMatchTask(taskId) - removePollingTask(taskId) - historyItems.value = historyItems.value.filter((row) => normalizeTaskId(row.taskId) !== taskId) - delete taskSnapshots.value[taskId] - saveTaskSnapshotsToStorage() + removeTaskLocally(taskId) } else if (resultId > 0) { await deleteShopMatchHistory(resultId) historyItems.value = historyItems.value.filter((row) => Number(row.resultId || 0) !== resultId) @@ -262,7 +276,14 @@ async function deleteTaskRecord(item: ShopMatchHistoryItem) { throw new Error('缺少可删除的任务标识') } await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()]) + ElMessage.success('删除成功') } catch (error) { + if (taskId > 0 && isTaskMissingError(error)) { + removeTaskLocally(taskId) + await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()]) + ElMessage.success('任务已在服务端删除,本地记录已同步清理') + return + } ElMessage.error(error instanceof Error ? error.message : '删除失败') } }