feat(jd-collect): 店内分类同步结果本机缓存,页面重开直接回填(客户口径「同步后就记住呀 别每次都同步」)
店内分类只能靠客户端起 Chrome 现拉(一次十几秒),页面每次重开都空着逼用户再点一次同步是白成本。新增 pages/jd/jd-category-cache.ts(零依赖纯逻辑):同步成功后把 shopName/shopId/categories/fetchedAt 落 localStorage(键 jd_shop_category_cache_v1),页面挂载即回填选项集,说明行标注「X 同步,点同步分类可刷新」。只回填选项集、不回填选中值——选中值决定这一单采哪些分类,跨次沿用它等于静默改采集范围。「同步分类」仍走现拉并覆盖缓存(商家在京麦改了分类可刷回来)。脏 JSON/空分类/配额失败一律读成 null 或静默跳过,不拿半张表填下拉。 判据:新 tests/jd-category-cache.test.ts 6 支(原样读回/脏 JSON 与空分类读 null/脏条目与重复 id 过滤/storage 不可用不抛/清缓存/预选值按现有 id 裁剪);jd-collect-tab/jd-console 既有 19 支全绿;vue-tsc --noEmit rc=0。
This commit is contained in:
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/shared/api/types/modules/jd-collect'
|
||||
import { retryClientTask } from '@/shared/api/task-retry'
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { loadCategoryCache, saveCategoryCache } from './jd-category-cache'
|
||||
import { resolvePageHref } from '@/shared/page-prefix'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
@@ -75,6 +76,28 @@ const syncingCategories = ref(false)
|
||||
const canSyncCategories = ref(false)
|
||||
/** 最近一次同步到的店铺名(空=尚未同步或京麦页面没返回店铺名)。 */
|
||||
const syncedShopName = ref('')
|
||||
/** 本页选项集来自上次缓存的时间(空=本次没回填缓存;只作提示,不参与建单)。 */
|
||||
const cachedFetchedAt = ref('')
|
||||
|
||||
/** localStorage 访问包一层:隐私模式/配额异常时退回「不缓存」,不影响建单。 */
|
||||
function localStore(): Storage | null {
|
||||
try {
|
||||
return window.localStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 挂载即回填上次成功同步的选项集(2026-11-19 客户口径「同步后就记住呀 别每次都同步」)。
|
||||
* 只回填**选项集**,不回填选中值——选中值是「这一单采哪些分类」,跨次沿用它等于
|
||||
* 静默改采集范围;要刷新就点「同步分类」,现拉会覆盖缓存。 */
|
||||
function restoreCategoryCache() {
|
||||
const cache = loadCategoryCache(localStore())
|
||||
if (!cache) return
|
||||
shopCategoryOptions.value = cache.categories
|
||||
syncedShopName.value = cache.shopName
|
||||
cachedFetchedAt.value = cache.fetchedAt
|
||||
}
|
||||
|
||||
/** 无桥(浏览器打开)或老客户端(桥没有该方法)时点同步的提示。 */
|
||||
const SYNC_UNAVAILABLE_NOTE =
|
||||
@@ -88,7 +111,10 @@ function refreshSyncAvailability() {
|
||||
const categoryHint = computed(() => {
|
||||
const parts: string[] = []
|
||||
if (syncedShopName.value) {
|
||||
parts.push(`已同步店铺「${syncedShopName.value}」:${shopCategoryOptions.value.length} 个分类`)
|
||||
const suffix = cachedFetchedAt.value
|
||||
? `(${formatDateTime(cachedFetchedAt.value)} 同步,点「同步分类」可刷新)`
|
||||
: ''
|
||||
parts.push(`已同步店铺「${syncedShopName.value}」:${shopCategoryOptions.value.length} 个分类${suffix}`)
|
||||
} else {
|
||||
parts.push('分类来自本机客户端已登录的京麦店铺,点「同步分类」拉取;未同步或空选=全店采集')
|
||||
}
|
||||
@@ -124,6 +150,13 @@ async function syncShopCategories() {
|
||||
selectedShopCategoryValues.value.filter((value) => optionIds.has(value))
|
||||
shopCategoryOptions.value = options
|
||||
syncedShopName.value = result.shopName || ''
|
||||
cachedFetchedAt.value = ''
|
||||
saveCategoryCache(localStore(), {
|
||||
shopName: syncedShopName.value,
|
||||
shopId: String(result.shopId || ''),
|
||||
categories: options,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
})
|
||||
if (staleCount > 0) {
|
||||
noticeMessage.value = `已按当前店铺刷新分类,清除了 ${staleCount} 个不属于当前店铺的已选项`
|
||||
}
|
||||
@@ -453,6 +486,8 @@ onMounted(async () => {
|
||||
board.loadPollingIds()
|
||||
// 同步按钮可用性:桥晚到(pywebviewready 在挂载之后)也要能翻成可用。
|
||||
refreshSyncAvailability()
|
||||
// 上次成功同步的分类直接回填:分类是现拉(起 Chrome 十几秒),不该每次重开都空着。
|
||||
restoreCategoryCache()
|
||||
window.addEventListener('pywebviewready', refreshSyncAvailability)
|
||||
await Promise.all([
|
||||
board.loadDashboard().catch(() => undefined),
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 京东采集「店内分类」的本机缓存(2026-11-19 客户口径「同步后就记住呀 别每次都同步」)。
|
||||
*
|
||||
* 分类只能靠客户端起 Chrome 现拉(`get_jd_shop_categories` → shop_categories.py),
|
||||
* 一次十几秒;页面每次重开都空着、逼用户再点一次「同步分类」是没必要的成本。
|
||||
* 这里把**上一次成功同步**的选项集连同店铺名/时间落在 localStorage,页面挂载即回填;
|
||||
* 「同步分类」按钮仍是现拉并覆盖缓存,所以商家在京麦改了分类也能刷回来。
|
||||
*
|
||||
* 刻意不 import 任何 Vue/桥模块(纯逻辑,`node --test` 可直测)。
|
||||
*/
|
||||
|
||||
export interface ShopCategoryOption {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface JdCategoryCache {
|
||||
/** 同步时的店铺名(空=京麦页面没回店铺名,不影响分类可用) */
|
||||
shopName: string
|
||||
shopId: string
|
||||
categories: ShopCategoryOption[]
|
||||
/** ISO 时间串;展示与「多久前同步」都读它 */
|
||||
fetchedAt: string
|
||||
}
|
||||
|
||||
/** localStorage 键:带版本号,形状变更时换版本而不是硬读旧值。 */
|
||||
export const JD_CATEGORY_CACHE_KEY = 'jd_shop_category_cache_v1'
|
||||
|
||||
interface StorageLike {
|
||||
getItem(key: string): string | null
|
||||
setItem(key: string, value: string): void
|
||||
removeItem(key: string): void
|
||||
}
|
||||
|
||||
function normalizeCategories(raw: unknown): ShopCategoryOption[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: ShopCategoryOption[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const label = String((item as ShopCategoryOption).label || '').trim()
|
||||
const value = String((item as ShopCategoryOption).value || '').trim()
|
||||
if (!label || !value || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push({ label, value })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 读缓存;没有、损坏、形状不对都返回 null(宁可空着也不让页面拿到半张表)。 */
|
||||
export function loadCategoryCache(storage: StorageLike | null): JdCategoryCache | null {
|
||||
if (!storage) return null
|
||||
let raw: string | null = null
|
||||
try {
|
||||
raw = storage.getItem(JD_CATEGORY_CACHE_KEY)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!raw) return null
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object') return null
|
||||
const data = parsed as Partial<JdCategoryCache>
|
||||
const categories = normalizeCategories(data.categories)
|
||||
if (!categories.length) return null
|
||||
return {
|
||||
shopName: String(data.shopName || '').trim(),
|
||||
shopId: String(data.shopId || '').trim(),
|
||||
categories,
|
||||
fetchedAt: String(data.fetchedAt || ''),
|
||||
}
|
||||
}
|
||||
|
||||
/** 写缓存;返回是否落盘成功(配额/隐私模式失败只影响「下次要重同步」,不阻断本次使用)。 */
|
||||
export function saveCategoryCache(storage: StorageLike | null, cache: JdCategoryCache): boolean {
|
||||
if (!storage) return false
|
||||
const categories = normalizeCategories(cache.categories)
|
||||
if (!categories.length) return false
|
||||
const payload: JdCategoryCache = {
|
||||
shopName: String(cache.shopName || '').trim(),
|
||||
shopId: String(cache.shopId || '').trim(),
|
||||
categories,
|
||||
fetchedAt: cache.fetchedAt || new Date().toISOString(),
|
||||
}
|
||||
try {
|
||||
storage.setItem(JD_CATEGORY_CACHE_KEY, JSON.stringify(payload))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 清缓存(当前没有调用方;留给「换店/换号」这类显式失效场景)。 */
|
||||
export function clearCategoryCache(storage: StorageLike | null): void {
|
||||
if (!storage) return
|
||||
try {
|
||||
storage.removeItem(JD_CATEGORY_CACHE_KEY)
|
||||
} catch {
|
||||
/* 清不掉不影响功能:下一次成功同步会覆盖 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 预选值只保留缓存里还存在的 id(id 是店铺自有,换店后旧 id 必须丢)。 */
|
||||
export function pruneSelectedCategoryValues(
|
||||
selected: string[],
|
||||
categories: ShopCategoryOption[],
|
||||
): string[] {
|
||||
const allowed = new Set(categories.map((item) => item.value))
|
||||
return selected.filter((value) => allowed.has(value))
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
JD_CATEGORY_CACHE_KEY,
|
||||
clearCategoryCache,
|
||||
loadCategoryCache,
|
||||
pruneSelectedCategoryValues,
|
||||
saveCategoryCache,
|
||||
} from '../src/pages/jd/jd-category-cache.ts'
|
||||
|
||||
/** 2026-11-19 客户口径「同步后就记住呀 别每次都同步」:
|
||||
* 店内分类现拉要起 Chrome 十几秒,页面重开后应当直接回填上次结果。 */
|
||||
|
||||
function memoryStorage(initial: Record<string, string> = {}) {
|
||||
const data = { ...initial }
|
||||
return {
|
||||
data,
|
||||
getItem: (key: string) => (key in data ? data[key] : null),
|
||||
setItem: (key: string, value: string) => {
|
||||
data[key] = value
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
delete data[key]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('保存后能原样读回(含店铺名与时间)', () => {
|
||||
const storage = memoryStorage()
|
||||
const categories = [
|
||||
{ label: '服饰内衣', value: '1024347001' },
|
||||
{ label: '其他', value: '1024347575' },
|
||||
]
|
||||
assert.equal(saveCategoryCache(storage, {
|
||||
shopName: '花屿巷旗舰店', shopId: '165515933', categories, fetchedAt: '2026-11-19T13:31:00.000Z',
|
||||
}), true)
|
||||
|
||||
const cache = loadCategoryCache(storage)
|
||||
assert.ok(cache)
|
||||
assert.equal(cache?.shopName, '花屿巷旗舰店')
|
||||
assert.equal(cache?.shopId, '165515933')
|
||||
assert.deepEqual(cache?.categories, categories)
|
||||
assert.equal(cache?.fetchedAt, '2026-11-19T13:31:00.000Z')
|
||||
})
|
||||
|
||||
test('没有缓存、脏 JSON、空分类都读成 null(不拿半张表去填下拉)', () => {
|
||||
assert.equal(loadCategoryCache(memoryStorage()), null)
|
||||
assert.equal(loadCategoryCache(memoryStorage({ [JD_CATEGORY_CACHE_KEY]: '{not json' })), null)
|
||||
assert.equal(loadCategoryCache(memoryStorage({ [JD_CATEGORY_CACHE_KEY]: '[]' })), null)
|
||||
assert.equal(loadCategoryCache(memoryStorage({
|
||||
[JD_CATEGORY_CACHE_KEY]: JSON.stringify({ categories: [] }),
|
||||
})), null)
|
||||
assert.equal(loadCategoryCache(null), null)
|
||||
})
|
||||
|
||||
test('脏条目被过滤、重复 id 只留第一条', () => {
|
||||
const storage = memoryStorage({
|
||||
[JD_CATEGORY_CACHE_KEY]: JSON.stringify({
|
||||
shopName: 'A',
|
||||
categories: [
|
||||
{ label: '其他', value: '1024347575' },
|
||||
{ label: '其他', value: '1024347575' },
|
||||
{ label: '', value: 'x' },
|
||||
{ label: '缺 id' },
|
||||
null,
|
||||
{ label: '女装', value: '1024347001' },
|
||||
],
|
||||
}),
|
||||
})
|
||||
const cache = loadCategoryCache(storage)
|
||||
assert.deepEqual(cache?.categories, [
|
||||
{ label: '其他', value: '1024347575' },
|
||||
{ label: '女装', value: '1024347001' },
|
||||
])
|
||||
})
|
||||
|
||||
test('storage 不可用(隐私模式/配额)只影响缓存,不抛异常', () => {
|
||||
const broken = {
|
||||
getItem: () => {
|
||||
throw new Error('denied')
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('denied')
|
||||
},
|
||||
removeItem: () => {
|
||||
throw new Error('denied')
|
||||
},
|
||||
}
|
||||
assert.equal(loadCategoryCache(broken), null)
|
||||
assert.equal(saveCategoryCache(broken, {
|
||||
shopName: 'A', shopId: '', categories: [{ label: '其他', value: '1' }], fetchedAt: '',
|
||||
}), false)
|
||||
assert.doesNotThrow(() => clearCategoryCache(broken))
|
||||
})
|
||||
|
||||
test('清缓存后读不到', () => {
|
||||
const storage = memoryStorage()
|
||||
saveCategoryCache(storage, {
|
||||
shopName: 'A', shopId: '', categories: [{ label: '其他', value: '1' }], fetchedAt: '',
|
||||
})
|
||||
assert.ok(loadCategoryCache(storage))
|
||||
clearCategoryCache(storage)
|
||||
assert.equal(loadCategoryCache(storage), null)
|
||||
})
|
||||
|
||||
test('预选值只保留缓存里还存在的 id(换店后旧 id 必须丢)', () => {
|
||||
const categories = [{ label: '其他', value: '1024347575' }]
|
||||
assert.deepEqual(pruneSelectedCategoryValues(['1024347575', '999'], categories), ['1024347575'])
|
||||
assert.deepEqual(pruneSelectedCategoryValues([], categories), [])
|
||||
})
|
||||
Reference in New Issue
Block a user