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
+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)
}
})