revert(common-tools): 回滚常用工具分类与三个工具页

按 2026-10-24 决定整体下线:工具目录分组、定价换算/五国ASIN/关键词共享
三页面与路由、资料下载区与测试全部移除;保留 package.json 的 test:mount
脚本(仓内测试基础设施,与后管同口径)。
This commit is contained in:
2026-10-24 01:43:45 +08:00
parent 314c283503
commit 634fefbc2f
29 changed files with 16 additions and 3234 deletions
@@ -1,38 +0,0 @@
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
echo 正在执行 PowerShell 命令解除文件锁定...
powershell -Command "Get-ChildItem -Path \"%cd%\" -Recurse | Unblock-File"
if %errorlevel% equ 0 (
echo 文件解锁完成
) else (
echo 文件解锁失败,请检查 PowerShell 权限
)
echo.
echo 检查 ShuFuAi.exe.config 文件...
if exist "ShuFuAi.exe.config" (
echo ShuFuAi.exe.config 已存在,跳过创建
) else (
echo 正在创建 ShuFuAi.exe.config...
(
echo ^<?xml version="1.0" encoding="utf-8" ?^>
echo ^<configuration^>
echo ^<runtime^>
echo ^<loadFromRemoteSources enabled="true"/^>
echo ^</runtime^>
echo ^</configuration^>
) > "ShuFuAi.exe.config"
if exist "ShuFuAi.exe.config" (
echo ShuFuAi.exe.config 创建成功
) else (
echo ShuFuAi.exe.config 创建失败,请检查权限
)
)
echo.
echo 操作完成!
pause
@@ -12,15 +12,15 @@
<span class="hero-pill">运营辅助 · 数据安全 · 高效跟价</span>
<h1 class="hero-title">让亚马逊运营,更清晰高效</h1>
<p class="hero-sub">
从换算、查询、采集、去重到上架跟价,23 个工具按「常用 · 前端 · 运营 · 后勤」四线组织,每条工具一句话讲清用途,标准流程一步不缺。
从采集、去重、查品到上架跟价,20 个工具按「前端 · 运营 · 后勤」三线组织,每条工具一句话讲清用途,标准流程一步不缺。
</p>
<div class="hero-stats">
<div class="stat">
<strong style="color: #2dd4bf">23</strong>
<strong style="color: #2dd4bf">20</strong>
<span>个工具</span>
</div>
<div class="stat">
<strong style="color: #60a5fa">4</strong>
<strong style="color: #60a5fa">3</strong>
<span>大分类</span>
</div>
<div class="stat">
@@ -128,7 +128,7 @@ import AmazonFooterBar from '@/pages/amazon/components/AmazonFooterBar.vue'
import ToolIcon from '@/pages/amazon/components/ToolIcon.vue'
import { TUTORIAL_DOWNLOAD_URL, resolveTutorialDownloadUrl } from '@/pages/amazon/download-btn'
import { filterGroupsByPermission, filterWorkflowByPermission, TOOL_GROUPS, TOOL_MAP } from '@/pages/amazon/tool-catalog'
import type { ToolGroup, ToolGroupKey, ToolInfo, VisibleGroup, WorkflowStep } from '@/pages/amazon/tool-catalog'
import type { ToolGroup, ToolInfo, VisibleGroup, WorkflowStep } from '@/pages/amazon/tool-catalog'
import { resolvePageHref } from '@/shared/page-prefix'
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
import { prefetchRouteChunk } from '@/shared/route-prefetch'
@@ -143,7 +143,7 @@ const visibleGroups = ref<VisibleGroup[]>(TOOL_GROUPS.map((group) => ({ ...group
const permissionUnavailable = ref(false)
const statusText = ref('')
const statusType = ref<'normal' | 'error'>('normal')
const activeCat = ref<ToolGroupKey>('front')
const activeCat = ref<'front' | 'ops' | 'logi'>('front')
let statusTimer: number | undefined
const currentGroup = computed(() => visibleGroups.value.find((g) => g.key === activeCat.value) ?? visibleGroups.value[0])
@@ -249,15 +249,15 @@ async function onDownloadClick() {
window.open(safeHttpUrl(url), '_blank', 'noopener')
}
function onCatChange(key: ToolGroupKey) {
function onCatChange(key: 'front' | 'ops' | 'logi') {
activeCat.value = key
history.replaceState(null, '', `#group-${key}`)
}
function parseHashGroup() {
const hash = window.location.hash.replace('#', '')
const m = /^group-(common|front|ops|logi)$/.exec(hash)
if (m) activeCat.value = m[1] as ToolGroupKey
const m = /^group-(front|ops|logi)$/.exec(hash)
if (m) activeCat.value = m[1] as 'front' | 'ops' | 'logi'
}
onMounted(async () => {
@@ -35,7 +35,6 @@ import AmazonTopBar from '@/pages/amazon/components/AmazonTopBar.vue'
import AmazonFooterBar from '@/pages/amazon/components/AmazonFooterBar.vue'
import DownloadProgressPanel from '@/shared/components/DownloadProgressPanel.vue'
import { TOOL_DETAILS, TOOL_GROUPS, TOOL_MAP } from '@/pages/amazon/tool-catalog'
import type { ToolGroupKey } from '@/pages/amazon/tool-catalog'
import { resolvePageHref } from '@/shared/page-prefix'
/** Aliprice 注册推广链接(对齐 gemini-code 工具页头 Aliprice 按钮) */
@@ -49,7 +48,7 @@ const props = defineProps<{
const tool = computed(() => TOOL_MAP.get(props.toolId))
const group = computed(() => TOOL_GROUPS.find((g) => g.tools.some((t) => t.id === props.toolId)))
const groupKey = computed<ToolGroupKey>(() => group.value?.key ?? 'front')
const groupKey = computed(() => group.value?.key ?? 'front')
const detailText = computed(() => {
if (!tool.value) return ''
return TOOL_DETAILS[tool.value.id] ?? tool.value.desc
@@ -42,21 +42,21 @@ import { computed, onMounted, ref } from 'vue'
import BrandApiSecretSettingsButton from '@/pages/brand/components/BrandApiSecretSettingsButton.vue'
import NotificationBell from '@/shared/components/NotificationBell.vue'
import { filterGroupsByPermission, TOOL_GROUPS } from '@/pages/amazon/tool-catalog'
import type { ToolGroupKey, VisibleGroup } from '@/pages/amazon/tool-catalog'
import type { VisibleGroup } from '@/pages/amazon/tool-catalog'
import { resolvePageHref } from '@/shared/page-prefix'
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
const props = withDefaults(
defineProps<{
/** 当前工具所属分类(功能页高亮对应 tab;工具台首页不传) */
activeCat?: ToolGroupKey
activeCat?: 'front' | 'ops' | 'logi'
}>(),
{
activeCat: undefined,
},
)
const emit = defineEmits<{ change: [key: ToolGroupKey] }>()
const emit = defineEmits<{ change: [key: 'front' | 'ops' | 'logi'] }>()
const activeCat = computed(() => props.activeCat)
const visibleCats = ref<VisibleGroup[]>(TOOL_GROUPS.map((group) => ({ ...group, tools: [...group.tools] })))
@@ -67,7 +67,7 @@ const toolbarHref = resolvePageHref('/new_web_source/amazon-console.html')
/** 返回桌面入口首页(亚马逊/视频/图片入口) */
const homeHref = resolvePageHref('/new_web_source/home.html')
function onTabClick(key: ToolGroupKey) {
function onTabClick(key: 'front' | 'ops' | 'logi') {
emit('change', key)
}
@@ -1,43 +0,0 @@
/**
* 定价利润换算页 · 常用链接与资料下载
*
* 链接清单源自桌面版 shufu_calc_app.py 的 PAGE_LINKS / 资料页(2026-10-23 实测可达),
* 下载文件源自「数富资料下载_独立版_v1.0.0」,源文件在 public/materials/,
* 发布时由 scripts/deploy_app_web.py 的 EXPECTED_STATIC 白名单上传到站点 /static/。
*/
export type CommonLink = {
name: string
url: string
}
export type DownloadItem = {
name: string
/** public/materials/ 下的文件名(含空格/中文,渲染时 encodeURI) */
file: string
}
export const PRICING_COMMON_LINKS: ReadonlyArray<CommonLink> = [
{ name: 'Aliprice 1688 采集插件', url: 'https://www.aiprice.com/?ext_id=10100&channel=chrome_offline&platform=1688&version=4.0.5' },
{ name: '店小密导出设置', url: 'https://www.dianxiaomi.com/web/orderSetting/export' },
{ name: '数富AI BUG登记系统', url: 'https://bug.aishufu.top/bug-tracker/' },
{ name: '代理IP提取', url: 'https://www.jikip.com/user/extractapi' },
{ name: 'LLM 平台', url: 'https://ai.t8star.org/' },
{ name: '豆包CDN短链', url: 'https://aka.doubaocdn.com/s/O1DRPbr9rd#f=1' },
{ name: '紫鸟浏览器下载', url: 'https://www.ziniao.com/download/?from=97340' },
{ name: '无影下载', url: 'https://www.aliyun.com/product/wuying/download' },
{ name: 'WebView2 运行时', url: 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' },
]
export const PRICING_DOWNLOADS: ReadonlyArray<DownloadItem> = [
{ name: 'winsrc兼容补丁.bat', file: 'winsrc兼容补丁.bat' },
{ name: '百分30利润表格.xlsx', file: '百分30利润表格.xlsx' },
{ name: '虚拟桌面任务工作_结构化.xlsx', file: '虚拟桌面任务工作_结构化.xlsx' },
{ name: '设置最低价ASIN 批量文档格式.xlsx', file: '设置最低价ASIN 批量文档格式.xlsx' },
]
export function downloadHref(file: string): string {
// 走既有 /static/ 静态位(nginx 已配,deploy_app_web.py 的 EXPECTED_STATIC 白名单同步登记);
// /materials/ 这类新目录不在发布清单里,上线即 404。
return `/static/${encodeURI(file)}`
}
+1 -44
View File
@@ -29,11 +29,8 @@ export type WorkflowStep = {
toolId?: string
}
/** 工具分组键(常用工具组排在最前) */
export type ToolGroupKey = 'common' | 'front' | 'ops' | 'logi'
export type ToolGroup = {
key: ToolGroupKey
key: 'front' | 'ops' | 'logi'
/** 菜单权限组键(与 BrandTopBar 一致) */
columnKey: string
name: string
@@ -51,37 +48,6 @@ export type ToolGroup = {
}
export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
{
key: 'common',
columnKey: 'brand_common_tools',
name: '常用工具',
desc: '换算 · 查询 · 词库共享,高频小工具',
color: '#F59E0B',
weak: '#3A2A10',
tools: [
{
id: 'pricing-calc',
name: '定价利润换算',
desc: '输入售价、运费、成本,自动换算利润与毛利,多币种同步',
href: '/pricing-calc',
permissionKeys: ['pricing-calc'],
},
{
id: 'five-asin',
name: '五国ASIN快速查询',
desc: '按国家输入ASIN,自动生成带邮编与汇率的链接,跳转谷歌直达',
href: '/five-asin',
permissionKeys: ['five-asin'],
},
{
id: 'keyword-share',
name: '五国关键词共享',
desc: '词库跨账户共享、已使用标记、操作记录留痕,防重复使用',
href: '/keyword-share',
permissionKeys: ['keyword-share'],
},
],
},
{
key: 'front',
columnKey: 'brand_front_tools',
@@ -294,9 +260,6 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
/** 图标渐变背景(照 icons.py ICON_COLORS 转 CSS) */
export const TOOL_ICON_GRADIENTS: Record<string, string> = {
'pricing-calc': 'linear-gradient(180deg, #FCD34D, #F59E0B)',
'five-asin': 'linear-gradient(180deg, #FDBA74, #F97316)',
'keyword-share': 'linear-gradient(180deg, #86EFAC, #22C55E)',
collect: 'linear-gradient(180deg, #5EEAD4, #14B8A6)',
variant: 'linear-gradient(180deg, #93C5FD, #3B82F6)',
dedupe: 'linear-gradient(180deg, #C4B5FD, #8B5CF6)',
@@ -324,12 +287,6 @@ export const TOOL_ICON_GRADIENTS: Record<string, string> = {
* 默认描边 stroke:#fff width:3(方头 butt),实心填充 shape 用 .fill 标记
*/
export const TOOL_ICON_SHAPES: Record<string, string> = {
// 定价利润换算:计算器(屏+按键)
'pricing-calc': '<rect x="12" y="8" width="24" height="32" rx="2"/><line x1="17" y1="14" x2="31" y2="14"/><line x1="18" y1="23" x2="22" y2="23"/><line x1="26" y1="23" x2="30" y2="23"/><line x1="18" y1="29" x2="22" y2="29"/><line x1="26" y1="29" x2="30" y2="29"/><line x1="18" y1="35" x2="22" y2="35"/><line x1="26" y1="35" x2="30" y2="35"/>',
// 五国ASIN快速查询:地球+放大镜
'five-asin': '<circle cx="21" cy="21" r="12"/><line x1="21" y1="9" x2="21" y2="33"/><line x1="9" y1="21" x2="33" y2="21"/><path d="M11 13 A 14 14 0 0 0 31 13"/><path d="M11 29 A 14 14 0 0 1 31 29"/><circle cx="32" cy="32" r="7"/><line x1="37" y1="37" x2="42" y2="42" stroke-width="4"/>',
// 五国关键词共享:分享三节点
'keyword-share': '<circle class="fill" cx="13" cy="24" r="4"/><circle class="fill" cx="34" cy="11" r="4"/><circle class="fill" cx="34" cy="37" r="4"/><line x1="16" y1="22" x2="31" y2="13"/><line x1="16" y1="26" x2="31" y2="35"/>',
// 采集数据:圆角方框+向下箭头
collect: '<rect x="10" y="8" width="28" height="24"/><line x1="24" y1="14" x2="24" y2="36"/><path class="fill" d="M19 33 L29 33 L24 38 Z"/>',
// ASIN变体采集:两个重叠方框
@@ -94,15 +94,6 @@ const showActions = props.showActions
const allowedColumnKeys = ref<string[]>([])
const navGroups: ReadonlyArray<NavGroup> = [
{
columnKey: 'brand_common_tools',
label: '常用工具',
items: [
{ key: 'pricing-calc', label: '定价利润换算', href: '/pricing-calc' },
{ key: 'five-asin', label: '五国ASIN快速查询', href: '/five-asin' },
{ key: 'keyword-share', label: '五国关键词共享', href: '/keyword-share' },
],
},
{
columnKey: 'brand_front_tools',
label: '前端工具',
@@ -1,306 +0,0 @@
<template>
<div class="page-shell module-page">
<AmazonToolPageShell tool-id="five-asin">
<div class="asin-body">
<section class="asin-panel">
<div class="panel-title">选择国家</div>
<div class="country-row" role="radiogroup" aria-label="国家选择">
<button
v-for="country in FIVE_ASIN_COUNTRIES"
:key="country.code"
type="button"
class="country-btn"
:class="{ 'country-btn--active': countryKey === country.code }"
@click="selectCountry(country.code)"
>
<span class="country-flag">{{ country.flag }}</span>
<span>{{ country.name }}</span>
</button>
</div>
</section>
<section class="asin-panel">
<div class="panel-title">输入 ASIN</div>
<div class="asin-input-row">
<el-input
v-model="asinInput"
clearable
placeholder="输入 10 位 ASIN,如 B0C1234ABC"
@keyup.enter="openProductPage"
/>
<button type="button" class="btn-run" :disabled="!isValid" @click="openProductPage">打开商品页</button>
</div>
<p v-if="asinError" class="asin-error">{{ asinError }}</p>
<div v-if="productUrl" class="link-card">
<a class="link-url" :href="safeHttpUrl(productUrl)" target="_blank" rel="noopener">{{ productUrl }}</a>
<button type="button" class="btn-ghost" @click="copyLink">复制链接</button>
</div>
<p class="panel-hint">链接同时可点击与复制,浏览器拦截弹窗时用「复制链接」兜底。</p>
</section>
<section class="asin-panel">
<div class="panel-title">{{ currentCountry.flag }} {{ currentCountry.name }} · 邮编信息</div>
<div class="postcode-row">
<span class="postcode-value">{{ currentCountry.postcode }}</span>
<span class="postcode-city">{{ currentCountry.city }} · {{ currentCountry.currency }}</span>
<button type="button" class="btn-ghost" @click="copyPostcode">复制邮编</button>
</div>
</section>
</div>
</AmazonToolPageShell>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue'
import {
buildAmazonProductUrl,
FIVE_ASIN_COUNTRIES,
FIVE_ASIN_COUNTRY_MAP,
isValidAsin,
normalizeAsin,
} from '@/pages/common/five-asin'
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
const countryKey = ref('uk')
const asinInput = ref('')
const currentCountry = computed(() => FIVE_ASIN_COUNTRY_MAP.get(countryKey.value) ?? FIVE_ASIN_COUNTRIES[0])
const normalizedAsin = computed(() => normalizeAsin(asinInput.value))
const isValid = computed(() => isValidAsin(normalizedAsin.value))
/** 有输入但不合法时给红字提示;空输入不打扰 */
const asinError = computed(() => {
if (!asinInput.value.trim()) return ''
return isValid.value ? '' : 'ASIN 必须是 10 位字母或数字'
})
const productUrl = computed(() =>
isValid.value ? buildAmazonProductUrl(currentCountry.value.domain, normalizedAsin.value) : '',
)
function selectCountry(code: string) {
countryKey.value = code
}
function openProductPage() {
const url = productUrl.value
if (!url) {
ElMessage.warning('请输入 10 位 ASIN(字母或数字)')
return
}
if (!isHttpUrl(url)) {
// 链接由写死的域名常量拼出,这里照出口守卫口径再判一次
ElMessage.error('链接地址不合法,已取消打开')
return
}
window.open(safeHttpUrl(url), '_blank', 'noopener')
}
function copyText(text: string, successText: string) {
if (!text) return
navigator.clipboard
.writeText(text)
.then(() => ElMessage.success(successText))
.catch(() => ElMessage.error('复制失败,请手动复制'))
}
function copyLink() {
copyText(productUrl.value, '链接已复制')
}
function copyPostcode() {
copyText(currentCountry.value.postcode, '邮编已复制')
}
</script>
<style scoped>
.page-shell.module-page {
min-height: 0;
}
.asin-body {
height: 100%;
overflow-y: auto;
overscroll-behavior: contain;
padding: 14px 34px 28px;
display: flex;
flex-direction: column;
gap: 16px;
}
.asin-panel {
max-width: 1080px;
width: 100%;
margin: 0 auto;
padding: 18px 24px;
border: 1px solid #3e4a62;
border-radius: 10px;
background: #232a3b;
}
.panel-title {
margin-bottom: 14px;
color: #f5f8fc;
font-size: 16px;
font-weight: 700;
}
.panel-hint {
margin: 8px 0 0;
color: #a0acbe;
font-size: 12px;
}
.country-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.country-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 9px 16px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.country-btn:hover {
border-color: #22c55e;
color: #f5f8fc;
}
.country-btn--active {
border-color: #22c55e;
background: #12301f;
color: #86efac;
}
.country-flag {
font-size: 16px;
}
.asin-input-row {
display: flex;
gap: 10px;
}
.asin-error {
margin: 8px 0 0;
color: #f87171;
font-size: 12px;
}
.btn-run {
flex-shrink: 0;
padding: 9px 22px;
border: none;
border-radius: 6px;
background: linear-gradient(135deg, #22c55e, #16a34a);
color: #ffffff;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-run:hover:not(:disabled) {
filter: brightness(1.15);
}
.btn-run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-ghost {
flex-shrink: 0;
padding: 8px 18px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: transparent;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-ghost:hover {
background: #2b3447;
color: #f5f8fc;
}
.link-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 14px;
padding: 12px 16px;
border: 1px solid #2f5d43;
border-radius: 8px;
background: #12301f;
}
.link-url {
min-width: 0;
color: #86efac;
font-size: 14px;
word-break: break-all;
text-decoration: none;
}
.link-url:hover {
text-decoration: underline;
}
.postcode-row {
display: flex;
align-items: center;
gap: 14px;
}
.postcode-value {
padding: 6px 16px;
border: 1px solid #2f5d43;
border-radius: 6px;
background: #12301f;
color: #86efac;
font-size: 18px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.postcode-city {
flex: 1;
color: #a0acbe;
font-size: 13px;
}
@media (max-width: 900px) {
.asin-body {
padding: 14px 16px 24px;
}
.asin-input-row {
flex-direction: column;
}
}
</style>
@@ -1,573 +0,0 @@
<template>
<div class="page-shell module-page">
<AmazonToolPageShell tool-id="keyword-share">
<div class="ks-body">
<!-- 筛选区 -->
<section class="ks-panel ks-filters">
<div class="filter-grid">
<label class="filter-item">
<span class="filter-label">国家</span>
<el-select v-model="filterCountry" clearable placeholder="全部国家" class="filter-select">
<el-option v-for="name in countries" :key="name" :label="name" :value="name" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">一级类目</span>
<el-select v-model="filterCategory" clearable placeholder="全部一级" class="filter-select" @change="onCategoryChange">
<el-option v-for="cat in categories" :key="cat.name" :label="cat.name" :value="cat.name" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">二级类目</span>
<el-select v-model="filterSubCategory" clearable placeholder="全部二级" class="filter-select" :disabled="!filterCategory" @change="onSubCategoryChange">
<el-option v-for="sub in subOptions" :key="sub.name" :label="sub.name" :value="sub.name" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">三级类目</span>
<el-select v-model="filterCategoryL3" clearable placeholder="全部三级" class="filter-select" :disabled="!filterSubCategory" @change="onL3Change">
<el-option v-for="l3 in l3Options" :key="l3.name" :label="l3.name" :value="l3.name" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">四级类目</span>
<el-select v-model="filterCategoryL4" clearable placeholder="全部四级" class="filter-select" :disabled="!filterCategoryL3">
<el-option v-for="l4 in l4Options" :key="l4" :label="l4" :value="l4" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">关键词 / 中文</span>
<el-input v-model="filterSearch" clearable placeholder="搜索关键词或中文" @input="onSearchInput" />
</label>
<label class="filter-item">
<span class="filter-label">使用状态</span>
<el-select v-model="filterStatus" class="filter-select">
<el-option label="全部" value="all" />
<el-option label="已使用" value="used" />
<el-option label="未使用" value="unused" />
</el-select>
</label>
<label class="filter-item">
<span class="filter-label">已使用时间</span>
<el-select v-model="filterUsedDays" class="filter-select">
<el-option v-for="opt in USED_DAYS_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
</el-select>
</label>
<label class="filter-item filter-item--switch">
<span class="filter-label">仅看我使用</span>
<el-switch v-model="filterOnlyMine" />
</label>
</div>
<!-- 统计卡 -->
<div class="stat-cards">
<div class="stat-card">
<span class="stat-label">命中总数</span>
<strong class="stat-value">{{ stats.hit }}</strong>
</div>
<div class="stat-card">
<span class="stat-label">已使用</span>
<strong class="stat-value stat-value--used">{{ stats.used }}</strong>
</div>
<div class="stat-card">
<span class="stat-label">未使用</span>
<strong class="stat-value stat-value--unused">{{ stats.unused }}</strong>
</div>
<div class="stat-card">
<span class="stat-label">跨国重复</span>
<strong class="stat-value">{{ stats.dup }}</strong>
</div>
<button type="button" class="btn-ghost" @click="statsDialogVisible = true">词库统计</button>
</div>
</section>
<!-- 操作区 -->
<section class="ks-toolbar">
<button type="button" class="btn-run" @click="addDialogVisible = true">添加</button>
<button type="button" class="btn-ghost" @click="randomDialogVisible = true">随机抽词</button>
<button type="button" class="btn-ghost" @click="logsDialogVisible = true">团队共享记录</button>
</section>
<!-- 列表 -->
<section class="ks-panel">
<el-table v-loading="listLoading" :data="rows" row-key="id" class="ks-table" height="520">
<el-table-column prop="keyword" label="关键词" min-width="160" show-overflow-tooltip />
<el-table-column prop="chinese" label="中文" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.chinese || '—' }}</template>
</el-table-column>
<el-table-column prop="category" label="一级类目" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.category || '—' }}</template>
</el-table-column>
<el-table-column prop="subCategory" label="二级类目" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.subCategory || '—' }}</template>
</el-table-column>
<el-table-column prop="categoryL3" label="三级类目" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.categoryL3 || '—' }}</template>
</el-table-column>
<el-table-column prop="categoryL4" label="四级类目" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.categoryL4 || '—' }}</template>
</el-table-column>
<el-table-column prop="country" label="国家" width="90" show-overflow-tooltip />
<el-table-column label="使用状态" width="200" show-overflow-tooltip>
<template #default="{ row }">
<span :class="row.used ? 'used' : 'unused'">{{ formatUsedStatus(row) }}</span>
</template>
</el-table-column>
<el-table-column label="操作" width="220" align="center" fixed="right">
<template #default="{ row }">
<button type="button" class="link-op" @click="copyKeyword(row)">复制</button>
<button type="button" class="link-op" @click="toggleUsed(row)">{{ row.used ? '标记未使用' : '标记已使用' }}</button>
<button type="button" class="link-danger" @click="removeKeyword(row)">删除</button>
</template>
</el-table-column>
</el-table>
<el-pagination
class="ks-pagination"
layout="total, prev, pager, next, jumper"
:total="total"
:page-size="PAGE_SIZE"
:current-page="page"
@current-change="onPageChange"
/>
</section>
</div>
<AddKeywordsDialog
v-model="addDialogVisible"
:country-options="countries"
:default-country="filterCountry"
@added="reloadFromFirstPage"
/>
<KeywordStatsDialog v-model="statsDialogVisible" />
<RandomKeywordsDialog v-model="randomDialogVisible" @marked="loadList" />
<ShareLogsDialog v-model="logsDialogVisible" />
</AmazonToolPageShell>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue'
import AddKeywordsDialog from '@/pages/common/keyword-share/AddKeywordsDialog.vue'
import KeywordStatsDialog from '@/pages/common/keyword-share/KeywordStatsDialog.vue'
import RandomKeywordsDialog from '@/pages/common/keyword-share/RandomKeywordsDialog.vue'
import ShareLogsDialog from '@/pages/common/keyword-share/ShareLogsDialog.vue'
import {
deleteKeywordShareKeywords,
fetchKeywordShareFilters,
fetchKeywordShareKeywords,
markKeywordShareUsage,
unmarkKeywordShareUsage,
} from '@/shared/api/types/modules/keyword-share'
import type {
KeywordShareCategory,
KeywordShareFiltersVo,
KeywordShareListVo,
KeywordShareRow,
KeywordShareStatusFilter,
KeywordShareUsedDays,
} from '@/shared/api/types/modules/keyword-share'
/** 后端分页每页 200(契约固定) */
const PAGE_SIZE = 200
const SEARCH_DEBOUNCE_MS = 300
const USED_DAYS_OPTIONS: ReadonlyArray<{ label: string; value: KeywordShareUsedDays }> = [
{ label: '全部', value: 0 },
{ label: '今天', value: 1 },
{ label: '近7天', value: 7 },
{ label: '近30天', value: 30 },
{ label: '近90天', value: 90 },
{ label: '近180天', value: 180 },
{ label: '近360天', value: 360 },
]
// ---- 筛选状态 ----
const filterCountry = ref('')
const filterCategory = ref('')
const filterSubCategory = ref('')
const filterCategoryL3 = ref('')
const filterCategoryL4 = ref('')
const filterSearch = ref('')
const filterStatus = ref<KeywordShareStatusFilter>('all')
const filterUsedDays = ref<KeywordShareUsedDays>(0)
const filterOnlyMine = ref(false)
// ---- 词库数据 ----
const filtersVo = ref<KeywordShareFiltersVo | null>(null)
const listVo = ref<KeywordShareListVo | null>(null)
const listLoading = ref(false)
const page = ref(1)
const rows = computed<KeywordShareRow[]>(() => listVo.value?.rows ?? [])
const total = computed(() => listVo.value?.total ?? 0)
const stats = computed(() => {
const raw = listVo.value?.stats
const num = (value: unknown) => (Number.isFinite(Number(value)) ? Number(value) : 0)
return {
hit: num(raw?.hit),
used: num(raw?.used),
unused: num(raw?.unused),
dup: num(raw?.dup),
}
})
const countries = computed<string[]>(() => filtersVo.value?.countries ?? [])
const categories = computed<KeywordShareCategory[]>(() => filtersVo.value?.categories ?? [])
const currentCategory = computed(() => categories.value.find((cat) => cat.name === filterCategory.value))
const currentSub = computed(() => currentCategory.value?.subs.find((sub) => sub.name === filterSubCategory.value))
const currentL3 = computed(() => currentSub.value?.l3.find((item) => item.name === filterCategoryL3.value))
const subOptions = computed(() => currentCategory.value?.subs ?? [])
const l3Options = computed(() => currentSub.value?.l3 ?? [])
const l4Options = computed<string[]>(() => currentL3.value?.l4 ?? [])
/** 级联父级变化时清空子级已选值 */
function onCategoryChange() {
filterSubCategory.value = ''
filterCategoryL3.value = ''
filterCategoryL4.value = ''
reloadFromFirstPage()
}
function onSubCategoryChange() {
filterCategoryL3.value = ''
filterCategoryL4.value = ''
reloadFromFirstPage()
}
function onL3Change() {
filterCategoryL4.value = ''
reloadFromFirstPage()
}
// ---- 搜索防抖(300ms 触发重新查询)----
let searchTimer: number | undefined
function onSearchInput() {
if (searchTimer !== undefined) {
window.clearTimeout(searchTimer)
}
searchTimer = window.setTimeout(() => {
searchTimer = undefined
reloadFromFirstPage()
}, SEARCH_DEBOUNCE_MS)
}
function clearSearchTimer() {
if (searchTimer !== undefined) {
window.clearTimeout(searchTimer)
searchTimer = undefined
}
}
function reloadFromFirstPage() {
page.value = 1
void loadList()
}
// ---- 数据加载(失败 toast,不白屏)----
function loadList() {
listLoading.value = true
fetchKeywordShareKeywords({
country: filterCountry.value,
category: filterCategory.value,
subCategory: filterSubCategory.value,
categoryL3: filterCategoryL3.value,
categoryL4: filterCategoryL4.value,
search: filterSearch.value,
status: filterStatus.value,
usedDays: filterUsedDays.value,
onlyMine: filterOnlyMine.value,
page: page.value,
size: PAGE_SIZE,
})
.then((data) => {
listVo.value = data
listLoading.value = false
})
.catch((error: unknown) => {
listLoading.value = false
ElMessage.error(error instanceof Error ? error.message : '关键词列表加载失败')
})
}
function loadFilters() {
fetchKeywordShareFilters()
.then((data) => {
filtersVo.value = data
})
.catch((error: unknown) => {
ElMessage.error(error instanceof Error ? error.message : '筛选条件加载失败')
})
}
function onPageChange(next: number) {
page.value = next
void loadList()
}
// ---- 行操作 ----
function formatUsedStatus(row: KeywordShareRow): string {
if (!row.used) return '未使用'
const parts = ['✓已使用']
if (row.usedTime) parts.push(String(row.usedTime))
if (row.usedUser) parts.push(String(row.usedUser))
return parts.join('·')
}
function copyKeyword(row: KeywordShareRow) {
const text = String(row.keyword ?? '')
if (!text) return
navigator.clipboard
.writeText(text)
.then(() => ElMessage.success('关键词已复制'))
.catch(() => ElMessage.error('复制失败,请手动复制'))
}
function toggleUsed(row: KeywordShareRow) {
const item = { country: String(row.country ?? ''), keyword: String(row.keyword ?? '') }
if (!item.country || !item.keyword) return
const request = row.used ? unmarkKeywordShareUsage([item]) : markKeywordShareUsage([item])
request
.then(() => {
ElMessage.success(row.used ? '已标记为未使用' : '已标记为已使用')
void loadList()
})
.catch((error: unknown) => {
ElMessage.error(error instanceof Error ? error.message : '使用状态更新失败')
})
}
function removeKeyword(row: KeywordShareRow) {
ElMessageBox.confirm(`确定删除关键词「${row.keyword}」吗?删除后不可恢复。`, '删除关键词', {
type: 'warning',
confirmButtonText: '删除',
cancelButtonText: '取消',
})
.then(() =>
deleteKeywordShareKeywords([row.id]).then((data) => {
ElMessage.success(`已删除 ${data.deleted} 条`)
void loadList()
}),
)
.catch(() => {
// 用户取消确认框:无提示即视为放弃
})
}
// ---- 弹窗开关(内容、请求与分页状态由各弹窗组件自持)----
const addDialogVisible = ref(false)
const statsDialogVisible = ref(false)
const randomDialogVisible = ref(false)
const logsDialogVisible = ref(false)
onMounted(() => {
loadFilters()
void loadList()
})
onBeforeUnmount(() => {
clearSearchTimer()
})
</script>
<style scoped>
.page-shell.module-page {
min-height: 0;
}
.ks-body {
height: 100%;
overflow-y: auto;
overscroll-behavior: contain;
padding: 14px 34px 28px;
display: flex;
flex-direction: column;
gap: 14px;
}
.ks-panel {
border: 1px solid #3e4a62;
border-radius: 10px;
background: #232a3b;
padding: 14px 18px;
}
.filter-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.filter-item {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.filter-label {
color: #a0acbe;
font-size: 12px;
}
.filter-select {
width: 100%;
}
.filter-item--switch {
flex-direction: row;
align-items: center;
gap: 10px;
}
.stat-cards {
display: flex;
align-items: center;
gap: 12px;
margin-top: 12px;
}
.stat-card {
flex: 1;
min-width: 0;
padding: 10px 14px;
border: 1px solid #3e4a62;
border-radius: 8px;
background: #2b3447;
}
.stat-label {
display: block;
color: #a0acbe;
font-size: 12px;
}
.stat-value {
display: block;
color: #f5f8fc;
font-size: 20px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.stat-value--used {
color: #86efac;
}
.stat-value--unused {
color: #93c5fd;
}
.ks-toolbar {
display: flex;
gap: 10px;
}
.btn-run {
padding: 9px 22px;
border: none;
border-radius: 6px;
background: linear-gradient(135deg, #22c55e, #16a34a);
color: #ffffff;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-run:hover:not(:disabled) {
filter: brightness(1.15);
}
.btn-run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-ghost {
padding: 8px 18px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-ghost:hover:not(:disabled) {
background: #323d52;
color: #f5f8fc;
}
.btn-ghost:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ks-table {
width: 100%;
}
.used {
color: #86efac;
}
.unused {
color: #93c5fd;
}
.ks-pagination {
margin-top: 12px;
justify-content: flex-end;
}
.link-op {
border: none;
background: transparent;
color: #93c5fd;
font-size: 12px;
font-family: inherit;
cursor: pointer;
padding: 0 4px;
}
.link-op:hover {
color: #f5f8fc;
}
.link-danger {
border: none;
background: transparent;
color: #f87171;
font-size: 12px;
font-family: inherit;
cursor: pointer;
padding: 0 4px;
}
.link-danger:hover {
color: #fca5a5;
}
.link-danger:disabled {
opacity: 0.4;
cursor: not-allowed;
}
@media (max-width: 1100px) {
.filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.ks-body {
padding: 14px 16px 24px;
}
}
</style>
@@ -1,464 +0,0 @@
<template>
<div class="page-shell module-page">
<AmazonToolPageShell tool-id="pricing-calc">
<div class="calc-body">
<section class="calc-panel">
<div class="panel-title">站点与成本</div>
<div class="station-row" role="radiogroup" aria-label="站点选择">
<button
v-for="station in PRICING_STATIONS"
:key="station.key"
type="button"
class="station-btn"
:class="{ 'station-btn--active': stationKey === station.key }"
@click="selectStation(station.key)"
>
{{ station.name }}({{ station.currency }})
</button>
</div>
<div class="input-grid">
<label class="input-item">
<span class="input-label">买货价(¥)</span>
<el-input
v-model="purchaseInput"
clearable
placeholder="如 25 或 ¥1,280"
@keyup.enter="runCalc"
/>
<span v-if="purchaseError" class="input-error">{{ purchaseError }}</span>
</label>
<label class="input-item">
<span class="input-label">运费(¥)</span>
<el-input
v-model="freightInput"
clearable
placeholder="如 3.5 或 ¥350"
@keyup.enter="runCalc"
/>
<span v-if="freightError" class="input-error">{{ freightError }}</span>
</label>
</div>
<div class="btn-row">
<button type="button" class="btn-run" @click="runCalc">换算利润</button>
<button type="button" class="btn-ghost" @click="resetAll">清空</button>
</div>
</section>
<section class="calc-panel">
<div class="panel-title">换算结果</div>
<div v-if="!result" class="result-empty">输入买货价与运费后点击「换算利润」,结果展示在这里。</div>
<div v-else class="result-grid">
<div class="result-card">
<span class="result-label">营业额(¥)</span>
<strong class="result-value">{{ formatMoney(result.revenue) }}</strong>
</div>
<div class="result-card">
<span class="result-label">利润(¥)</span>
<strong class="result-value" :class="{ 'result-value--neg': result.profit < 0 }">
{{ formatMoney(result.profit) }}
</strong>
</div>
<div class="result-card">
<span class="result-label">利润百分比</span>
<strong class="result-value">{{ formatProfitRate(result.profitRate) }}</strong>
</div>
<div class="result-card">
<span class="result-label">换算汇率({{ station?.currency }})</span>
<strong class="result-value">{{ formatExchangeRate(result.converted) }}</strong>
</div>
</div>
</section>
<section class="calc-panel calc-panel--note">
<div class="panel-title">公式说明</div>
<ul class="formula-list">
<li>成本 = 买货价 + 运费</li>
<li>营业额 = 成本 ÷ 0.5</li>
<li>平台费 = 营业额 × 20%</li>
<li>利润 = 营业额 − 成本 − 平台费</li>
<li>利润率 = 利润 ÷ 营业额</li>
<li>换算汇率 = 营业额 ÷ 站点除数(英国 9 / 德国·法国 8,反推外币单价)</li>
</ul>
<p class="formula-note">切换站点会清空当前结果;金额输入支持带 ¥/¥ 与千分位逗号。</p>
</section>
<section class="calc-panel">
<div class="panel-title">常用链接与资料下载</div>
<div class="resource-grid">
<div class="resource-block">
<div class="resource-block-title">常用链接</div>
<ul class="resource-list">
<li v-for="link in PRICING_COMMON_LINKS" :key="link.url" class="resource-item">
<span class="resource-name" :title="link.url">{{ link.name }}</span>
<a
class="resource-action"
:href="safeHttpUrl(link.url)"
target="_blank"
rel="noopener"
>打开</a>
<button
type="button"
class="resource-copy"
@click="copyText(link.url, `「${link.name}」链接已复制`)"
>复制</button>
</li>
</ul>
</div>
<div class="resource-block">
<div class="resource-block-title">资料下载</div>
<ul class="resource-list">
<li v-for="item in PRICING_DOWNLOADS" :key="item.file" class="resource-item">
<span class="resource-name">{{ item.name }}</span>
<a class="resource-action" :href="safeHttpUrl(downloadHref(item.file))" download>下载</a>
</li>
</ul>
</div>
</div>
</section>
</div>
</AmazonToolPageShell>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue'
import {
downloadHref,
PRICING_COMMON_LINKS,
PRICING_DOWNLOADS,
} from '@/pages/amazon/pricing-resources'
import { safeHttpUrl } from '@/shared/utils/safe-url'
import {
calcPricing,
formatExchangeRate,
formatMoney,
formatProfitRate,
parseMoneyInput,
PRICING_STATIONS,
PRICING_STATION_MAP,
} from '@/pages/common/pricing-calc'
import type { PricingResult, PricingStationKey } from '@/pages/common/pricing-calc'
const stationKey = ref<PricingStationKey>('uk')
const purchaseInput = ref('')
const freightInput = ref('')
const result = ref<PricingResult | null>(null)
const station = computed(() => PRICING_STATION_MAP.get(stationKey.value))
const purchaseError = computed(() => {
if (!purchaseInput.value.trim()) return ''
return parseMoneyInput(purchaseInput.value) === null ? '买货价格式不正确' : ''
})
const freightError = computed(() => {
if (!freightInput.value.trim()) return ''
return parseMoneyInput(freightInput.value) === null ? '运费格式不正确' : ''
})
/** 切换站点清空结果(口径照抄桌面版) */
function selectStation(key: PricingStationKey) {
if (stationKey.value === key) return
stationKey.value = key
result.value = null
}
function runCalc() {
const purchase = parseMoneyInput(purchaseInput.value)
const freight = parseMoneyInput(freightInput.value)
if (purchase === null || freight === null) {
ElMessage.warning('请输入合法的买货价与运费(支持 ¥/¥ 与千分位逗号)')
return
}
const current = station.value
if (!current) return
result.value = calcPricing(purchase, freight, current)
}
function resetAll() {
purchaseInput.value = ''
freightInput.value = ''
result.value = null
}
/** 复制常用链接(口径与 FiveAsinPage 一致:clipboard + toast,失败给明确提示) */
function copyText(text: string, successText: string) {
if (!text) return
navigator.clipboard
.writeText(text)
.then(() => ElMessage.success(successText))
.catch(() => ElMessage.error('复制失败,请手动复制'))
}
</script>
<style scoped>
.page-shell.module-page {
min-height: 0;
}
.calc-body {
height: 100%;
overflow-y: auto;
overscroll-behavior: contain;
padding: 14px 34px 28px;
display: flex;
flex-direction: column;
gap: 16px;
}
.calc-panel {
max-width: 1080px;
width: 100%;
margin: 0 auto;
padding: 18px 24px;
border: 1px solid #3e4a62;
border-radius: 10px;
background: #232a3b;
}
.calc-panel--note {
background: #1f2635;
}
.panel-title {
margin-bottom: 14px;
color: #f5f8fc;
font-size: 16px;
font-weight: 700;
}
.station-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 16px;
}
.station-btn {
padding: 9px 18px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.station-btn:hover {
border-color: #f59e0b;
color: #f5f8fc;
}
.station-btn--active {
border-color: #f59e0b;
background: #3a2a10;
color: #f59e0b;
}
.input-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
margin-bottom: 16px;
}
.input-item {
display: flex;
flex-direction: column;
gap: 6px;
}
.input-label {
color: #a0acbe;
font-size: 13px;
}
.input-error {
color: #f87171;
font-size: 12px;
}
.btn-row {
display: flex;
gap: 10px;
}
.btn-run {
padding: 9px 22px;
border: none;
border-radius: 6px;
background: linear-gradient(135deg, #f59e0b, #d97706);
color: #ffffff;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-run:hover {
filter: brightness(1.15);
}
.btn-ghost {
padding: 9px 22px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: transparent;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-ghost:hover {
background: #2b3447;
color: #f5f8fc;
}
.result-empty {
color: #a0acbe;
font-size: 13px;
}
.result-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 14px;
}
.result-card {
padding: 14px 16px;
border: 1px solid #3e4a62;
border-radius: 8px;
background: #2b3447;
}
.result-label {
display: block;
margin-bottom: 6px;
color: #a0acbe;
font-size: 12px;
}
.result-value {
display: block;
color: #f5f8fc;
font-size: 20px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.result-value--neg {
color: #f87171;
}
.formula-list {
margin: 0 0 10px;
padding-left: 20px;
color: #c8d2e2;
font-size: 13px;
line-height: 1.9;
}
.formula-note {
margin: 0;
color: #a0acbe;
font-size: 12px;
}
.resource-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
}
.resource-block-title {
margin-bottom: 10px;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
}
.resource-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 8px;
}
.resource-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
}
.resource-name {
flex: 1;
min-width: 0;
overflow: hidden;
color: #f5f8fc;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.resource-action {
flex-shrink: 0;
color: #f59e0b;
font-size: 12px;
font-weight: 700;
text-decoration: none;
}
.resource-action:hover {
text-decoration: underline;
}
.resource-copy {
flex-shrink: 0;
padding: 4px 12px;
border: 1px solid #3e4a62;
border-radius: 4px;
background: transparent;
color: #c8d2e2;
font-size: 12px;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.resource-copy:hover {
border-color: #f59e0b;
color: #f59e0b;
}
@media (max-width: 900px) {
.input-grid,
.result-grid,
.resource-grid {
grid-template-columns: 1fr;
}
.calc-body {
padding: 14px 16px 24px;
}
}
</style>
@@ -1,55 +0,0 @@
/**
* 五国ASIN快速查询 · 纯逻辑(网页化桌面版五国ASIN工具)。
*
* 五国站点数据写死为常量(域名 / 默认邮编 / 币种 / 国旗),与桌面版一致;
* ASIN 规范化:strip + 大写 + 去掉非字母数字,规范化后必须 10 位。
* 桌面版的自动填邮编 / 切币种(Playwright 驱动 Chrome)网页版明确不做。
* 本模块不依赖 Vue / DOM,供 node --test 直接单测。
*/
export interface FiveAsinCountry {
/** 站点代号(页面内部 key) */
code: string
/** 国家显示名 */
name: string
/** 国旗 emoji */
flag: string
/** 亚马逊站点域名(不带协议) */
domain: string
/** 默认邮编 */
postcode: string
/** 邮编所在城市 */
city: string
/** 币种代码 */
currency: string
}
export const FIVE_ASIN_COUNTRIES: ReadonlyArray<FiveAsinCountry> = [
{ code: 'uk', name: '英国', flag: '🇬🇧', domain: 'www.amazon.co.uk', postcode: 'SW1A 1AA', city: '伦敦', currency: '英镑' },
{ code: 'de', name: '德国', flag: '🇩🇪', domain: 'www.amazon.de', postcode: '10115', city: '柏林', currency: '欧元' },
{ code: 'fr', name: '法国', flag: '🇫🇷', domain: 'www.amazon.fr', postcode: '75001', city: '巴黎', currency: '欧元' },
{ code: 'es', name: '西班牙', flag: '🇪🇸', domain: 'www.amazon.es', postcode: '28001', city: '马德里', currency: '欧元' },
{ code: 'it', name: '意大利', flag: '🇮🇹', domain: 'www.amazon.it', postcode: '20121', city: '米兰', currency: '欧元' },
]
export const FIVE_ASIN_COUNTRY_MAP: ReadonlyMap<string, FiveAsinCountry> = new Map(
FIVE_ASIN_COUNTRIES.map((country) => [country.code, country] as const),
)
/** ASIN 规范化:strip + 大写 + 去掉所有非字母数字字符 */
export function normalizeAsin(raw: string): string {
return String(raw ?? '')
.trim()
.toUpperCase()
.replace(/[^A-Z0-9]/g, '')
}
/** 规范化后的 ASIN 是否合法(必须恰好 10 位字母数字) */
export function isValidAsin(asin: string): boolean {
return /^[A-Z0-9]{10}$/.test(String(asin ?? ''))
}
/** 由站点域名与 ASIN 生成商品页地址:https://{domain}/dp/{asin} */
export function buildAmazonProductUrl(domain: string, asin: string): string {
return `https://${domain}/dp/${asin}`
}
@@ -1,204 +0,0 @@
<template>
<el-dialog
:model-value="modelValue"
title="添加关键词"
width="640px"
append-to-body
@update:model-value="(visible: boolean) => emit('update:modelValue', visible)"
@open="resetRows"
>
<div class="add-rows">
<div v-for="(item, index) in addRows" :key="index" class="add-row">
<el-select v-model="item.country" placeholder="国家" class="add-country">
<el-option v-for="name in countryOptions" :key="name" :label="name" :value="name" />
</el-select>
<el-input v-model="item.keyword" placeholder="关键词" class="add-keyword" />
<el-input v-model="item.chinese" placeholder="中文(可空)" class="add-chinese" />
<button
type="button"
class="link-danger"
:disabled="addRows.length <= 1"
@click="removeAddRow(index)"
>删除行</button>
</div>
</div>
<div class="dialog-btn-row">
<button type="button" class="btn-ghost" @click="addAddRow">再加一行</button>
<button type="button" class="btn-run" :disabled="addSubmitting" @click="submitAdd">
{{ addSubmitting ? '提交中...' : '批量添加' }}
</button>
</div>
<p v-if="addResultText" class="dialog-result">{{ addResultText }}</p>
</el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addKeywordShareKeywords } from '@/shared/api/types/modules/keyword-share'
import type { KeywordShareAddItem } from '@/shared/api/types/modules/keyword-share'
const props = defineProps<{
modelValue: boolean
countryOptions: string[]
defaultCountry: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', visible: boolean): void
(e: 'added'): void
}>()
const addRows = ref<KeywordShareAddItem[]>([])
const addSubmitting = ref(false)
const addResultText = ref('')
function emptyRow(): KeywordShareAddItem {
return { country: props.defaultCountry, keyword: '', chinese: '' }
}
function resetRows() {
addRows.value = [emptyRow()]
addResultText.value = ''
}
function addAddRow() {
addRows.value.push(emptyRow())
}
function removeAddRow(index: number) {
if (addRows.value.length <= 1) return
addRows.value.splice(index, 1)
}
function submitAdd() {
const items = addRows.value
.map((row) => ({
country: String(row.country ?? '').trim(),
keyword: String(row.keyword ?? '').trim(),
chinese: String(row.chinese ?? '').trim(),
}))
.filter((row) => row.country && row.keyword)
if (!items.length) {
ElMessage.warning('请至少填写一行完整的关键词(国家 + 关键词)')
return
}
addSubmitting.value = true
addKeywordShareKeywords(items)
.then((data) => {
addSubmitting.value = false
addResultText.value = `新增 ${data.added} 条,跳过(重复)${data.skipped} 条`
ElMessage.success(addResultText.value)
emit('added')
})
.catch((error: unknown) => {
addSubmitting.value = false
ElMessage.error(error instanceof Error ? error.message : '添加失败')
})
}
</script>
<style scoped>
.btn-run {
padding: 9px 22px;
border: none;
border-radius: 6px;
background: linear-gradient(135deg, #22c55e, #16a34a);
color: #ffffff;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-run:hover:not(:disabled) {
filter: brightness(1.15);
}
.btn-run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-ghost {
padding: 8px 18px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-ghost:hover:not(:disabled) {
background: #323d52;
color: #f5f8fc;
}
.btn-ghost:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.link-danger {
border: none;
background: transparent;
color: #f87171;
font-size: 12px;
font-family: inherit;
cursor: pointer;
padding: 0 4px;
}
.link-danger:hover {
color: #fca5a5;
}
.link-danger:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.add-rows {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 14px;
}
.add-row {
display: flex;
align-items: center;
gap: 10px;
}
.add-country {
width: 130px;
flex-shrink: 0;
}
.add-keyword {
flex: 1;
}
.add-chinese {
flex: 1;
}
.dialog-btn-row {
display: flex;
justify-content: flex-end;
gap: 10px;
}
.dialog-result {
margin: 10px 0 0;
color: #86efac;
font-size: 13px;
}
</style>
@@ -1,118 +0,0 @@
<template>
<el-dialog
:model-value="modelValue"
title="词库统计"
width="620px"
append-to-body
@update:model-value="(visible: boolean) => emit('update:modelValue', visible)"
@open="loadStats"
>
<div class="stats-sections">
<section v-for="section in STATS_SECTIONS" :key="section.key" class="stats-section">
<h4 class="stats-title">{{ section.title }}</h4>
<div v-if="!statsSections[section.key].length" class="dialog-empty">暂无数据</div>
<ul v-else class="stats-list">
<li v-for="item in statsSections[section.key]" :key="`${item.group}-${item.label}`" class="stats-row">
<span class="stats-label"><em v-if="item.group">{{ item.group }} / </em>{{ item.label }}</span>
<span class="stats-count">{{ item.count.toLocaleString('zh-CN') }}</span>
</li>
</ul>
</section>
</div>
</el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
buildKeywordStatsSections,
fetchKeywordShareStatsGrouped,
} from '@/shared/api/types/modules/keyword-share'
import type { KeywordStatsSections } from '@/shared/api/types/modules/keyword-share'
defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ (e: 'update:modelValue', visible: boolean): void }>()
/** 词库统计四段(与桌面版弹窗同序) */
const STATS_SECTIONS: ReadonlyArray<{ key: keyof KeywordStatsSections; title: string }> = [
{ key: 'byCountry', title: '按国家分布' },
{ key: 'byCategory', title: '按一级类目分布' },
{ key: 'bySubCategory', title: '按二级类目分布' },
{ key: 'byCategoryL3', title: '按三级类目分布' },
]
const EMPTY_STATS: KeywordStatsSections = { byCountry: [], byCategory: [], bySubCategory: [], byCategoryL3: [] }
const statsSections = ref<KeywordStatsSections>({ ...EMPTY_STATS })
function loadStats() {
fetchKeywordShareStatsGrouped()
.then((data) => {
statsSections.value = buildKeywordStatsSections(data)
})
.catch((error: unknown) => {
statsSections.value = { ...EMPTY_STATS }
ElMessage.error(error instanceof Error ? error.message : '词库统计加载失败')
})
}
</script>
<style scoped>
.dialog-empty {
color: #a0acbe;
font-size: 13px;
padding: 20px 0;
text-align: center;
}
.stats-sections {
max-height: 460px;
overflow-y: auto;
}
.stats-section + .stats-section {
border-top: 1px solid #2c3854;
margin-top: 12px;
padding-top: 12px;
}
.stats-title {
color: #4da3ff;
font-size: 13px;
margin: 0 0 6px;
}
.stats-list {
list-style: none;
margin: 0;
padding: 0;
}
.stats-row {
align-items: center;
display: flex;
font-size: 13px;
justify-content: space-between;
padding: 3px 0;
}
.stats-label {
color: #e8ecf4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.stats-label em {
color: #8b95ad;
font-style: normal;
}
.stats-count {
color: #ff9a3c;
font-weight: 600;
margin-left: 16px;
}
</style>
@@ -1,139 +0,0 @@
<template>
<el-dialog
:model-value="modelValue"
title="随机抽词(10 条)"
width="760px"
append-to-body
@update:model-value="(visible: boolean) => emit('update:modelValue', visible)"
@open="loadRandom"
>
<div v-if="loading" class="dialog-empty">抽词中...</div>
<div v-else-if="!rows.length" class="dialog-empty">暂无可抽取的关键词</div>
<el-table v-else :data="rows" class="ks-table" height="420" row-key="id">
<el-table-column prop="keyword" label="关键词" min-width="160" show-overflow-tooltip />
<el-table-column prop="chinese" label="中文" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.chinese || '—' }}</template>
</el-table-column>
<el-table-column prop="country" label="国家" width="90" />
<el-table-column label="使用状态" width="110">
<template #default="{ row }">
<span :class="row.used ? 'used' : 'unused'">{{ row.used ? '✓已使用' : '未使用' }}</span>
</template>
</el-table-column>
</el-table>
<div class="dialog-btn-row">
<button
type="button"
class="btn-run"
:disabled="!markableRows.length || marking"
@click="markRows"
>
{{ marking ? '标记中...' : `一键标记已使用(${markableRows.length})` }}
</button>
</div>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchKeywordShareRandom, markKeywordShareUsage } from '@/shared/api/types/modules/keyword-share'
import type { KeywordShareRow } from '@/shared/api/types/modules/keyword-share'
defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{
(e: 'update:modelValue', visible: boolean): void
(e: 'marked'): void
}>()
const rows = ref<KeywordShareRow[]>([])
const loading = ref(false)
const marking = ref(false)
const markableRows = computed(() => rows.value.filter((row) => !row.used))
function loadRandom() {
loading.value = true
fetchKeywordShareRandom(10)
.then((data) => {
loading.value = false
rows.value = Array.isArray(data) ? data : []
})
.catch((error: unknown) => {
loading.value = false
rows.value = []
ElMessage.error(error instanceof Error ? error.message : '随机抽词失败')
})
}
function markRows() {
const items = markableRows.value.map((row) => ({
country: String(row.country ?? ''),
keyword: String(row.keyword ?? ''),
}))
if (!items.length) return
marking.value = true
markKeywordShareUsage(items)
.then((data) => {
marking.value = false
ElMessage.success(`已标记 ${data.marked} 条为已使用`)
rows.value = rows.value.map((row) => ({ ...row, used: true }))
emit('marked')
})
.catch((error: unknown) => {
marking.value = false
ElMessage.error(error instanceof Error ? error.message : '标记失败')
})
}
</script>
<style scoped>
.btn-run {
padding: 9px 22px;
border: none;
border-radius: 6px;
background: linear-gradient(135deg, #22c55e, #16a34a);
color: #ffffff;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.btn-run:hover:not(:disabled) {
filter: brightness(1.15);
}
.btn-run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.dialog-btn-row {
display: flex;
justify-content: flex-end;
gap: 10px;
}
.dialog-empty {
color: #a0acbe;
font-size: 13px;
padding: 20px 0;
text-align: center;
}
.ks-table {
width: 100%;
}
.used {
color: #86efac;
}
.unused {
color: #93c5fd;
}
</style>
@@ -1,150 +0,0 @@
<template>
<el-dialog
:model-value="modelValue"
title="团队共享记录"
width="720px"
append-to-body
@update:model-value="(visible: boolean) => emit('update:modelValue', visible)"
@open="openFirstTab"
>
<div class="logs-tabs">
<button
v-for="tab in LOG_TYPE_TABS"
:key="tab.value"
type="button"
class="logs-tab"
:class="{ 'logs-tab--active': logType === tab.value }"
@click="switchLogType(tab.value)"
>{{ tab.label }}</button>
</div>
<div v-if="!logRows.length" class="dialog-empty">暂无记录</div>
<el-table v-else :data="logRows" class="ks-table" height="380">
<el-table-column prop="createdAt" label="时间" width="170" show-overflow-tooltip>
<template #default="{ row }">{{ row.createdAt || '—' }}</template>
</el-table-column>
<el-table-column prop="type" label="类型" width="90">
<template #default="{ row }">{{ formatLogType(row.type) }}</template>
</el-table-column>
<el-table-column prop="country" label="国家" width="90" show-overflow-tooltip>
<template #default="{ row }">{{ row.country || '—' }}</template>
</el-table-column>
<el-table-column prop="keyword" label="关键词" min-width="150" show-overflow-tooltip>
<template #default="{ row }">{{ row.keyword || '—' }}</template>
</el-table-column>
<el-table-column prop="operator" label="操作人" width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.operator || '—' }}</template>
</el-table-column>
</el-table>
<el-pagination
class="ks-pagination"
layout="total, prev, pager, next"
:total="logTotal"
:page-size="LOG_PAGE_SIZE"
:current-page="logPage"
@current-change="onLogPageChange"
/>
</el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchKeywordShareLogs } from '@/shared/api/types/modules/keyword-share'
import type { KeywordShareLogRow, KeywordShareLogType } from '@/shared/api/types/modules/keyword-share'
defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ (e: 'update:modelValue', visible: boolean): void }>()
const LOG_PAGE_SIZE = 20
const LOG_TYPE_TABS: ReadonlyArray<{ label: string; value: KeywordShareLogType }> = [
{ label: '使用', value: 'usage' },
{ label: '添加', value: 'add' },
{ label: '删除', value: 'delete' },
]
const logType = ref<KeywordShareLogType>('usage')
const logRows = ref<KeywordShareLogRow[]>([])
const logTotal = ref(0)
const logPage = ref(1)
function formatLogType(type: unknown): string {
if (type === 'usage') return '使用'
if (type === 'add') return '添加'
if (type === 'delete') return '删除'
return String(type ?? '—')
}
function loadLogs() {
fetchKeywordShareLogs({ type: logType.value, page: logPage.value, size: LOG_PAGE_SIZE })
.then((data) => {
logRows.value = Array.isArray(data?.rows) ? data.rows : []
logTotal.value = Number(data?.total) || 0
})
.catch((error: unknown) => {
logRows.value = []
logTotal.value = 0
ElMessage.error(error instanceof Error ? error.message : '共享记录加载失败')
})
}
function openFirstTab() {
logType.value = 'usage'
logPage.value = 1
void loadLogs()
}
function switchLogType(type: KeywordShareLogType) {
logType.value = type
logPage.value = 1
void loadLogs()
}
function onLogPageChange(next: number) {
logPage.value = next
void loadLogs()
}
</script>
<style scoped>
.ks-table {
width: 100%;
}
.ks-pagination {
margin-top: 12px;
justify-content: flex-end;
}
.dialog-empty {
color: #a0acbe;
font-size: 13px;
padding: 20px 0;
text-align: center;
}
.logs-tabs {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
.logs-tab {
padding: 7px 18px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #2b3447;
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
}
.logs-tab--active {
border-color: #22c55e;
background: #12301f;
color: #86efac;
}
</style>
@@ -1,95 +0,0 @@
/**
* 定价利润换算 · 纯计算逻辑(网页化桌面版定价换算工具)。
*
* 口径照抄桌面版:站点分 英国(英镑 GBP,换算除数 9)与 德国·法国(欧元 EUR,除数 8);
* 成本 = 买货价 + 运费;营业额 = 成本 ÷ 0.5;平台费 = 营业额 × 20%;
* 利润 = 营业额 − 成本 − 平台费;利润率 = 利润 ÷ 营业额;换算汇率 = 营业额 ÷ 除数。
*
* 金额输入允许带货币符号(¥/¥)与千分位逗号,解析时先剥离再 parseFloat。
* 本模块不依赖 Vue / DOM,供 node --test 直接单测。
*/
export type PricingStationKey = 'uk' | 'eu'
export interface PricingStation {
key: PricingStationKey
/** 站点显示名 */
name: string
/** 币种代码 */
currency: string
/** 营业额反推外币单价的换算除数 */
divisor: number
}
export const PRICING_STATIONS: ReadonlyArray<PricingStation> = [
{ key: 'uk', name: '英国', currency: 'GBP', divisor: 9 },
{ key: 'eu', name: '德国·法国', currency: 'EUR', divisor: 8 },
]
export const PRICING_STATION_MAP: ReadonlyMap<PricingStationKey, PricingStation> = new Map(
PRICING_STATIONS.map((station) => [station.key, station] as const),
)
/** 目标毛利率分母:营业额 = 成本 ÷ PROFIT_TARGET */
const PROFIT_TARGET = 0.5
/** 平台佣金比例:平台费 = 营业额 × PLATFORM_FEE_RATE */
const PLATFORM_FEE_RATE = 0.2
/**
* 解析金额输入:剥离 ¥/¥/千分位逗号/空白后再 parseFloat。
* 合法返回非负数值;空串、非纯数字(含尾部残渣如 12abc)、负数一律返回 null
* (由页面给出非法提示)。
*/
export function parseMoneyInput(raw: string): number | null {
const text = String(raw ?? '')
.replace(/[¥¥,\s]/g, '')
.trim()
if (!text || !/^\d*\.?\d+$/.test(text)) return null
const value = Number.parseFloat(text)
if (!Number.isFinite(value) || value < 0) return null
return value
}
export interface PricingResult {
/** 成本(买货价 + 运费) */
cost: number
/** 营业额(成本 ÷ 0.5) */
revenue: number
/** 平台费(营业额 × 20%) */
platformFee: number
/** 利润(营业额 − 成本 − 平台费) */
profit: number
/** 利润率(利润 ÷ 营业额;营业额为 0 时记 0) */
profitRate: number
/** 换算汇率(营业额 ÷ 站点除数,反推外币单价) */
converted: number
}
/** 按站点口径换算利润(入参必须是已通过 parseMoneyInput 的非负数值) */
export function calcPricing(purchasePrice: number, freight: number, station: PricingStation): PricingResult {
const cost = purchasePrice + freight
const revenue = cost / PROFIT_TARGET
const platformFee = revenue * PLATFORM_FEE_RATE
const profit = revenue - cost - platformFee
const profitRate = revenue > 0 ? profit / revenue : 0
const converted = revenue / station.divisor
return { cost, revenue, platformFee, profit, profitRate, converted }
}
/** 金额格式化:千分位 + 固定 2 位小数 */
export function formatMoney(value: number): string {
return Number(value ?? 0).toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
}
/** 利润率格式化:百分比 + 固定 1 位小数 */
export function formatProfitRate(value: number): string {
return `${(Number(value ?? 0) * 100).toFixed(1)}%`
}
/** 换算汇率格式化:固定 4 位小数 */
export function formatExchangeRate(value: number): string {
return Number(value ?? 0).toFixed(4)
}
-16
View File
@@ -122,22 +122,6 @@ const routes = [
name: 'withdraw',
component: () => import('@/pages/brand/components/BrandWithdrawTab.vue'),
},
// ---- 常用工具(网页化的桌面小工具;权限键与 tool-catalog / BrandTopBar 一致)----
{
path: '/pricing-calc',
name: 'pricing-calc',
component: () => import('@/pages/common/PricingCalcPage.vue'),
},
{
path: '/five-asin',
name: 'five-asin',
component: () => import('@/pages/common/FiveAsinPage.vue'),
},
{
path: '/keyword-share',
name: 'keyword-share',
component: () => import('@/pages/common/KeywordSharePage.vue'),
},
// ---- 兜底:未匹配路径回首页(保持与 MPA 时代"未知页 404 后回首页"一致体验)----
{ path: '/:pathMatch(.*)*', redirect: '/home' },
]
@@ -15,7 +15,6 @@ export * from "./types/modules/brand.ts";
export * from "./types/modules/permission.ts";
export * from "./types/modules/user-secret.ts";
export * from "./types/modules/digital-human.ts";
export * from "./types/modules/keyword-share.ts";
export * from "./progress-light.ts";
export * from "./upload.ts";
export * from "./download-url.ts";
@@ -1,342 +0,0 @@
import { del, get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
import { JAVA_API_PREFIX } from '../../url.ts'
/**
* 五国关键词共享 API(/api/keyword-share,后端并行实现,契约以本文档字段为准)。
*
* companyId 服务端取;鉴权与错误折叠统一走 shared/api/http 的请求封装。
* 所有函数返回 unwrapJavaResponse 拆包后的业务数据;失败时向调用方抛错
* (页面用 ElMessage 提示,不白屏)。
*/
export type KeywordShareStatusFilter = 'all' | 'used' | 'unused'
export type KeywordShareLogType = 'usage' | 'add' | 'delete'
/** 已使用时间筛选:0=全部(不传参),1=今天,7/30/90/180/360=近 N 天 */
export type KeywordShareUsedDays = 0 | 1 | 7 | 30 | 90 | 180 | 360
export interface KeywordShareRow {
id: number | string
country: string
keyword: string
chinese?: string | null
category?: string | null
subCategory?: string | null
categoryL3?: string | null
categoryL4?: string | null
used?: boolean
usedTime?: string | null
usedUser?: string | null
}
export interface KeywordShareStats {
/** 命中总数 */
hit: number
used: number
unused: number
/** 跨国重复 */
dup: number
}
export interface KeywordShareListVo {
total: number
rows: KeywordShareRow[]
stats: KeywordShareStats
}
export interface KeywordShareCategoryL3 {
name: string
l4: string[]
}
export interface KeywordShareSubCategory {
name: string
l3: KeywordShareCategoryL3[]
}
export interface KeywordShareCategory {
name: string
subs: KeywordShareSubCategory[]
}
export interface KeywordShareFiltersVo {
countries: string[]
categories: KeywordShareCategory[]
}
export interface KeywordShareAddItem {
country: string
keyword: string
chinese?: string
}
export interface KeywordShareAddVo {
added: number
skipped: number
}
export interface KeywordShareDeleteVo {
deleted: number
}
export interface KeywordShareMarkVo {
marked: number
}
export interface KeywordShareUnmarkVo {
unmarked: number
}
export interface KeywordShareLogRow {
id?: number | string
/** usage=标记使用 / add=添加 / delete=删除 */
type?: KeywordShareLogType | string
country?: string | null
keyword?: string | null
chinese?: string | null
operator?: string | null
createdAt?: string | null
detail?: string | null
}
export interface KeywordShareLogsVo {
total: number
rows: KeywordShareLogRow[]
}
export interface KeywordShareListQuery {
country?: string
/** 一级类目 */
category?: string
subCategory?: string
categoryL3?: string
categoryL4?: string
/** 关键词 / 中文模糊搜索 */
search?: string
status?: KeywordShareStatusFilter
/** 0=全部(不传参) */
usedDays?: KeywordShareUsedDays
/** 仅看我使用 */
onlyMine?: boolean
page?: number
size?: number
}
export interface KeywordShareLogsQuery {
type?: KeywordShareLogType
country?: string
page?: number
size?: number
}
/** 列表查询参数拼装:空值与「全部」不传,避免后端把空串当条件 */
export function buildKeywordShareListParams(query: KeywordShareListQuery): Record<string, unknown> {
const params: Record<string, unknown> = {
page: query.page ?? 1,
size: query.size ?? 200,
}
const text = (value?: string | null) => {
const trimmed = String(value ?? '').trim()
return trimmed ? trimmed : undefined
}
params.country = text(query.country)
params.category = text(query.category)
params.subCategory = text(query.subCategory)
params.categoryL3 = text(query.categoryL3)
params.categoryL4 = text(query.categoryL4)
params.search = text(query.search)
if (query.status && query.status !== 'all') {
params.status = query.status
}
if (query.usedDays && query.usedDays > 0) {
params.usedDays = query.usedDays
}
if (query.onlyMine) {
params.onlyMine = true
}
return params
}
export function fetchKeywordShareKeywords(query: KeywordShareListQuery) {
return unwrapJavaResponse(
get<JavaApiResponse<KeywordShareListVo>>(`${JAVA_API_PREFIX}/keyword-share/keywords`, {
params: buildKeywordShareListParams(query),
}),
)
}
export function fetchKeywordShareFilters() {
return unwrapJavaResponse(
get<JavaApiResponse<KeywordShareFiltersVo>>(`${JAVA_API_PREFIX}/keyword-share/filters`),
)
}
export function fetchKeywordShareStatsGrouped() {
return unwrapJavaResponse(
get<JavaApiResponse<KeywordShareStatsGroupedVo>>(`${JAVA_API_PREFIX}/keyword-share/stats-grouped`),
)
}
export function addKeywordShareKeywords(items: KeywordShareAddItem[]) {
return unwrapJavaResponse(
post<JavaApiResponse<KeywordShareAddVo>, { items: KeywordShareAddItem[] }>(
`${JAVA_API_PREFIX}/keyword-share/keywords`,
{ items },
),
)
}
export function deleteKeywordShareKeywords(ids: Array<number | string>) {
return unwrapJavaResponse(
del<JavaApiResponse<KeywordShareDeleteVo>>(
`${JAVA_API_PREFIX}/keyword-share/keywords`,
{ data: { ids } },
),
)
}
export interface KeywordShareUsageItem {
country: string
keyword: string
}
export function markKeywordShareUsage(items: KeywordShareUsageItem[]) {
return unwrapJavaResponse(
post<JavaApiResponse<KeywordShareMarkVo>, { items: KeywordShareUsageItem[] }>(
`${JAVA_API_PREFIX}/keyword-share/usage/mark`,
{ items },
),
)
}
export function unmarkKeywordShareUsage(items: KeywordShareUsageItem[]) {
return unwrapJavaResponse(
post<JavaApiResponse<KeywordShareUnmarkVo>, { items: KeywordShareUsageItem[] }>(
`${JAVA_API_PREFIX}/keyword-share/usage/unmark`,
{ items },
),
)
}
export function fetchKeywordShareLogs(query: KeywordShareLogsQuery) {
return unwrapJavaResponse(
get<JavaApiResponse<KeywordShareLogRawVo>>(`${JAVA_API_PREFIX}/keyword-share/logs`, {
params: {
type: query.type,
country: query.country || undefined,
page: query.page ?? 1,
size: query.size ?? 20,
},
}),
).then((raw) => mapKeywordShareLogs(raw, query.type))
}
export function fetchKeywordShareRandom(count = 10) {
return unwrapJavaResponse(
get<JavaApiResponse<KeywordShareRow[]>>(`${JAVA_API_PREFIX}/keyword-share/random`, {
params: { count },
}),
)
}
/** 后端 /stats-grouped 的四段分布(对齐桌面版词库统计弹窗:国家 / 一级 / 二级 / 三级) */
export interface KeywordShareStatsGroupedVo {
byCountry?: Array<{ name?: string | null; count?: number | string | null }> | null
byCategory?: Array<{ name?: string | null; count?: number | string | null }> | null
bySubCategory?: Array<{ category?: string | null; name?: string | null; count?: number | string | null }> | null
byCategoryL3?: Array<{
category?: string | null
subCategory?: string | null
name?: string | null
count?: number | string | null
}> | null
}
/** 弹窗一行:group 是所属上级(二级/三级段用),label 是本段名称 */
export interface KeywordStatsItem {
group: string
label: string
count: number
}
export interface KeywordStatsSections {
byCountry: KeywordStatsItem[]
byCategory: KeywordStatsItem[]
bySubCategory: KeywordStatsItem[]
byCategoryL3: KeywordStatsItem[]
}
function statsCount(value: unknown): number | null {
// Number(null) 与 Number('') 都是 0——缺计数的脏行必须判无效丢弃,不能冒充「0 个词」
if (value === null || value === undefined || value === '') return null
const n = Number(value)
return Number.isFinite(n) ? n : null
}
/**
* /stats-grouped → 四段分布。后端返回的是四份各自 GROUP BY 的清单(不是国家×类目交叉表),
* 缺段/脏行按空处理,弹窗对应段显示「暂无数据」而不是整窗报错。
*/
export function buildKeywordStatsSections(raw: unknown): KeywordStatsSections {
const source = (raw && typeof raw === 'object' ? raw : {}) as KeywordShareStatsGroupedVo
const flat = (
rows: Array<{ name?: string | null; count?: number | string | null }> | null | undefined,
groupOf: (row: { name?: string | null; count?: number | string | null }) => string,
): KeywordStatsItem[] =>
(Array.isArray(rows) ? rows : []).flatMap((row) => {
const label = String(row?.name ?? '').trim()
const count = statsCount(row?.count)
if (!label || count === null) return []
return [{ group: groupOf(row), label, count }]
})
return {
byCountry: flat(source.byCountry, () => ''),
byCategory: flat(source.byCategory, () => ''),
bySubCategory: flat(source.bySubCategory, (row) => String((row as { category?: string | null }).category ?? '').trim()),
byCategoryL3: flat(source.byCategoryL3, (row) => {
const item = row as { category?: string | null; subCategory?: string | null }
const category = String(item.category ?? '').trim()
const sub = String(item.subCategory ?? '').trim()
return [category, sub].filter(Boolean).join(' / ')
}),
}
}
/** 后端日志行字段名与展示口径不同(userName/time),映射到表格用的 operator/createdAt */
export interface KeywordShareLogRawRow {
id?: number | string
userName?: string | null
country?: string | null
keyword?: string | null
/** Jackson 默认 ISO-8601(2026-10-23T21:12:34),也可能带毫秒 */
time?: string | null
}
export interface KeywordShareLogRawVo {
total?: number | string
rows?: KeywordShareLogRawRow[] | null
}
/** ISO 时间 → 'YYYY-MM-DD HH:mm:ss';非 ISO 形态原样透出,空值给空串 */
export function formatLogTime(raw?: string | null): string {
const value = String(raw ?? '').trim()
if (!value) return ''
const matched = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/.exec(value)
return matched ? `${matched[1]} ${matched[2]}` : value
}
export function mapKeywordShareLogs(raw: unknown, type?: KeywordShareLogType): KeywordShareLogsVo {
const source = (raw && typeof raw === 'object' ? raw : {}) as KeywordShareLogRawVo
const rows = Array.isArray(source.rows) ? source.rows : []
return {
total: Number.isFinite(Number(source.total)) ? Number(source.total) : rows.length,
rows: rows.map((row) => ({
id: row?.id,
type,
country: row?.country ?? null,
keyword: row?.keyword ?? null,
operator: row?.userName ?? null,
createdAt: formatLogTime(row?.time),
})),
}
}
+2 -47
View File
@@ -11,9 +11,9 @@ import {
TOOL_MAP,
} from '../src/pages/amazon/tool-catalog.ts'
test('工具目录:23 个工具 id 唯一且每个都有图标与渐变配色', () => {
test('工具目录:20 个工具 id 唯一且每个都有图标与渐变配色', () => {
const ids = TOOL_GROUPS.flatMap((g) => g.tools.map((t) => t.id))
assert.equal(ids.length, 23, '工具总数应为 23(常用3 + 前端8 + 运营10 + 后勤2)')
assert.equal(ids.length, 20, '工具总数应为 20(前端8 + 运营10 + 后勤2)')
assert.equal(new Set(ids).size, ids.length, '工具 id 不应重复')
for (const id of ids) {
assert.ok(TOOL_ICON_SHAPES[id], `图标形状缺失: ${id}`)
@@ -22,51 +22,6 @@ test('工具目录:23 个工具 id 唯一且每个都有图标与渐变配色'
}
})
test('工具目录:常用工具分组排在最前且三个工具都有页面与权限键', () => {
const common = TOOL_GROUPS[0]
assert.equal(common.key, 'common', '常用工具组应在 TOOL_GROUPS 最前')
assert.equal(common.columnKey, 'brand_common_tools')
assert.equal(common.name, '常用工具')
assert.equal(common.desc, '换算 · 查询 · 词库共享,高频小工具')
assert.ok(common.color, '常用工具组应有主色')
assert.equal(common.workflow, undefined, '常用工具组没有标准工作流')
const byId = new Map(common.tools.map((tool) => [tool.id, tool]))
assert.deepEqual(
[...byId.keys()],
['pricing-calc', 'five-asin', 'keyword-share'],
'常用工具组的三个工具顺序固定',
)
assert.equal(byId.get('pricing-calc')?.href, '/pricing-calc')
assert.equal(byId.get('five-asin')?.href, '/five-asin')
assert.equal(byId.get('keyword-share')?.href, '/keyword-share')
assert.deepEqual(byId.get('pricing-calc')?.permissionKeys, ['pricing-calc'])
assert.deepEqual(byId.get('five-asin')?.permissionKeys, ['five-asin'])
assert.deepEqual(byId.get('keyword-share')?.permissionKeys, ['keyword-share'])
})
test('权限过滤:常用工具组整组 / 单工具键都按口径过滤', () => {
// 组键命中:整组保留且排在最前
const withCommon = filterGroupsByPermission(TOOL_GROUPS, ['brand_common_tools'])
const common = withCommon.find((group) => group.key === 'common')
assert.ok(common, '组键 brand_common_tools 命中时常用工具组应整组可见')
assert.deepEqual(common.tools.map((tool) => tool.id), ['pricing-calc', 'five-asin', 'keyword-share'])
// 只给单个工具权限键:常用组只留命中工具,不整组放行
const partial = filterGroupsByPermission(TOOL_GROUPS, ['pricing-calc', 'keyword-share'])
const partialCommon = partial.find((group) => group.key === 'common')
assert.ok(partialCommon, '有可见工具时常用组不应整体隐藏')
assert.deepEqual(partialCommon.tools.map((tool) => tool.id), ['pricing-calc', 'keyword-share'])
assert.equal(partialCommon.tools.some((tool) => tool.id === 'five-asin'), false, '无权限的 five-asin 不应混入')
// 无任何常用权限:常用组整体隐藏
const none = filterGroupsByPermission(TOOL_GROUPS, ['brand_front_tools'])
assert.equal(none.some((group) => group.key === 'common'), false, '无常用权限时常用组应隐藏')
// 无任何权限:全部隐藏
assert.equal(filterGroupsByPermission(TOOL_GROUPS, []).length, 0)
})
test('工具目录:无页面的工具应在 catalog 里标记为未开通(无 href)', () => {
const pending = TOOL_GROUPS.flatMap((g) => g.tools).filter((t) => !t.href)
const pendingIds = pending.map((t) => t.id).sort()
-48
View File
@@ -1,48 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
buildAmazonProductUrl,
FIVE_ASIN_COUNTRIES,
FIVE_ASIN_COUNTRY_MAP,
isValidAsin,
normalizeAsin,
} from '../src/pages/common/five-asin.ts'
test('五国站点常量:域名 / 邮编 / 城市与桌面版一致', () => {
assert.equal(FIVE_ASIN_COUNTRIES.length, 5)
const byCode = new Map(FIVE_ASIN_COUNTRIES.map((c) => [c.code, c]))
assert.deepEqual(byCode.get('uk'), {
code: 'uk', name: '英国', flag: '🇬🇧', domain: 'www.amazon.co.uk', postcode: 'SW1A 1AA', city: '伦敦', currency: '英镑',
})
assert.equal(byCode.get('de')?.postcode, '10115')
assert.equal(byCode.get('fr')?.postcode, '75001')
assert.equal(byCode.get('es')?.postcode, '28001')
assert.equal(byCode.get('it')?.postcode, '20121')
// 五国域名唯一且都带 https 之外的裸域名形状
assert.equal(new Set(FIVE_ASIN_COUNTRIES.map((c) => c.domain)).size, 5)
for (const country of FIVE_ASIN_COUNTRIES) {
assert.equal(FIVE_ASIN_COUNTRY_MAP.get(country.code), country, 'code→country 映射应完整')
}
})
test('ASIN 规范化:strip + 大写 + 去非字母数字', () => {
assert.equal(normalizeAsin(' b0c1234abc '), 'B0C1234ABC')
assert.equal(normalizeAsin('B0C-1234 abc'), 'B0C1234ABC')
assert.equal(normalizeAsin('asin/1234?5'), 'ASIN12345')
assert.equal(normalizeAsin(''), '')
})
test('ASIN 校验:规范化后必须恰好 10 位字母数字', () => {
assert.equal(isValidAsin('B0C1234ABC'), true)
assert.equal(isValidAsin(normalizeAsin(' b0c1234abc ')), true, '页面先规范化再校验,小写输入规范化后应合法')
assert.equal(isValidAsin('B0C1234AB'), false, '9 位应判不合法')
assert.equal(isValidAsin('B0C1234ABCD'), false, '11 位应判不合法')
assert.equal(isValidAsin(''), false)
assert.equal(isValidAsin('B0C1234AB!'), false, '非字母数字应判不合法')
})
test('商品页链接:https://{domain}/dp/{asin}', () => {
assert.equal(buildAmazonProductUrl('www.amazon.co.uk', 'B0C1234ABC'), 'https://www.amazon.co.uk/dp/B0C1234ABC')
assert.equal(buildAmazonProductUrl('www.amazon.de', 'B0C1234ABC'), 'https://www.amazon.de/dp/B0C1234ABC')
})
@@ -1,73 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
buildKeywordStatsSections,
formatLogTime,
mapKeywordShareLogs,
} from '../src/shared/api/types/modules/keyword-share.ts'
test('buildKeywordStatsSections:后端四段各自成段,二级/三级带上级分组', () => {
const sections = buildKeywordStatsSections({
byCountry: [{ name: '英国', count: 1200 }, { name: '德国', count: 800 }],
byCategory: [{ name: '3C', count: 900 }],
bySubCategory: [{ category: '3C', name: '充电器', count: 300 }],
byCategoryL3: [{ category: '3C', subCategory: '充电器', name: '无线充', count: 90 }],
})
assert.deepEqual(sections.byCountry, [
{ group: '', label: '英国', count: 1200 },
{ group: '', label: '德国', count: 800 },
])
assert.deepEqual(sections.byCategory, [{ group: '', label: '3C', count: 900 }])
assert.deepEqual(sections.bySubCategory, [{ group: '3C', label: '充电器', count: 300 }])
assert.deepEqual(sections.byCategoryL3, [{ group: '3C / 充电器', label: '无线充', count: 90 }])
})
test('buildKeywordStatsSections:缺段/脏行按空处理,不抛错(弹窗显示暂无数据)', () => {
const sections = buildKeywordStatsSections({
byCountry: [{ name: '', count: 5 }, { name: '法国', count: null }, { name: '西班牙', count: 7 }],
byCategory: null,
})
assert.deepEqual(sections.byCountry, [{ group: '', label: '西班牙', count: 7 }])
assert.deepEqual(sections.byCategory, [])
assert.deepEqual(sections.bySubCategory, [])
assert.deepEqual(sections.byCategoryL3, [])
assert.deepEqual(buildKeywordStatsSections(undefined).byCountry, [])
})
test('mapKeywordShareLogs:userName/time 映射到 operator/createdAt,ISO 时间转可读', () => {
const vo = mapKeywordShareLogs(
{
total: 2,
rows: [
{ id: 1, userName: '张三', country: '英国', keyword: 'wireless charger', time: '2026-10-23T21:12:34' },
{ id: 2, userName: '李四', country: '德国', keyword: 'usb c hub', time: '2026-10-22T09:00:01.000' },
],
},
'usage',
)
assert.equal(vo.total, 2)
assert.deepEqual(vo.rows[0], {
id: 1,
type: 'usage',
country: '英国',
keyword: 'wireless charger',
operator: '张三',
createdAt: '2026-10-23 21:12:34',
})
assert.equal(vo.rows[1]?.createdAt, '2026-10-22 09:00:01')
})
test('mapKeywordShareLogs:空返回与缺 total 时按行数兜底,不造出幽灵记录', () => {
assert.deepEqual(mapKeywordShareLogs(undefined), { total: 0, rows: [] })
const vo = mapKeywordShareLogs({ rows: [{ userName: '王五' }] })
assert.equal(vo.total, 1)
assert.equal(vo.rows[0]?.country, null)
assert.equal(vo.rows[0]?.createdAt, '')
})
test('formatLogTime:非 ISO 形态原样透出,空值给空串', () => {
assert.equal(formatLogTime('2026-10-23 21:12:34'), '2026-10-23 21:12:34')
assert.equal(formatLogTime('刚刚'), '刚刚')
assert.equal(formatLogTime(null), '')
})
@@ -1,153 +0,0 @@
/**
* 常用工具两页的挂载冒烟测试(tests/mount/** 由 vitest 收)。
*
* 页面壳(AmazonToolPageShell→AmazonTopBar)依赖权限接口与路由,这里整体桩掉,
* 只验页面本体的行为:换算数值、站点切换清空、资料下载/常用链接出口、ASIN 校验与链接拼装。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import PricingCalcPage from '@/pages/common/PricingCalcPage.vue'
import FiveAsinPage from '@/pages/common/FiveAsinPage.vue'
vi.mock('@/shared/api/permission', () => ({
getCurrentUserAppColumnKeys: vi.fn().mockResolvedValue([]),
}))
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
const STUBS = {
RouterLink: true,
'router-link': true,
AmazonTopBar: true,
NotificationBell: true,
BrandApiSecretSettingsButton: true,
DownloadProgressPanel: true,
AmazonFooterBar: true,
}
let wrapper: VueWrapper | null = null
function mountPage(component: object) {
wrapper = mount(component, {
global: { plugins: [ElementPlus], stubs: STUBS },
})
return wrapper
}
function findButtonByText(text: RegExp) {
return (wrapper?.findAll('button') ?? []).find((b) => text.test(b.text()))
}
async function setInput(index: number, value: string) {
const input = wrapper?.findAll('input')[index]
expect(input, `第 ${index} 个输入框不存在`).toBeTruthy()
await input!.setValue(value)
}
describe('定价利润换算页', () => {
beforeEach(() => {
if (!(globalThis as Record<string, unknown>).ResizeObserver) {
;(globalThis as Record<string, unknown>).ResizeObserver = ResizeObserverStub
}
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
it('买货价 10 + 运费 5(英国)→ 营业额 30.00 / 利润 9.00 / 利润率 30.0% / 汇率 3.3333', async () => {
const page = mountPage(PricingCalcPage)
await setInput(0, '10')
await setInput(1, '5')
findButtonByText(/^换算利润$/).trigger('click')
await flushPromises()
const values = page.findAll('.result-value').map((n) => n.text())
expect(values).toEqual(['30.00', '9.00', '30.0%', '3.3333'])
})
it('切到德国·法国:除数 8 生效,且切换站点清空已有结果', async () => {
const page = mountPage(PricingCalcPage)
await setInput(0, '10')
await setInput(1, '5')
findButtonByText(/^换算利润$/).trigger('click')
await flushPromises()
expect(page.findAll('.result-value').length).toBe(4)
findButtonByText(/德国·法国/).trigger('click')
await flushPromises()
expect(page.find('.result-empty').exists()).toBe(true)
findButtonByText(/^换算利润$/).trigger('click')
await flushPromises()
expect(page.findAll('.result-value')[3]?.text()).toBe('3.7500')
})
it('资料下载四个锚点落在 /static/ 且 href 无裸空格;常用链接均为 http(s)', async () => {
const page = mountPage(PricingCalcPage)
const downloadHrefs = page
.findAll('a[download]')
.map((a) => a.attributes('href') ?? '')
expect(downloadHrefs).toHaveLength(4)
for (const href of downloadHrefs) {
expect(href.startsWith('/static/')).toBe(true)
expect(href.includes(' ')).toBe(false)
}
const linkHrefs = page
.findAll('.resource-block')
.filter((block) => block.text().includes('常用链接'))
.flatMap((block) => block.findAll('a').map((a) => a.attributes('href') ?? ''))
expect(linkHrefs.length).toBeGreaterThanOrEqual(5)
for (const href of linkHrefs) {
expect(/^https?:\/\//.test(href)).toBe(true)
}
})
})
describe('五国ASIN快速查询页', () => {
beforeEach(() => {
if (!(globalThis as Record<string, unknown>).ResizeObserver) {
;(globalThis as Record<string, unknown>).ResizeObserver = ResizeObserverStub
}
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
it('五个国家可选,小写输入规范化后拼出 amazon.co.uk 商品链接', async () => {
const page = mountPage(FiveAsinPage)
expect(page.findAll('.country-btn')).toHaveLength(5)
await setInput(0, ' b0c1234abc ')
await flushPromises()
const link = page.find('.link-url')
expect(link.attributes('href')).toBe('https://www.amazon.co.uk/dp/B0C1234ABC')
expect(link.text()).toBe('https://www.amazon.co.uk/dp/B0C1234ABC')
})
it('切到德国后链接域名随国家走', async () => {
const page = mountPage(FiveAsinPage)
page.findAll('.country-btn')[1].trigger('click')
await setInput(0, 'B012345678')
await flushPromises()
expect(page.find('.link-url').attributes('href')).toBe('https://www.amazon.de/dp/B012345678')
expect(page.find('.postcode-value').text()).toBe('10115')
})
it('不足 10 位给中文报错并禁用「打开商品页」', async () => {
const page = mountPage(FiveAsinPage)
await setInput(0, 'B0123')
await flushPromises()
expect(page.find('.asin-error').text()).toContain('10')
expect(findButtonByText(/^打开商品页$/).attributes('disabled')).toBeDefined()
})
})
@@ -1,160 +0,0 @@
/**
* 五国关键词共享页挂载用例(2026-10-21 常用工具网页化)。
*
* 两件事都要判,缺一条就是假绿:
* ① 首屏真实走 API:列表行、统计卡都来自 /keywords 返回,页面不得自带假数据;
* ② 行内「标记已使用」真实打到 POST /usage/mark,且载荷是 country+keyword、
* 成功后重拉列表(防"点了没反应")。
*
* 跑法:cd frontend-vue && npx vitest run tests/mount/keyword-share-page.mount.test.ts
* (tests/mount/** 由 vitest.config.ts 收,node --test 的 glob 抓不到这里。)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import KeywordSharePage from '@/pages/common/KeywordSharePage.vue'
// API 层整模块 mock:纯函数(buildKeywordStatsSections / mapKeywordShareLogs)保留真实现,
// 网络函数按用例给桩。页面经 shared/api/types/modules/keyword-share 调用。
const api = vi.hoisted(() => ({
fetchKeywordShareFilters: vi.fn(),
fetchKeywordShareKeywords: vi.fn(),
fetchKeywordShareStatsGrouped: vi.fn(),
addKeywordShareKeywords: vi.fn(),
deleteKeywordShareKeywords: vi.fn(),
markKeywordShareUsage: vi.fn(),
unmarkKeywordShareUsage: vi.fn(),
fetchKeywordShareLogs: vi.fn(),
fetchKeywordShareRandom: vi.fn(),
}))
vi.mock('@/shared/api/types/modules/keyword-share', async (importOriginal) => ({
...(await importOriginal<typeof import('@/shared/api/types/modules/keyword-share')>()),
...api,
}))
vi.mock('@/shared/api/permission', () => ({
getCurrentUserAppColumnKeys: vi.fn().mockResolvedValue([]),
}))
const ROWS = [
{
id: 1,
country: '英国',
keyword: 'wireless charger',
chinese: '无线充电器',
category: '电子',
subCategory: '配件',
categoryL3: '充电',
categoryL4: '无线充',
used: false,
usedTime: null,
usedUser: null,
},
{
id: 2,
country: '德国',
keyword: 'handtuch wärmer',
chinese: '毛巾架',
category: '家居',
subCategory: '浴室',
categoryL3: '毛巾架',
categoryL4: '加热',
used: true,
usedTime: '2026-10-20 10:00:00',
usedUser: '张三',
},
]
const LIST_VO = {
total: 2,
rows: ROWS,
stats: { hit: 2, used: 1, unused: 1, dup: 0 },
}
// happy-dom 没有ResizeObserver 时 el-table 会挂不上,补一个最小桩
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
let wrapper: VueWrapper | null = null
async function mountPage() {
wrapper = mount(KeywordSharePage, {
global: {
plugins: [ElementPlus],
stubs: {
RouterLink: true,
'router-link': true,
NotificationBell: true,
BrandApiSecretSettingsButton: true,
DownloadProgressPanel: true,
AmazonFooterBar: true,
},
},
})
await flushPromises()
await flushPromises()
return wrapper
}
function findButtonByText(text: string) {
const buttons = wrapper?.findAll('button') ?? []
return buttons.find((button) => button.text().trim() === text)
}
describe('五国关键词共享页', () => {
beforeEach(() => {
if (!(globalThis as Record<string, unknown>).ResizeObserver) {
;(globalThis as Record<string, unknown>).ResizeObserver = ResizeObserverStub
}
api.fetchKeywordShareFilters.mockResolvedValue({ countries: ['英国', '德国'], categories: [] })
api.fetchKeywordShareKeywords.mockResolvedValue(LIST_VO)
api.markKeywordShareUsage.mockResolvedValue({ marked: 1 })
api.unmarkKeywordShareUsage.mockResolvedValue({ unmarked: 1 })
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
vi.clearAllMocks()
})
it('首屏渲染 API 返回的关键词行与统计卡(无假数据)', async () => {
const w = await mountPage()
expect(api.fetchKeywordShareKeywords).toHaveBeenCalledTimes(1)
const text = w.text()
expect(text, '行数据来自 /keywords 返回').toContain('wireless charger')
expect(text).toContain('handtuch wärmer')
expect(text).toContain('✓已使用·2026-10-20 10:00:00·张三')
expect(text).toContain('未使用')
// 统计卡四格来自返回的 stats
expect(text).toContain('命中总数')
expect(w.findAll('.stat-card .stat-value').map((node) => node.text())).toEqual(['2', '1', '1', '0'])
})
it('行内「标记已使用」打到 POST /usage/mark(country+keyword 载荷)并重拉列表', async () => {
await mountPage()
expect(api.markKeywordShareUsage).not.toHaveBeenCalled()
const markBtn = findButtonByText('标记已使用')
expect(markBtn, '未使用行应显示「标记已使用」').toBeTruthy()
await markBtn!.trigger('click')
await flushPromises()
expect(api.markKeywordShareUsage).toHaveBeenCalledTimes(1)
expect(api.markKeywordShareUsage).toHaveBeenCalledWith([{ country: '英国', keyword: 'wireless charger' }])
expect(api.fetchKeywordShareKeywords, '标记成功后应重拉列表').toHaveBeenCalledTimes(2)
})
it('已使用行的行内按钮是「标记未使用」,点击走 POST /usage/unmark', async () => {
await mountPage()
const unmarkBtn = findButtonByText('标记未使用')
expect(unmarkBtn, '已使用行应显示「标记未使用」').toBeTruthy()
await unmarkBtn!.trigger('click')
await flushPromises()
expect(api.unmarkKeywordShareUsage).toHaveBeenCalledWith([{ country: '德国', keyword: 'handtuch wärmer' }])
expect(api.markKeywordShareUsage).not.toHaveBeenCalled()
})
})
-84
View File
@@ -1,84 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
calcPricing,
formatExchangeRate,
formatMoney,
formatProfitRate,
parseMoneyInput,
PRICING_STATIONS,
PRICING_STATION_MAP,
} from '../src/pages/common/pricing-calc.ts'
test('站点配置:英国 GBP 除数 9,德国·法国 EUR 除数 8', () => {
assert.deepEqual(PRICING_STATIONS.map((s) => s.key), ['uk', 'eu'])
assert.equal(PRICING_STATION_MAP.get('uk')?.currency, 'GBP')
assert.equal(PRICING_STATION_MAP.get('uk')?.divisor, 9)
assert.equal(PRICING_STATION_MAP.get('eu')?.currency, 'EUR')
assert.equal(PRICING_STATION_MAP.get('eu')?.divisor, 8)
})
test('金额解析:剥离 ¥/¥/千分位逗号/空白后 parseFloat', () => {
assert.equal(parseMoneyInput('25'), 25)
assert.equal(parseMoneyInput('¥1,280'), 1280)
assert.equal(parseMoneyInput('¥3.5'), 3.5)
assert.equal(parseMoneyInput(' 1,234.56 '), 1234.56)
assert.equal(parseMoneyInput('0'), 0)
assert.ok(parseMoneyInput('0.001') !== null)
})
test('金额解析:空串、非数字、负数一律判非法(返回 null)', () => {
assert.equal(parseMoneyInput(''), null)
assert.equal(parseMoneyInput(' '), null)
assert.equal(parseMoneyInput('abc'), null)
assert.equal(parseMoneyInput('12abc'), null)
assert.equal(parseMoneyInput('-5'), null)
assert.equal(parseMoneyInput('¥-5'), null)
})
test('计算口径:英国站逐项对上桌面版公式', () => {
const uk = PRICING_STATION_MAP.get('uk')
assert.ok(uk)
// 成本=100+10=110;营业额=110/0.5=220;平台费=44;利润=66;利润率=0.3;换算=220/9
const result = calcPricing(100, 10, uk)
assert.equal(result.cost, 110)
assert.equal(result.revenue, 220)
assert.equal(result.platformFee, 44)
assert.equal(result.profit, 66)
assert.ok(Math.abs(result.profitRate - 0.3) < 1e-12)
assert.ok(Math.abs(result.converted - 220 / 9) < 1e-12)
})
test('计算口径:德国·法国站按除数 8 反推', () => {
const eu = PRICING_STATION_MAP.get('eu')
assert.ok(eu)
const result = calcPricing(80, 0, eu)
assert.equal(result.cost, 80)
assert.equal(result.revenue, 160)
assert.equal(result.platformFee, 32)
assert.equal(result.profit, 48)
assert.equal(result.converted, 20)
})
test('计算边界:买货价与运费都为 0 时结果全 0,利润率不出现 NaN', () => {
const uk = PRICING_STATION_MAP.get('uk')
assert.ok(uk)
const result = calcPricing(0, 0, uk)
assert.equal(result.cost, 0)
assert.equal(result.revenue, 0)
assert.equal(result.platformFee, 0)
assert.equal(result.profit, 0)
assert.equal(result.profitRate, 0, '营业额为 0 时利润率应记 0 而不是 NaN')
assert.equal(result.converted, 0)
})
test('展示格式:金额千分位 2 位 / 利润率 1 位百分比 / 汇率 4 位小数', () => {
assert.equal(formatMoney(220), '220.00')
assert.equal(formatMoney(1234567.891), '1,234,567.89')
assert.equal(formatMoney(0), '0.00')
assert.equal(formatProfitRate(0.3), '30.0%')
assert.equal(formatProfitRate(0), '0.0%')
assert.equal(formatExchangeRate(220 / 9), (220 / 9).toFixed(4))
assert.equal(formatExchangeRate(20), '20.0000')
})
@@ -1,58 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join, resolve } from 'node:path'
import {
downloadHref,
PRICING_COMMON_LINKS,
PRICING_DOWNLOADS,
} from '../src/pages/amazon/pricing-resources.ts'
const here = dirname(fileURLToPath(import.meta.url))
const ROOT = resolve(here, '..')
test('downloadHref:落在 /static/ 下,空格与非 ASCII 都按 encodeURI 转义', () => {
assert.equal(downloadHref('百分30利润表格.xlsx'), `/static/${encodeURI('百分30利润表格.xlsx')}`)
assert.equal(
downloadHref('设置最低价ASIN 批量文档格式.xlsx'),
'/static/%E8%AE%BE%E7%BD%AE%E6%9C%80%E4%BD%8E%E4%BB%B7ASIN%20%E6%89%B9%E9%87%8F%E6%96%87%E6%A1%A3%E6%A0%BC%E5%BC%8F.xlsx',
)
// 不允许出现裸空格(浏览器会容忍,但 href 里必须是编码后的形态)
for (const item of PRICING_DOWNLOADS) {
assert.ok(!downloadHref(item.file).includes(' '), `${item.file} 的 href 含裸空格`)
}
})
test('资料下载清单与 public/materials/ 实际文件一一对应(少一个下载就 404)', () => {
const dir = join(ROOT, 'public', 'materials')
const onDisk = readdirSync(dir)
assert.ok(onDisk.length >= PRICING_DOWNLOADS.length, 'public/materials 里的文件比清单还少')
for (const item of PRICING_DOWNLOADS) {
assert.ok(onDisk.includes(item.file), `public/materials/ 缺少清单文件:${item.file}`)
}
})
test('常用链接清单:名称/地址非空、http(s) 协议、无重复', () => {
assert.ok(PRICING_COMMON_LINKS.length >= 5, `常用链接只有 ${PRICING_COMMON_LINKS.length} 条,桌面版清单不止这些`)
const names = new Set<string>()
const urls = new Set<string>()
for (const link of PRICING_COMMON_LINKS) {
assert.ok(link.name.trim(), '存在空名称的常用链接')
assert.match(link.url, /^https?:\/\//, `${link.name} 的地址不是 http(s):${link.url}`)
assert.ok(!names.has(link.name), `链接名称重复:${link.name}`)
assert.ok(!urls.has(link.url), `链接地址重复:${link.url}`)
names.add(link.name)
urls.add(link.url)
}
})
test('下载清单:名称与文件字段成对、无重复文件', () => {
const files = new Set<string>()
for (const item of PRICING_DOWNLOADS) {
assert.ok(item.name.trim() && item.file.trim(), '存在空的名称或文件名')
assert.ok(!files.has(item.file), `下载文件重复:${item.file}`)
files.add(item.file)
}
})