diff --git a/README.en.md b/README.en.md index fa7d42b..b4dd46c 100644 --- a/README.en.md +++ b/README.en.md @@ -37,11 +37,13 @@ Uploads become WebP images with a maximum long edge of 1920 pixels, without enla Items are sorted by latest update by default. +New items reuse the most recently added item's category, locations, brand, style and variant settings in the current area. Enter a new name, barcode, tags and photos; the private checkbox is not carried over. + The background moves subtly as you scroll, and item cards slide into view on their first entrance. The first screen appears immediately. Both effects respect the system's reduced-motion preference. The first visit downloads the interface. If a module fails to load after login, the page reloads once to fetch the current application; if it fails again, use Reload to try again. -Click the app name at the top-left to unlock the private area. Locking or refreshing hides it again. +Click the app name at the top-left to unlock the private area and show only private items. Click it again to return to ordinary items. Refreshing hides the private area again. ## Development diff --git a/README.md b/README.md index 6595fcd..53341a3 100644 --- a/README.md +++ b/README.md @@ -37,11 +37,13 @@ docker compose up -d 物品默认按最近更新排列。 +新增物品沿用当前区域最近新增物品的分类、位置、品牌、款式及规格设置;名称、条码、标签、图片和隐私勾选重新填写。 + 滚动时背景轻微视差移动,物品卡片首次滚入视野时滑入显示。首屏内容直接显示,系统开启“减少动态效果”时关闭这两种动效。 首次打开会下载界面程序。若文件加载失败,登录后会自动重新加载最新页面一次;仍失败可点击“重新加载”重试。 -点击左上角“物品管理”输入隐私区密码;解锁后可设置隐私物品、分类和位置;物品的隐私开关位于“标签”右侧。锁定或刷新后重新隐藏。 +点击左上角“物品管理”输入隐私区密码;解锁后只显示隐私物品,也可设置隐私物品、分类和位置;物品的隐私开关位于“标签”右侧。再次点击收起,恢复普通物品;刷新后重新隐藏。 ## 开发 diff --git a/desktop/package.json b/desktop/package.json index c3df079..c96ae07 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@itemmanager/desktop", - "version": "26.8.0", + "version": "26.9.0", "private": true, "description": "物品管理桌面客户端", "author": "MCJ", diff --git a/package.json b/package.json index 14fcb0f..0e7dcfa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "itemmanager-workspace", - "version": "26.8.0", + "version": "26.9.0", "private": true, "license": "MIT", "packageManager": "pnpm@11.7.0", diff --git a/web/package.json b/web/package.json index fa933a8..0992de1 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@itemmanager/web", - "version": "26.8.0", + "version": "26.9.0", "private": true, "license": "MIT", "packageManager": "pnpm@11.7.0", diff --git a/web/src/renderer/features/items/ItemEditorModal.jsx b/web/src/renderer/features/items/ItemEditorModal.jsx index 40538c6..b59f2e1 100644 --- a/web/src/renderer/features/items/ItemEditorModal.jsx +++ b/web/src/renderer/features/items/ItemEditorModal.jsx @@ -30,7 +30,7 @@ function createVariantRow(row = { color: '', size: '', isPackaged: false }) { return { ...row, rowKey: ++variantRowSequence }; } -function normalizeItem(item, categories, locations, mode = 'edit') { +function normalizeItem(item, categories, locations, mode = 'edit', defaultsFromItem = null) { if (item) { return { ...(mode === 'copy' ? {} : { id: item.id }), @@ -53,8 +53,9 @@ function normalizeItem(item, categories, locations, mode = 'edit') { }; } - const empty = createEmptyItemDraft(categories, locations); - return { ...empty, imagePaths: [], imagePath: '', variants: getItemVariants(empty).map(createVariantRow), locationIds: [empty.locationId || ''], isPrivate: false }; + const empty = createEmptyItemDraft(categories, locations, mode === 'create' ? defaultsFromItem : null); + const locationIds = getItemLocationIds(empty); + return { ...empty, imagePaths: [], imagePath: '', variants: getItemVariants(empty).map(createVariantRow), locationIds: locationIds.length ? locationIds : [''], isPrivate: false }; } function buildCategorySelection(categories, categoryId) { @@ -80,6 +81,7 @@ export default function ItemEditorModal({ open, mode = 'edit', item = null, + defaultsFromItem = null, categories = [], locations = [], availableTags = [], @@ -90,7 +92,7 @@ export default function ItemEditorModal({ onDelete, onCopy }) { - const [draft, setDraft] = useState(() => normalizeItem(item, categories, locations, mode)); + const [draft, setDraft] = useState(() => normalizeItem(item, categories, locations, mode, defaultsFromItem)); const [dirtyDraft, setDirtyDraft] = useState(false); const [tagInput, setTagInput] = useState(''); const [imageFeedback, setImageFeedback] = useState({ type: '', message: '' }); @@ -144,7 +146,7 @@ export default function ItemEditorModal({ } else { browserEditorSessionRef.current = null; } - setDraft(normalizeItem(item, categories, locations, mode)); + setDraft(normalizeItem(item, categories, locations, mode, defaultsFromItem)); setDirtyDraft(false); setActiveTab('edit'); setTagInput(''); @@ -153,7 +155,7 @@ export default function ItemEditorModal({ replacePendingImages([]); stagedBrowserUploadRef.current.clear(); stagedImageCopyRef.current.clear(); - }, [open, item, categories, locations, mode, imageAccess]); + }, [open, item, categories, locations, mode, imageAccess, defaultsFromItem]); const categorySelection = useMemo( () => buildCategorySelection(categories, draft.categoryId), diff --git a/web/src/renderer/features/items/ItemsGalleryPage.jsx b/web/src/renderer/features/items/ItemsGalleryPage.jsx index dd28fe6..c0e1175 100644 --- a/web/src/renderer/features/items/ItemsGalleryPage.jsx +++ b/web/src/renderer/features/items/ItemsGalleryPage.jsx @@ -62,7 +62,9 @@ export default function ItemsGalleryPage({ setModalState({ open: true, mode: 'create', - itemId: null + itemId: null, + // Reverse the stable tie order for older records without creation dates. + defaultsFromItem: sortItemGalleryItems([...allItems].reverse(), 'created-desc')[0] || null }); } @@ -257,6 +259,7 @@ export default function ItemsGalleryPage({ item); } -export function createEmptyItemDraft(categories = [], locations = []) { +export function createEmptyItemDraft(categories = [], locations = [], previousItem = null) { const firstMainCategory = getChildEntries(categories, null)[0] || null; const firstSubCategory = firstMainCategory ? getChildEntries(categories, firstMainCategory.id)[0] || null : null; const level1Location = getChildEntries(locations, null)[0] || null; const level2Location = level1Location ? getChildEntries(locations, level1Location.id)[0] || null : null; const level3Location = level2Location ? getChildEntries(locations, level2Location.id)[0] || null : null; - return { + const empty = { barcode: '', code: '', name: '', @@ -65,6 +65,25 @@ export function createEmptyItemDraft(categories = [], locations = []) { imagePath: '', tags: [] }; + if (!previousItem) return empty; + + const locationIds = getItemLocationIds(previousItem).filter(id => locations.some(location => location.id === id)); + const rows = getItemVariants(previousItem); + const variants = (rows.length ? rows : getItemVariants(empty)).map(row => ({ + color: row.color, size: row.size, quantity: getVariantQuantity(row), isPackaged: row.isPackaged, imageId: '' + })); + return { + ...empty, + brand: toText(previousItem.brand), + specification: toText(previousItem.specification), + categoryId: categories.some(category => category.id === previousItem.categoryId) ? previousItem.categoryId : null, + locationId: locationIds[0] || null, + locationIds, + variants, + quantity: getItemQuantity({ variants }), + isPackaged: variants.some(row => row.isPackaged), + isPrivate: false + }; } export function buildTagChips(items = []) { diff --git a/web/src/renderer/features/web/WebApp.jsx b/web/src/renderer/features/web/WebApp.jsx index 7ce003b..a596f93 100644 --- a/web/src/renderer/features/web/WebApp.jsx +++ b/web/src/renderer/features/web/WebApp.jsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import AppShell from '../layout/AppShell'; import { applyItemGalleryFilters } from '../items/item-gallery-selectors'; import { createProjectStore, useProjectStore } from '../../store/project-store'; -import { sanitizeProject, syncProjectItems } from '../../lib/project-data'; +import { isItemPrivate, sanitizeProject, syncProjectItems } from '../../lib/project-data'; import { createWebApi } from './api'; import { ImageAccessProvider } from './ImageAccessContext'; import './web.css'; @@ -226,7 +226,13 @@ export default function WebApp({ fetchImpl, bootstrap }) { } const project = state.currentProject; - const visibleItems = useMemo(() => project ? applyItemGalleryFilters(project.items, project.categories, project.locations, state.itemFilters, state.search) : [], [project, state.itemFilters, state.search]); + // Keep the complete authorized project in the store for every save. The + // unlocked view displays only its private items, including inherited privacy. + const viewProject = useMemo(() => !project || !privacyOpen ? project : { + ...project, + items: project.items.filter(item => isItemPrivate(item, project)) + }, [project, privacyOpen]); + const visibleItems = useMemo(() => viewProject ? applyItemGalleryFilters(viewProject.items, viewProject.categories, viewProject.locations, state.itemFilters, state.search) : [], [viewProject, state.itemFilters, state.search]); if (!authenticated) return
@@ -257,7 +263,7 @@ export default function WebApp({ fetchImpl, bootstrap }) { : null} {project ? { cleanup(); vi.restoreAllMocks(); }); + +describe('new item defaults from saved items', () => { + it('reuses selections and specification rows without identity, photos, tags or privacy flags', () => { + const snapshot = structuredClone(previous); + const draft = createEmptyItemDraft(categories, locations, previous); + expect(draft).toMatchObject({ name: '', barcode: '', tags: [], imagePath: '', isPrivate: false, + brand: '品牌', specification: '印花 镂空', categoryId: 'clothes', locationIds: ['closet', 'desk'], + variants: [{ color: '蓝色', size: 'XL', quantity: 3, isPackaged: true, imageId: '' }, + { color: '白色', size: 'M', quantity: 1, isPackaged: false, imageId: '' }] }); + expect(draft).not.toHaveProperty('id'); + expect(draft).not.toHaveProperty('createdAt'); + draft.variants[0].color = '红色'; + draft.locationIds.pop(); + expect(previous).toEqual(snapshot); + }); + + it('does not reintroduce unavailable private categories or locations', () => { + const draft = createEmptyItemDraft(categories, locations, { ...previous, categoryId: 'hidden-category', locationIds: ['hidden-place', 'desk'] }); + expect(draft.categoryId).toBeNull(); + expect(draft.locationIds).toEqual(['desk']); + expect(draft.isPrivate).toBe(false); + }); + + it('opens a fresh item using the most recently added record instead of the last edited record', async () => { + const old = { ...previous, id: 'old', name: '旧物品', categoryId: 'first', createdAt: '2025-01-01T00:00:00Z', updatedAt: '2026-10-29T23:00:00Z' }; + const newest = { ...previous, id: 'newest', name: '新物品', isPrivate: false }; + const onCreateItem = vi.fn().mockResolvedValue(undefined); + render(); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: '新增物品', exact: true })); + expect(screen.getByLabelText('名称')).toHaveValue(''); + expect(screen.getByLabelText('主分类')).toHaveValue('clothes'); + expect(screen.getByLabelText('颜色1')).toHaveValue('蓝色'); + expect(screen.getByLabelText('尺码1')).toHaveValue('XL'); + expect(screen.getByLabelText('数量1')).toHaveValue(3); + expect(screen.getByLabelText('包装1')).toBeChecked(); + expect(screen.getAllByLabelText('一级位置').map(select => select.value)).toEqual(['closet', 'desk']); + expect(screen.getByLabelText('隐私区')).not.toBeChecked(); + expect(screen.queryByRole('button', { name: /放大规格/ })).not.toBeInTheDocument(); + await user.type(screen.getByLabelText('名称'), '下一件'); + await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: '保存', exact: true })); + expect(onCreateItem).toHaveBeenCalledWith(expect.objectContaining({ name: '下一件', isPrivate: false, + categoryId: 'clothes', locationIds: ['closet', 'desk'], imagePaths: [], tags: [] })); + expect(onCreateItem.mock.calls[0][0]).not.toHaveProperty('id'); + expect(onCreateItem.mock.calls[0][0]).not.toHaveProperty('createdAt'); + }); + + it('does not remember canceled changes or the source privacy checkbox', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(true); + const onCreateItem = vi.fn(); + render(); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: '新增物品', exact: true })); + await user.clear(screen.getByLabelText('颜色1')); + await user.type(screen.getByLabelText('颜色1'), '未保存颜色'); + await user.click(screen.getByLabelText('隐私区')); + await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: '取消', exact: true })); + await user.click(screen.getByRole('button', { name: '新增物品', exact: true })); + expect(screen.getByLabelText('颜色1')).toHaveValue('蓝色'); + expect(screen.getByLabelText('隐私区')).not.toBeChecked(); + expect(onCreateItem).not.toHaveBeenCalled(); + }); +}); diff --git a/web/tests/renderer/web-app.test.jsx b/web/tests/renderer/web-app.test.jsx index 22a3e31..c9e53ae 100644 --- a/web/tests/renderer/web-app.test.jsx +++ b/web/tests/renderer/web-app.test.jsx @@ -1,4 +1,3 @@ -import { uploadVariantPhotos } from '../helpers/upload-variant-photo'; import { StrictMode } from 'react'; import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; @@ -66,11 +65,14 @@ describe('password gated browser inventory', () => { const view = render(); await screen.findByRole('button', { name: '普通物品' }); async function checkEditors(unlocked) { - for (const name of ['新增物品', '普通物品']) { + for (const name of ['新增物品', unlocked ? '隐藏物品' : '普通物品']) { await user.click(screen.getByRole('button', { name, exact: true })); const dialog = screen.getByRole('dialog'); - if (unlocked) expect(within(dialog).getByRole('checkbox', { name: '隐私区' })).toBeEnabled(); - else expect(dialog).not.toHaveTextContent('隐私'); + if (unlocked) { + const privacyChoice = within(dialog).getByRole('checkbox', { name: '隐私区' }); + expect(privacyChoice).toBeInTheDocument(); + if (name === '隐藏物品') expect(privacyChoice).toBeChecked(); + } else expect(dialog).not.toHaveTextContent('隐私'); expect(within(dialog).getByRole('checkbox', { name: '包装1' })).toBeEnabled(); await user.click(screen.getByRole('button', { name: '关闭物品弹窗' })); } @@ -115,7 +117,7 @@ describe('password gated browser inventory', () => { await checkCatalog(false); }); - it('counts only the current privacy projection and immediately removes full counts when relocking', async () => { + it('counts only the current privacy view and immediately removes private counts when relocking', async () => { const ordinaryFetch = server({ authenticated: true }); let finishClose; const fetchImpl = vi.fn((url, init = {}) => { @@ -133,7 +135,7 @@ describe('password gated browser inventory', () => { await submitLogoPassword(user); await screen.findByRole('button', { name: '秘密条目', exact: true }); await user.click(screen.getByRole('button', { name: '分类', exact: true })); - expect(screen.getByLabelText('当前分类物品数量')).toHaveTextContent(/^2$/); + expect(screen.getByLabelText('当前分类物品数量')).toHaveTextContent(/^1$/); await user.click(screen.getByRole('button', { name: '物品管理', exact: true })); expect(screen.queryByRole('tree')).not.toBeInTheDocument(); expect(screen.queryByLabelText('当前分类物品数量')).not.toBeInTheDocument(); @@ -199,7 +201,7 @@ describe('password gated browser inventory', () => { expect(document.body).not.toHaveTextContent('隐藏物品'); }); - it('keeps the toolbar quiet and opens all records only after the independent password', async () => { + it('keeps the toolbar quiet and shows only private records after the independent password', async () => { const fetchImpl = server({ authenticated: true }); const user = userEvent.setup(); render(); @@ -209,12 +211,53 @@ describe('password gated browser inventory', () => { expect(document.body).not.toHaveTextContent(/隐私|重新读取|完整备份|导入 JSON|退出登录/); await submitLogoPassword(user); expect(await screen.findByRole('button', { name: '隐藏物品' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: '普通物品', exact: true })).not.toBeInTheDocument(); expect(screen.queryByLabelText('访问密码')).not.toBeInTheDocument(); expect(fetchImpl).toHaveBeenCalledWith('/api/privacy/open', expect.objectContaining({ body: JSON.stringify({ password: 'separate-password' }), headers: expect.objectContaining({ 'X-CSRF-Token': 'csrf' }) })); expect(fetchImpl).toHaveBeenCalledWith('/api/project', expect.objectContaining({ headers: expect.objectContaining({ 'X-Storage-Privacy': 'tab-private' }) })); expect(document.body).not.toHaveTextContent(/隐私区已打开|隐私范围|密码正确/); }); + it('resets ordinary filters on unlock and includes explicit, category and location inherited privacy', async () => { + const normalFetch = server({ authenticated: true }); + const privateProject = { + ...full, + categories: [...full.categories, { id: 'look-child', name: '衣物', level: 2, parentId: 'look' }], + locations: [...full.locations, + { id: 'private-room', name: '私密位置', level: 1, parentId: null, isPrivate: true }, + { id: 'private-box', name: '柜子', level: 2, parentId: 'private-room' } + ], + items: [...full.items, + { id: 'category-secret', name: '分类隐私物品', categoryId: 'look-child', isPrivate: false, imagePath: '', tags: [] }, + { id: 'location-secret', name: '位置隐私物品', categoryId: 'office', locationIds: ['home', 'private-box'], isPrivate: false, imagePath: '', tags: [] }, + { id: 'explicit-secret', name: '手动隐私物品', categoryId: 'office', isPrivate: true, imagePath: '', tags: [] } + ] + }; + const fetchImpl = vi.fn((url, init = {}) => url === '/api/project' && init.method !== 'PUT' && init.headers?.['X-Storage-Privacy'] + ? Promise.resolve(response(privateProject)) : normalFetch(url, init)); + const user = userEvent.setup(); + render(); + await screen.findByRole('button', { name: '普通物品', exact: true }); + act(() => { + useProjectStore.getState().setSearch('普通'); + useProjectStore.getState().setItemFilters({ mainCategoryId: 'office', locationId: 'home', tag: 'PUBLIC' }); + }); + await submitLogoPassword(user); + for (const name of ['隐藏物品', '分类隐私物品', '位置隐私物品', '手动隐私物品']) { + expect(await screen.findByRole('button', { name, exact: true })).toBeInTheDocument(); + } + expect(screen.queryByRole('button', { name: '普通物品', exact: true })).not.toBeInTheDocument(); + expect(useProjectStore.getState().search).toBe(''); + expect(useProjectStore.getState().itemFilters).toMatchObject({ mainCategoryId: '', locationId: '', tag: '' }); + // Rendering the private view must not discard the ordinary records needed for saves. + expect(useProjectStore.getState().currentProject.items).toHaveLength(5); + await submitLogoPassword(user, 'wrong-password'); + expect(await screen.findByRole('button', { name: '普通物品', exact: true })).toBeInTheDocument(); + for (const name of ['隐藏物品', '分类隐私物品', '位置隐私物品', '手动隐私物品']) { + expect(screen.queryByRole('button', { name, exact: true })).not.toBeInTheDocument(); + } + }); + it.each(['wrong-password', 'correct-password', ''])('silently leaves ordinary records unchanged for an unsuccessful password attempt %j', async (password) => { const fetchImpl = server({ authenticated: true }); const user = userEvent.setup(); @@ -364,16 +407,22 @@ describe('password gated browser inventory', () => { await screen.findByRole('button', { name: '普通物品' }); await submitLogoPassword(user); await screen.findByRole('button', { name: '隐藏物品' }); - await user.click(await screen.findByRole('button', { name: '普通物品' })); + const ordinaryBefore = structuredClone(useProjectStore.getState().currentProject.items.find(item => item.id === 'normal')); + await user.click(screen.getByRole('button', { name: '隐藏物品', exact: true })); const dialog = screen.getByRole('dialog'); - await uploadVariantPhotos(user, new File(['photo'], 'photo.png', { type: 'image/png' })); + await user.click(within(dialog).getByRole('button', { name: '上传规格1图片', exact: true })); + await user.upload(screen.getByLabelText('从相册选择图片'), new File(['photo'], 'photo.png', { type: 'image/png' })); expect(fetchImpl.mock.calls.some(([url]) => url === '/api/images')).toBe(false); - await user.click(within(dialog).getByLabelText('隐私区')); + expect(within(dialog).getByLabelText('隐私区')).toBeChecked(); await user.click(within(dialog).getByRole('button', { name: '保存', exact: true })); await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); - expect(useProjectStore.getState().currentProject.items[0]).toMatchObject({ isPrivate: true, imagePath: 'uploaded-image' }); + expect(useProjectStore.getState().currentProject.items.find(item => item.id === 'hidden')).toMatchObject({ isPrivate: true, imagePath: 'uploaded-image' }); + expect(useProjectStore.getState().currentProject.items.find(item => item.id === 'normal')).toEqual(ordinaryBefore); + expect(screen.queryByRole('button', { name: '普通物品', exact: true })).not.toBeInTheDocument(); const saved = fetchImpl.mock.calls.find(([url, init]) => url === '/api/project' && init.method === 'PUT'); expect(JSON.parse(saved[1].body)).toMatchObject({ revision: 3, scope: 'all', items: expect.arrayContaining([expect.objectContaining({ isPrivate: true, imagePath: 'uploaded-image' })]) }); + expect(JSON.parse(saved[1].body).items).toHaveLength(2); + expect(JSON.parse(saved[1].body).items.find(item => item.id === 'normal')).toMatchObject({ id: 'normal', name: '普通物品', isPrivate: false, imagePath: '' }); expect(saved[1].headers['X-Storage-Privacy']).toBe('tab-private'); expect(saved[1].headers['X-CSRF-Token']).toBe('csrf'); expect(fetchImpl.mock.calls.find(([url]) => url === '/api/images')[1].body).toContain('data:image/png;base64,');