19 Commits

Author SHA1 Message Date
bblaz 50e147b079 Reduce grouped mark-gone refresh to summary fetch only
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 23:00:06 +02:00
bblaz 065eed9769 Bump app version to 0.2.4
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 22:49:01 +02:00
bblaz 6ca09cdf1f Add inactive item fallback for dashboard change feed lookups
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 22:46:28 +02:00
bblaz 79f4138b95 Merge pull request 'Drop stale label drafts after inactivity and bump version to 0.2.3' (#8) from codex/reset-stale-app-date into main
ci/woodpecker/push/woodpecker Pipeline is pending
Reviewed-on: #8
2026-04-12 20:36:44 +00:00
bblaz e50f848896 Drop stale label drafts after inactivity and bump version to 0.2.3
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-04-12 22:29:09 +02:00
bblaz 39dd474813 Align stock API with paginated backend and bump to v0.2.2
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 17:57:53 +02:00
bblaz ae8ad07d87 Rename grouped stock label from Latest quantity to Quantity
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 17:32:48 +02:00
bblaz c00e41170a Merge pull request 'codex/promote-grouped-stock-view' (#7) from codex/promote-grouped-stock-view into main
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #7
2026-04-12 15:25:34 +00:00
bblaz cc0e368480 Improve stock list restore and item-level refresh feedback
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-04-12 17:23:39 +02:00
bblaz 1d23279819 Refactor stock filters into a responsive sidebar rail
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 13:37:45 +02:00
bblaz 569ef1804b Add tests for grouped stock list behavior and improve stock view mode UI and API enhancements
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 13:05:14 +02:00
bblaz 8797726915 Merge pull request 'codex/add-barcode-scan-to-item' (#6) from codex/add-barcode-scan-to-item into main
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #6
2026-04-11 22:41:11 +00:00
bblaz ac2eafb504 Use patchStockItem to save stock detail identifier code
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-04-12 00:39:58 +02:00
bblaz 2974124555 Merge remote-tracking branch 'origin/codex/add-barcode-scan-to-item' into codex/add-barcode-scan-to-item
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/pr/woodpecker Pipeline failed
# Conflicts:
#	src/features/stock/stock-detail-page.js
2026-04-12 00:36:45 +02:00
bblaz c264c61226 Ignore scanner decode noise and log debug errors in dev 2026-04-12 00:33:12 +02:00
bblaz b65514bd0f Add barcode scanner and identifier editing to stock detail 2026-04-12 00:33:08 +02:00
bblaz 9677e47680 Ignore scanner decode noise and log debug errors in dev
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-04-12 00:24:41 +02:00
bblaz bbb5bd4dea Add barcode scanner and identifier editing to stock detail
ci/woodpecker/push/woodpecker Pipeline was successful
2026-04-12 00:18:25 +02:00
bblaz dfe83ab236 Merge pull request 'Upgrade OFF lookup UX and stock detail identifier editing' (#5) from codex/upgrade-openfoodfacts-handling into main
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #5
2026-04-11 08:16:23 +00:00
16 changed files with 3102 additions and 498 deletions
+14 -2
View File
@@ -110,17 +110,29 @@ Reason:
- grouped result is a better template for “new item from existing definition” - grouped result is a better template for “new item from existing definition”
- not expanding children keeps the query lighter - not expanding children keeps the query lighter
### List pagination
- `GET /{database}/kitchen/items` and `GET /{database}/kitchen/items/grouped` are paginated (`limit`/`offset`, backend default `limit=100`)
- frontend API helpers aggregate pages when no explicit `limit`/`offset` is requested
### Grouped stock view ### Grouped stock view
Grouped stock view uses: Grouped stock view uses:
- `GET /{database}/kitchen/items/grouped?expanded=1` - `GET /{database}/kitchen/items/grouped?expanded=0` for summary
- `GET /{database}/kitchen/items/grouped?expanded=1` for hydrated child details
Important: Important:
- group-level fields are meaningful and should be used - group-level fields are meaningful and should be used
- group expiration status should follow the backend-provided “first item expires” semantics - group expiration status should follow the backend-provided “first item expires” semantics
- do not assume grouped child records are always returned unless `expanded=1` - with `expanded=0`, grouped child `items` may be ID-only stubs (`{ id }`)
- do not assume grouped child records are fully returned unless `expanded=1`
### Stock updates
- `POST /{database}/kitchen/items/{uuid_b64}/stock` creates a stock event and returns `{ status, stock }`
- frontend refreshes item details with `GET /{database}/kitchen/items/{uuid_b64}` after stock updates
## UX rules that should be preserved ## UX rules that should be preserved
+7 -5
View File
@@ -137,7 +137,7 @@ Project-specific operating conventions for future contributors and coding agents
- Active kitchen selection and switching - Active kitchen selection and switching
- Dashboard with quick actions - Dashboard with quick actions
- Label creation flow with item lookup, location loading, preview, and stock entry creation - Label creation flow with item lookup, location loading, preview, and stock entry creation
- Stock list with search and filters - Grouped-first stock review with search and overview filters
- Stock detail page with stock adjustment workflow - Stock detail page with stock adjustment workflow
- PWA manifest, icons, service worker, and offline fallback - PWA manifest, icons, service worker, and offline fallback
@@ -164,7 +164,10 @@ Expected shapes today:
- `GET /{database}/kitchen/items?search_name=...` - `GET /{database}/kitchen/items?search_name=...`
Returns item definitions for autocomplete. Returns item definitions for autocomplete.
- `GET /{database}/kitchen/items` - `GET /{database}/kitchen/items`
Returns the current stock review list. Returns the current stock review list. Endpoint is paginated (`limit`/`offset`, backend default `limit=100`); frontend helpers aggregate pages by default unless explicit pagination is passed.
- `GET /{database}/kitchen/items/grouped?expanded=0|1`
Returns grouped stock data; grouped review uses summary-first loading (`expanded=0`) and hydrates item children in background (`expanded=1`).
With `expanded=0`, child `items` can be ID-only stubs (`{ id }`) instead of full item payloads.
- `GET /{database}/kitchen/items/{uuid_b64}` - `GET /{database}/kitchen/items/{uuid_b64}`
Returns one item detail payload. Returns one item detail payload.
- `GET /{database}/kitchen/changes` - `GET /{database}/kitchen/changes`
@@ -180,13 +183,12 @@ Expected shapes today:
- `POST /{database}/kitchen/items?label=1&preview=1` - `POST /{database}/kitchen/items?label=1&preview=1`
Returns an image blob, `{ imageUrl }`, or `{ imageSvg }` for in-browser preview. Returns an image blob, `{ imageUrl }`, or `{ imageSvg }` for in-browser preview.
- `POST /{database}/kitchen/items/{uuid_b64}/stock` - `POST /{database}/kitchen/items/{uuid_b64}/stock`
Updates measured or descriptive stock state using `{ quantity }` or `{ level }`. Creates a stock event for measured or descriptive updates using `{ quantity }` or `{ level }`.
Response shape is `{ status, stock }`; frontend re-fetches the item detail after successful update.
- `POST /{database}/kitchen/items/{uuid_b64}/use` - `POST /{database}/kitchen/items/{uuid_b64}/use`
Marks an item used up (`gone`) via stock-event semantics. Marks an item used up (`gone`) via stock-event semantics.
- `POST /{database}/kitchen/items/{uuid_b64}/print-label` - `POST /{database}/kitchen/items/{uuid_b64}/print-label`
Prints label for an existing item; called from the save flow when `Print` is enabled. Prints label for an existing item; called from the save flow when `Print` is enabled.
- `DELETE /{database}/kitchen/items/{uuid_b64}`
Compatibility fallback when `/use` is not available on the backend.
- `PATCH /{database}/kitchen/items/{uuid_b64}` - `PATCH /{database}/kitchen/items/{uuid_b64}`
Used for item-level edits from stock detail (for example identifier code updates). Used for item-level edits from stock detail (for example identifier code updates).
- `GET /{database}/kitchen/locations` - `GET /{database}/kitchen/locations`
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "lonc-web", "name": "lonc-web",
"version": "0.2.0", "version": "0.2.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "lonc-web", "name": "lonc-web",
"version": "0.2.0", "version": "0.2.4",
"dependencies": { "dependencies": {
"@zxing/browser": "^0.1.5", "@zxing/browser": "^0.1.5",
"alpinejs": "^3.14.9", "alpinejs": "^3.14.9",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "lonc-web", "name": "lonc-web",
"version": "0.2.0", "version": "0.2.4",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+95 -23
View File
@@ -1,9 +1,51 @@
import { apiRequest, getPath } from './client.js'; import { apiRequest, getPath } from './client.js';
const DEFAULT_LIST_PAGE_LIMIT = 100;
function unwrapEntryPayload(payload) { function unwrapEntryPayload(payload) {
return payload?.data || payload?.entry || payload?.item || payload; return payload?.data || payload?.entry || payload?.item || payload;
} }
function unwrapListPayload(payload) {
if (Array.isArray(payload)) {
return payload;
}
return payload?.data || payload?.entries || payload?.items || payload?.groups || [];
}
function hasExplicitPagination(filters = {}) {
return (
(filters.limit !== undefined && filters.limit !== null)
|| (filters.offset !== undefined && filters.offset !== null)
);
}
async function fetchAllListPages(store, path, baseQuery = {}) {
const items = [];
let offset = 0;
while (true) {
const payload = await apiRequest(store, path, {
query: {
...baseQuery,
limit: DEFAULT_LIST_PAGE_LIMIT,
offset,
},
});
const pageItems = unwrapListPayload(payload);
items.push(...pageItems);
if (pageItems.length < DEFAULT_LIST_PAGE_LIMIT) {
break;
}
offset += DEFAULT_LIST_PAGE_LIMIT;
}
return items;
}
export async function searchItemDefinitions(store, query) { export async function searchItemDefinitions(store, query) {
if (query.trim().length <= 2) { if (query.trim().length <= 2) {
return []; return [];
@@ -21,29 +63,64 @@ export async function searchItemDefinitions(store, query) {
} }
export async function listStockEntries(store, filters = {}) { export async function listStockEntries(store, filters = {}) {
const payload = await apiRequest(store, getPath('items')); const baseQuery = {};
const searchName = filters.searchName || filters.search_name;
if (Array.isArray(payload)) { if (searchName) {
return payload; baseQuery.search_name = searchName;
} }
return payload?.data || payload?.entries || payload?.items || []; if (hasExplicitPagination(filters)) {
const query = { ...baseQuery };
if (filters.limit !== undefined && filters.limit !== null) {
query.limit = filters.limit;
}
if (filters.offset !== undefined && filters.offset !== null) {
query.offset = filters.offset;
} }
export async function listGroupedStockEntries(store) { const payload = await apiRequest(store, getPath('items'), {
const payload = await apiRequest(store, `${getPath('items')}/grouped`, { query,
query: { expanded: 1 },
}); });
if (Array.isArray(payload)) { return unwrapListPayload(payload);
return payload;
} }
return payload?.data || payload?.entries || payload?.items || payload?.groups || []; return fetchAllListPages(store, getPath('items'), baseQuery);
} }
export async function getStockEntry(store, stockId) { export async function listGroupedStockEntries(store, options = {}) {
const payload = await apiRequest(store, `${getPath('items')}/${stockId}`); const baseQuery = {};
const expanded = options.expanded ?? 1;
baseQuery.expanded = expanded;
const searchName = options.searchName || options.search_name;
if (searchName) {
baseQuery.search_name = searchName;
}
if (hasExplicitPagination(options)) {
const query = { ...baseQuery };
if (options.limit !== undefined && options.limit !== null) {
query.limit = options.limit;
}
if (options.offset !== undefined && options.offset !== null) {
query.offset = options.offset;
}
const payload = await apiRequest(store, `${getPath('items')}/grouped`, {
query,
});
return unwrapListPayload(payload);
}
return fetchAllListPages(store, `${getPath('items')}/grouped`, baseQuery);
}
export async function getStockEntry(store, stockId, { allowInactive = false } = {}) {
const path = `${getPath('items')}/${stockId}`;
const payload = allowInactive
? await apiRequest(store, path, { query: { allow_inactive: 1 } })
: await apiRequest(store, path);
return unwrapEntryPayload(payload); return unwrapEntryPayload(payload);
} }
@@ -149,11 +226,11 @@ export async function patchStockItem(store, uuidB64, body) {
} }
export async function updateStockItem(store, uuidB64, body) { export async function updateStockItem(store, uuidB64, body) {
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, { await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, {
method: 'POST', method: 'POST',
body, body,
}); });
return unwrapEntryPayload(payload); return getStockEntry(store, uuidB64);
} }
export async function deleteStockItem(store, uuidB64) { export async function deleteStockItem(store, uuidB64) {
@@ -171,25 +248,20 @@ export async function useStockItem(store, uuidB64) {
return { status: 'used' }; return { status: 'used' };
} catch (error) { } catch (error) {
const status = error?.status || error?.cause?.status; const status = error?.status || error?.cause?.status;
if (status === 409) { if (status === 409 || status === 404) {
return { status: 'already_gone' }; return { status: 'already_gone' };
} }
if (status === 404 || status === 405) {
await deleteStockItem(store, uuidB64);
return { status: 'fallback_delete' };
}
throw error; throw error;
} }
} }
export async function adjustStockEntry(store, stockId, body) { export async function adjustStockEntry(store, stockId, body) {
const payload = await apiRequest(store, `${getPath('items')}/${stockId}/stock`, { await apiRequest(store, `${getPath('items')}/${stockId}/stock`, {
method: 'POST', method: 'POST',
body, body,
}); });
return unwrapEntryPayload(payload); return getStockEntry(store, stockId);
} }
export async function listKitchenChanges(store, { since, limit = 10 } = {}) { export async function listKitchenChanges(store, { since, limit = 10 } = {}) {
+2 -1
View File
@@ -1,5 +1,5 @@
export const APP_NAME = 'Lonc'; export const APP_NAME = 'Lonc';
export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.2.0'; export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.2.4';
export const TRYTON_APPLICATION = 'kitchen'; export const TRYTON_APPLICATION = 'kitchen';
export const CONNECTION_STATES = { export const CONNECTION_STATES = {
@@ -14,6 +14,7 @@ export const STORAGE_KEYS = {
session: 'lonc.auth.session', session: 'lonc.auth.session',
activeKitchen: 'lonc.kitchen.active', activeKitchen: 'lonc.kitchen.active',
labelDraft: 'lonc.labels.draft', labelDraft: 'lonc.labels.draft',
stockListContext: 'lonc.stock.list.context',
}; };
export const DEFAULT_CONFIG = { export const DEFAULT_CONFIG = {
+12 -1
View File
@@ -165,7 +165,18 @@ export function dashboardPageData(store) {
if (missingItemUuids.length) { if (missingItemUuids.length) {
const results = await Promise.allSettled( const results = await Promise.allSettled(
missingItemUuids.map((uuid) => getStockEntry(store, uuid)), missingItemUuids.map(async (uuid) => {
try {
return await getStockEntry(store, uuid);
} catch (error) {
const status = error?.status || error?.cause?.status;
if (status !== 404) {
throw error;
}
return getStockEntry(store, uuid, { allowInactive: true });
}
}),
); );
results.forEach((result) => { results.forEach((result) => {
+55 -11
View File
@@ -34,6 +34,7 @@ const STOCK_LEVEL_OPTIONS = [
const QUANTITY_UNIT_OPTIONS = ['g', 'ml', 'pc']; const QUANTITY_UNIT_OPTIONS = ['g', 'ml', 'pc'];
const EXPIRATION_DAY_OPTIONS = ['3', '5', '8', '10', '15', '20', '25', '30', '45', '60', '90', '120', '150', '180']; const EXPIRATION_DAY_OPTIONS = ['3', '5', '8', '10', '15', '20', '25', '30', '45', '60', '90', '120', '150', '180'];
const LABEL_DRAFT_STALE_MS = 30 * 60 * 1000;
export function renderLabelCreatePage() { export function renderLabelCreatePage() {
return ` return `
@@ -607,9 +608,7 @@ function createDefaultForm() {
}; };
} }
function loadLabelDraft() { function normalizeLabelDraft(draft) {
const draft = loadStoredValue(STORAGE_KEYS.labelDraft, createDefaultForm());
return { return {
...createDefaultForm(), ...createDefaultForm(),
...draft, ...draft,
@@ -638,6 +637,41 @@ function buildDraftPayload(form) {
}; };
} }
function buildLabelDraftEnvelope(form) {
return {
form: buildDraftPayload(form),
savedAt: Date.now(),
};
}
function saveLabelDraft(form) {
saveStoredValue(STORAGE_KEYS.labelDraft, buildLabelDraftEnvelope(form));
}
function loadLabelDraft() {
const storedDraft = loadStoredValue(STORAGE_KEYS.labelDraft, null);
if (!storedDraft || typeof storedDraft !== 'object' || Array.isArray(storedDraft)) {
return createDefaultForm();
}
const hasEnvelope =
storedDraft.form
&& typeof storedDraft.form === 'object'
&& !Array.isArray(storedDraft.form);
if (!hasEnvelope) {
return normalizeLabelDraft(storedDraft);
}
const savedAt = Number(storedDraft.savedAt || 0);
if (!savedAt || Date.now() - savedAt >= LABEL_DRAFT_STALE_MS) {
return createDefaultForm();
}
return normalizeLabelDraft(storedDraft.form);
}
export function labelCreatePageData(store) { export function labelCreatePageData(store) {
return { return {
previewState: createAsyncState(), previewState: createAsyncState(),
@@ -843,6 +877,9 @@ export function labelCreatePageData(store) {
this.stopScanner(); this.stopScanner();
this.scannerState.isLoading = true; this.scannerState.isLoading = true;
const shouldLogDecodeErrors = import.meta.env.DEV;
let lastDecodeErrorName = '';
let lastDecodeErrorAt = 0;
try { try {
if (!this.scannerReader) { if (!this.scannerReader) {
@@ -863,12 +900,19 @@ export function labelCreatePageData(store) {
return; return;
} }
if (!error || error?.name === 'NotFoundException') { if (error) {
return; // Continuous decode emits expected per-frame misses/errors before a valid barcode is found.
// Keep the modal quiet and only surface startup failures from the outer catch block.
if (shouldLogDecodeErrors) {
const errorName = String(error?.name || 'UnknownError');
const now = Date.now();
if (errorName !== lastDecodeErrorName || now - lastDecodeErrorAt > 2000) {
console.debug('[scanner] Ignoring frame decode error while scanning:', errorName, error?.message || '');
lastDecodeErrorName = errorName;
lastDecodeErrorAt = now;
} }
}
if (!this.scannerState.error) { return;
this.scannerState.error = this.normalizeScannerError(error);
} }
}, },
); );
@@ -1074,7 +1118,7 @@ export function labelCreatePageData(store) {
this.persistDraft(); this.persistDraft();
}, },
persistDraft() { persistDraft() {
saveStoredValue(STORAGE_KEYS.labelDraft, buildDraftPayload(this.form)); saveLabelDraft(this.form);
}, },
get filteredLocations() { get filteredLocations() {
const query = this.locationSearch.trim().toLowerCase(); const query = this.locationSearch.trim().toLowerCase();
@@ -1477,7 +1521,7 @@ export function labelCreatePageData(store) {
message: `${entryName} was ${operationVerb} successfully.`, message: `${entryName} was ${operationVerb} successfully.`,
}); });
this.upsertPreview = entry; this.upsertPreview = entry;
saveStoredValue(STORAGE_KEYS.labelDraft, buildDraftPayload(this.form)); saveLabelDraft(this.form);
} catch (error) { } catch (error) {
this.fieldErrors = normalizeValidationError(error); this.fieldErrors = normalizeValidationError(error);
this.submitError = error.message; this.submitError = error.message;
@@ -1498,7 +1542,7 @@ export function labelCreatePageData(store) {
this.fieldErrors = {}; this.fieldErrors = {};
this.upsertPreview = null; this.upsertPreview = null;
this.printIssue = ''; this.printIssue = '';
saveStoredValue(STORAGE_KEYS.labelDraft, this.form); saveLabelDraft(this.form);
if (revokePreview && this.previewUrl.startsWith('blob:')) { if (revokePreview && this.previewUrl.startsWith('blob:')) {
URL.revokeObjectURL(this.previewUrl); URL.revokeObjectURL(this.previewUrl);
} }
+218 -28
View File
@@ -5,6 +5,7 @@ import {
patchStockItem, patchStockItem,
useStockItem, useStockItem,
} from '../../api/stock.js'; } from '../../api/stock.js';
import { BrowserMultiFormatReader } from '@zxing/browser';
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js'; import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
import { fetchLocations } from '../../api/locations.js'; import { fetchLocations } from '../../api/locations.js';
import { getRouteContext } from '../../app/router.js'; import { getRouteContext } from '../../app/router.js';
@@ -147,6 +148,7 @@ export function renderStockDetailPage() {
class="form-control" class="form-control"
type="text" type="text"
x-model="identifierDraft" x-model="identifierDraft"
@input="identifierState.error = ''"
inputmode="numeric" inputmode="numeric"
autocomplete="off" autocomplete="off"
placeholder="EAN / UPC / GTIN" placeholder="EAN / UPC / GTIN"
@@ -160,8 +162,16 @@ export function renderStockDetailPage() {
<span x-show="!identifierState.isLoading">Save identifier</span> <span x-show="!identifierState.isLoading">Save identifier</span>
<span x-show="identifierState.isLoading">Saving...</span> <span x-show="identifierState.isLoading">Saving...</span>
</button> </button>
<button
class="btn btn-outline-secondary"
type="button"
@click="openScanner()"
x-show="scannerState.hasCamera"
>
Camera
</button>
</div> </div>
<div class="form-text">Used for OpenFoodFacts lookups and product metadata refresh.</div> <div class="form-text">Used for product identifier tracking and metadata lookups.</div>
<template x-if="identifierState.error"> <template x-if="identifierState.error">
<div class="small text-danger mt-1" x-text="identifierState.error"></div> <div class="small text-danger mt-1" x-text="identifierState.error"></div>
</template> </template>
@@ -200,7 +210,6 @@ export function renderStockDetailPage() {
></div> ></div>
</template> </template>
</div> </div>
<div class="mt-4"> <div class="mt-4">
<h3 class="h6 mb-3">Nutrition</h3> <h3 class="h6 mb-3">Nutrition</h3>
<dl class="row mb-0 detail-grid"> <dl class="row mb-0 detail-grid">
@@ -356,6 +365,39 @@ export function renderStockDetailPage() {
</div> </div>
</div> </div>
</template> </template>
<div
class="scanner-modal-backdrop"
x-show="scannerState.isOpen"
@click.self="closeScanner()"
@keydown.escape.window="closeScanner()"
>
<div class="scanner-modal card border-0 shadow-lg">
<div class="card-body p-3 p-md-4">
<div class="d-flex align-items-center justify-content-between gap-3 mb-3">
<div>
<h2 class="h5 mb-1">Scan barcode</h2>
<p class="text-body-secondary small mb-0">Point your camera at the barcode to fill the identifier field.</p>
</div>
<button class="btn btn-sm btn-outline-secondary" type="button" @click="closeScanner()">Close</button>
</div>
<div class="scanner-video-shell mb-3">
<video class="scanner-video" x-ref="scannerVideo" autoplay muted playsinline></video>
</div>
<div class="d-flex flex-wrap align-items-center gap-2">
<div class="small text-body-secondary" x-show="scannerState.isLoading">Starting camera...</div>
<div class="small text-success" x-show="scannerState.lastDetectedCode" x-text="'Detected: ' + scannerState.lastDetectedCode"></div>
<button class="btn btn-outline-secondary btn-sm" type="button" @click="startScanner()" :disabled="scannerState.isLoading">Retry</button>
</div>
<template x-if="scannerState.error">
<div class="alert alert-warning py-2 mt-3 mb-0" x-text="scannerState.error"></div>
</template>
</div>
</div>
</div>
</section> </section>
`; `;
} }
@@ -366,6 +408,15 @@ export function stockDetailPageData(store) {
adjustmentState: createAsyncState(), adjustmentState: createAsyncState(),
printState: createAsyncState(), printState: createAsyncState(),
identifierState: createAsyncState(), identifierState: createAsyncState(),
scannerReader: null,
scannerControls: null,
scannerState: {
isOpen: false,
isLoading: false,
hasCamera: false,
error: '',
lastDetectedCode: '',
},
lookupDetailsState: createAsyncState(), lookupDetailsState: createAsyncState(),
printFeedback: { printFeedback: {
type: '', type: '',
@@ -384,6 +435,7 @@ export function stockDetailPageData(store) {
level: 'plenty', level: 'plenty',
}, },
async init() { async init() {
this.scannerState.hasCamera = this.canUseCameraScanner();
if (!store.isConnected) { if (!store.isConnected) {
return; return;
} }
@@ -404,6 +456,170 @@ export function stockDetailPageData(store) {
this.adjustment.level = this.entry?.level || 'plenty'; this.adjustment.level = this.entry?.level || 'plenty';
}).catch(() => {}); }).catch(() => {});
}, },
destroy() {
this.stopScanner();
},
canUseCameraScanner() {
return Boolean(
typeof navigator !== 'undefined'
&& navigator.mediaDevices
&& typeof navigator.mediaDevices.getUserMedia === 'function',
);
},
normalizeScannerError(error) {
const message = String(error?.message || '');
const normalized = message.toLowerCase();
if (error?.name === 'NotAllowedError' || normalized.includes('permission')) {
return 'Camera access was denied. Allow access to scan, or enter the code manually.';
}
if (error?.name === 'NotFoundError' || normalized.includes('requested device not found')) {
return 'No camera was found on this device. Enter the identifier code manually.';
}
if (error?.name === 'NotReadableError' || normalized.includes('could not start video source')) {
return 'Camera is busy in another app. Close it there and try scanning again.';
}
return 'Could not start barcode scanning. Enter the identifier code manually.';
},
async openScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
this.scannerState.isOpen = true;
await this.$nextTick();
await this.startScanner();
},
async startScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
if (!this.canUseCameraScanner()) {
this.scannerState.hasCamera = false;
this.scannerState.error = 'Camera scanning is not supported in this browser. Enter the identifier code manually.';
return;
}
const videoElement = this.$refs.scannerVideo;
if (!videoElement) {
this.scannerState.error = 'Scanner video element is unavailable. Close and reopen scanner.';
return;
}
this.stopScanner();
this.scannerState.isLoading = true;
const shouldLogDecodeErrors = import.meta.env.DEV;
let lastDecodeErrorName = '';
let lastDecodeErrorAt = 0;
try {
if (!this.scannerReader) {
this.scannerReader = new BrowserMultiFormatReader();
}
this.scannerControls = await this.scannerReader.decodeFromConstraints(
{
audio: false,
video: {
facingMode: { ideal: 'environment' },
},
},
videoElement,
(result, error) => {
if (result) {
this.onBarcodeDetected(result.getText?.() || '');
return;
}
if (error) {
// Continuous decode emits expected per-frame misses/errors before a valid barcode is found.
// Keep the modal quiet and only surface startup failures from the outer catch block.
if (shouldLogDecodeErrors) {
const errorName = String(error?.name || 'UnknownError');
const now = Date.now();
if (errorName !== lastDecodeErrorName || now - lastDecodeErrorAt > 2000) {
console.debug('[scanner] Ignoring frame decode error while scanning:', errorName, error?.message || '');
lastDecodeErrorName = errorName;
lastDecodeErrorAt = now;
}
}
return;
}
},
);
} catch (error) {
this.scannerState.error = this.normalizeScannerError(error);
} finally {
this.scannerState.isLoading = false;
}
},
stopScanner() {
try {
this.scannerControls?.stop?.();
} catch {
// Ignore cleanup errors when scanner is already stopped.
}
this.scannerControls = null;
try {
this.scannerReader?.reset?.();
} catch {
// Ignore cleanup errors from stale reader state.
}
const videoElement = this.$refs.scannerVideo;
const stream = videoElement?.srcObject;
if (stream && typeof stream.getTracks === 'function') {
stream.getTracks().forEach((track) => track.stop());
}
if (videoElement) {
videoElement.srcObject = null;
}
},
closeScanner() {
this.stopScanner();
this.scannerState.isOpen = false;
this.scannerState.isLoading = false;
this.scannerState.error = '';
},
onBarcodeDetected(rawCode) {
const code = normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen) {
return;
}
this.identifierDraft = code;
this.scannerState.lastDetectedCode = code;
this.closeScanner();
store.addAlert({
type: 'success',
message: `Scanned identifier code: ${code}`,
});
},
async saveIdentifierCode() {
if (!this.entry?.uuid_b64) {
return;
}
this.identifierState.error = '';
await runAsyncState(this.identifierState, async () => {
const identifierCode = normalizeIdentifierCode(this.identifierDraft);
const updated = await patchStockItem(store, this.entry.uuid_b64, {
identifier_code: identifierCode || null,
});
this.entry = updated;
this.identifierDraft = normalizeIdentifierCode(updated?.identifier_code || identifierCode);
store.addAlert({
type: 'success',
message: identifierCode
? `Identifier code saved for ${this.entry.name}.`
: `Identifier code cleared for ${this.entry.name}.`,
});
}).catch(() => {});
},
normalizedIdentifierDraft() { normalizedIdentifierDraft() {
return normalizeIdentifierCode(this.identifierDraft); return normalizeIdentifierCode(this.identifierDraft);
}, },
@@ -471,32 +687,6 @@ export function stockDetailPageData(store) {
return parts.join(' '); return parts.join(' ');
}, },
async saveIdentifierCode() {
if (!this.entry?.uuid_b64) {
return;
}
this.identifierState.error = '';
await runAsyncState(this.identifierState, async () => {
const identifierCode = this.normalizedIdentifierDraft();
const updated = await patchStockItem(store, this.entry.uuid_b64, {
identifier_code: identifierCode || null,
});
this.entry = updated;
this.identifierDraft = normalizeIdentifierCode(updated?.identifier_code || identifierCode);
this.offLookupFeedback = {
type: '',
message: '',
};
store.addAlert({
type: 'success',
message: identifierCode
? `Identifier code saved for ${this.entry.name}.`
: `Identifier code cleared for ${this.entry.name}.`,
});
}).catch(() => {});
},
async runItemLookup(update) { async runItemLookup(update) {
if (!this.entry?.uuid_b64) { if (!this.entry?.uuid_b64) {
return; return;
File diff suppressed because it is too large Load Diff
+289 -11
View File
@@ -314,10 +314,112 @@ body {
color: var(--lonc-primary); color: var(--lonc-primary);
} }
.stock-filter-hub {
background:
linear-gradient(160deg, rgba(255, 255, 255, 0.94), rgba(245, 250, 255, 0.88)),
linear-gradient(135deg, rgba(93, 169, 255, 0.1), rgba(31, 75, 153, 0.06));
}
.stock-workspace {
align-items: flex-start;
}
.stock-results-pane {
min-width: 0;
}
.stock-filter-summary {
padding: 0.85rem 0.95rem;
border-radius: 0.9rem;
border: 1px dashed rgba(31, 75, 153, 0.24);
background: rgba(255, 255, 255, 0.7);
min-height: 100%;
}
.stock-filter-rail .overview-list-locations {
max-height: 18rem;
}
.stock-filter-rail .location-overview-columns {
grid-template-columns: 1fr;
}
@media (min-width: 768px) and (max-width: 1199.98px) {
.stock-filter-panels {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
.stock-filter-panels.stock-filter-panels-single-open {
grid-template-columns: 1fr;
}
}
@media (min-width: 1200px) {
.stock-filter-rail .stock-filter-hub {
position: sticky;
top: 1rem;
}
}
.stock-view-switch { .stock-view-switch {
display: inline-flex; display: grid;
flex-wrap: wrap; grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem; gap: 0.65rem;
}
.stock-view-switch-wrap {
min-width: min(100%, 38rem);
}
.stock-view-tab {
display: grid;
align-content: start;
gap: 0.2rem;
text-align: left;
border: 1px solid var(--lonc-border);
border-radius: 0.9rem;
background: rgba(255, 255, 255, 0.66);
color: inherit;
padding: 0.65rem 0.85rem;
transition:
border-color 160ms ease,
box-shadow 160ms ease,
background-color 160ms ease,
transform 160ms ease;
}
.stock-view-tab:hover {
transform: translateY(-1px);
border-color: rgba(31, 75, 153, 0.24);
box-shadow: 0 8px 16px rgba(24, 42, 79, 0.08);
}
.stock-view-tab:focus-visible {
outline: 2px solid rgba(31, 75, 153, 0.4);
outline-offset: 2px;
}
.stock-view-tab-active {
border-color: rgba(31, 75, 153, 0.42);
background: rgba(31, 75, 153, 0.1);
box-shadow: inset 0 0 0 1px rgba(31, 75, 153, 0.18);
}
.stock-view-tab-title {
font-weight: 700;
font-size: 0.95rem;
}
.stock-view-tab-subtitle {
font-size: 0.78rem;
color: var(--lonc-muted);
}
@media (max-width: 767.98px) {
.stock-view-switch {
grid-template-columns: 1fr;
}
} }
.overview-row-single-open > [class*='col-'] { .overview-row-single-open > [class*='col-'] {
@@ -329,6 +431,16 @@ body {
height: auto; height: auto;
} }
.stock-filter-panel-card {
border: 1px solid var(--lonc-border);
border-radius: 1rem;
background: rgba(255, 255, 255, 0.84);
}
.stock-filter-panel-card[open] {
box-shadow: 0 10px 24px rgba(24, 42, 79, 0.08);
}
.overview-summary { .overview-summary {
display: block; display: block;
cursor: pointer; cursor: pointer;
@@ -592,21 +704,69 @@ button.legend-card:focus-visible {
list-style: none; list-style: none;
} }
.grouped-stock-summary-row {
min-height: 0;
}
.grouped-stock-summary-title {
font-size: 1.1rem;
line-height: 1.2;
}
.grouped-stock-summary-description {
margin: 0.12rem 0 0.35rem;
}
.grouped-stock-summary::-webkit-details-marker { .grouped-stock-summary::-webkit-details-marker {
display: none; display: none;
} }
.grouped-stock-summary-meta { .grouped-stock-summary-meta {
align-items: center; align-items: center;
align-content: flex-start;
column-gap: 0.95rem;
row-gap: 0.08rem;
line-height: 1.25;
}
.grouped-stock-summary-status {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-start;
gap: 0.4rem 0.75rem;
}
.grouped-stock-secondary-details {
border-top: 1px dashed rgba(31, 39, 64, 0.14);
padding-top: 0.75rem;
}
.grouped-stock-secondary-toggle {
border-radius: 0.85rem;
border: 1px solid var(--lonc-border);
padding: 0.5rem 0.75rem;
background: rgba(255, 255, 255, 0.66);
}
.grouped-stock-secondary-toggle > summary {
list-style: none;
cursor: pointer;
}
.grouped-stock-secondary-toggle > summary::-webkit-details-marker {
display: none;
} }
.grouped-stock-toggle-label { .grouped-stock-toggle-label {
color: var(--lonc-primary); color: var(--lonc-primary);
font-size: 0.8rem;
line-height: 1.1;
} }
.grouped-stock-toggle-label::after { .grouped-stock-toggle-label::after {
content: 'Expand'; content: 'Expand';
margin-left: 0.35rem; margin-left: 0.25rem;
} }
.grouped-stock-card[open] .grouped-stock-toggle-label::after { .grouped-stock-card[open] .grouped-stock-toggle-label::after {
@@ -633,14 +793,20 @@ button.legend-card:focus-visible {
border-left-color: #6c757d; border-left-color: #6c757d;
} }
@media (min-width: 1200px) {
.grouped-stock-summary-status {
justify-content: flex-end;
}
}
.grouped-stock-items { .grouped-stock-items {
display: grid; display: grid;
gap: 0.75rem; gap: 0.55rem;
} }
.grouped-stock-item { .grouped-stock-item {
display: block; display: block;
padding: 0.9rem 1rem; padding: 0.65rem 0.8rem;
border-radius: 0.95rem; border-radius: 0.95rem;
border: 1px solid var(--lonc-border); border: 1px solid var(--lonc-border);
background: rgba(255, 255, 255, 0.72); background: rgba(255, 255, 255, 0.72);
@@ -677,12 +843,71 @@ button.legend-card:focus-visible {
background: rgba(108, 117, 125, 0.08); background: rgba(108, 117, 125, 0.08);
} }
.grouped-stock-item-meta { .grouped-stock-item-row {
justify-content: flex-start; display: grid;
grid-template-columns: minmax(0, 1fr) auto auto;
align-items: center;
gap: 0.75rem;
}
.grouped-stock-item-main {
min-width: 0;
}
.grouped-stock-item-title-line {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.6rem;
}
.grouped-stock-item-name {
font-size: 1rem;
line-height: 1.2;
}
.grouped-stock-item-id {
color: var(--lonc-muted);
font-size: 0.8rem;
}
.grouped-stock-item-aux {
display: grid;
gap: 0.2rem;
text-align: right;
justify-items: end;
white-space: nowrap;
}
.grouped-stock-item-actions {
display: flex;
align-items: center;
gap: 0.5rem;
white-space: nowrap;
}
.grouped-stock-item-link {
font-size: 0.8rem;
}
.stock-item-link-disabled {
pointer-events: none;
opacity: 0.55;
}
.stock-item-refresh-indicator {
color: rgba(31, 39, 64, 0.78) !important;
font-weight: 600;
margin-top: 0.15rem;
}
.stock-item-refreshing {
opacity: 0.94;
} }
.grouped-stock-mark-gone { .grouped-stock-mark-gone {
align-self: center; padding: 0.2rem 0.55rem;
line-height: 1.2;
white-space: nowrap; white-space: nowrap;
} }
@@ -708,9 +933,62 @@ button.legend-card:focus-visible {
font-weight: 700; font-weight: 700;
} }
@media (min-width: 1200px) { .grouped-stock-close-row {
.grouped-stock-item-meta { display: flex;
justify-content: flex-end; justify-content: flex-end;
margin-top: 0.2rem;
padding-top: 0.2rem;
border-top: 1px dashed rgba(31, 39, 64, 0.12);
}
.grouped-stock-close {
padding: 0.1rem 0.2rem;
font-size: 0.78rem;
color: rgba(31, 39, 64, 0.82);
line-height: 1.1;
}
.grouped-stock-close:hover {
color: var(--lonc-primary-dark);
}
@media (max-width: 991.98px) {
.grouped-stock-item-row {
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
}
.grouped-stock-item-actions {
grid-column: 1 / -1;
justify-content: space-between;
padding-top: 0.15rem;
}
.grouped-stock-item-aux {
text-align: left;
justify-items: start;
}
}
@media (max-width: 575.98px) {
.grouped-stock-item {
padding: 0.6rem 0.7rem;
}
.grouped-stock-item-row {
grid-template-columns: 1fr;
gap: 0.4rem;
}
.grouped-stock-item-aux {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
text-align: left;
}
.grouped-stock-item-title-line {
gap: 0.45rem;
} }
} }
+182 -12
View File
@@ -14,12 +14,17 @@ vi.mock('../../src/api/client.js', () => ({
})); }));
const { const {
adjustStockEntry,
applyItemUpsert, applyItemUpsert,
getStockEntry,
listGroupedStockEntries,
listKitchenChanges,
listStockEntries,
lookupItemByIdentifier, lookupItemByIdentifier,
lookupItemDetails, lookupItemDetails,
listKitchenChanges,
patchStockItem, patchStockItem,
previewItemUpsert, previewItemUpsert,
updateStockItem,
useStockItem, useStockItem,
} = await import('../../src/api/stock.js'); } = await import('../../src/api/stock.js');
@@ -28,6 +33,128 @@ describe('api/stock', () => {
apiRequestMock.mockReset(); apiRequestMock.mockReset();
}); });
it('listStockEntries forwards explicit pagination query filters', async () => {
apiRequestMock.mockResolvedValueOnce([]);
await listStockEntries(
{ config: { database: 'db' } },
{ searchName: 'Milk', limit: 20, offset: 40 },
);
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items',
{
query: {
search_name: 'Milk',
limit: 20,
offset: 40,
},
},
);
});
it('listStockEntries aggregates all pages by default', async () => {
apiRequestMock
.mockResolvedValueOnce(Array.from({ length: 100 }, (_, id) => ({ id: id + 1 })))
.mockResolvedValueOnce([{ id: 101 }]);
const response = await listStockEntries(
{ config: { database: 'db' } },
{ searchName: 'Milk' },
);
expect(response).toHaveLength(101);
expect(apiRequestMock).toHaveBeenNthCalledWith(
1,
{ config: { database: 'db' } },
'kitchen/items',
{ query: { search_name: 'Milk', limit: 100, offset: 0 } },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
2,
{ config: { database: 'db' } },
'kitchen/items',
{ query: { search_name: 'Milk', limit: 100, offset: 100 } },
);
});
it('listGroupedStockEntries forwards explicit pagination options', async () => {
apiRequestMock.mockResolvedValueOnce([]);
await listGroupedStockEntries(
{ config: { database: 'db' } },
{ expanded: 0, searchName: 'Rice', limit: 10, offset: 0 },
);
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/grouped',
{
query: {
expanded: 0,
search_name: 'Rice',
limit: 10,
offset: 0,
},
},
);
});
it('listGroupedStockEntries aggregates all pages by default', async () => {
apiRequestMock
.mockResolvedValueOnce(Array.from({ length: 100 }, (_, id) => ({ id: id + 1 })))
.mockResolvedValueOnce([{ id: 101 }]);
const response = await listGroupedStockEntries(
{ config: { database: 'db' } },
{ expanded: 1, searchName: 'Rice' },
);
expect(response).toHaveLength(101);
expect(apiRequestMock).toHaveBeenNthCalledWith(
1,
{ config: { database: 'db' } },
'kitchen/items/grouped',
{ query: { expanded: 1, search_name: 'Rice', limit: 100, offset: 0 } },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
2,
{ config: { database: 'db' } },
'kitchen/items/grouped',
{ query: { expanded: 1, search_name: 'Rice', limit: 100, offset: 100 } },
);
});
it('getStockEntry fetches item without allow_inactive by default', async () => {
apiRequestMock.mockResolvedValueOnce({ uuid_b64: 'item-1', name: 'Milk' });
const result = await getStockEntry({ config: { database: 'db' } }, 'item-1');
expect(result).toEqual({ uuid_b64: 'item-1', name: 'Milk' });
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-1',
);
});
it('getStockEntry forwards allow_inactive when requested', async () => {
apiRequestMock.mockResolvedValueOnce({ uuid_b64: 'item-2', active: false });
const result = await getStockEntry(
{ config: { database: 'db' } },
'item-2',
{ allowInactive: true },
);
expect(result).toEqual({ uuid_b64: 'item-2', active: false });
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-2',
{ query: { allow_inactive: 1 } },
);
});
it('listKitchenChanges returns normalized changes payload', async () => { it('listKitchenChanges returns normalized changes payload', async () => {
apiRequestMock.mockResolvedValueOnce({ apiRequestMock.mockResolvedValueOnce({
since: 'cursor-1', since: 'cursor-1',
@@ -210,6 +337,56 @@ describe('api/stock', () => {
}); });
}); });
it('updateStockItem posts stock event and re-fetches updated item', async () => {
apiRequestMock
.mockResolvedValueOnce({ status: 'OK', stock: { id: 1 } })
.mockResolvedValueOnce({ uuid_b64: 'item-1', quantity: 2 });
const response = await updateStockItem(
{ config: { database: 'db' } },
'item-1',
{ quantity: 2 },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
1,
{ config: { database: 'db' } },
'kitchen/items/item-1/stock',
{ method: 'POST', body: { quantity: 2 } },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
2,
{ config: { database: 'db' } },
'kitchen/items/item-1',
);
expect(response).toEqual({ uuid_b64: 'item-1', quantity: 2 });
});
it('adjustStockEntry posts stock event and re-fetches updated item', async () => {
apiRequestMock
.mockResolvedValueOnce({ status: 'OK', stock: { id: 2 } })
.mockResolvedValueOnce({ uuid_b64: 'item-1', level: 'good' });
const response = await adjustStockEntry(
{ config: { database: 'db' } },
'item-1',
{ level: 'good' },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
1,
{ config: { database: 'db' } },
'kitchen/items/item-1/stock',
{ method: 'POST', body: { level: 'good' } },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
2,
{ config: { database: 'db' } },
'kitchen/items/item-1',
);
expect(response).toEqual({ uuid_b64: 'item-1', level: 'good' });
});
it('useStockItem returns used on 204', async () => { it('useStockItem returns used on 204', async () => {
apiRequestMock.mockResolvedValueOnce(null); apiRequestMock.mockResolvedValueOnce(null);
@@ -231,20 +408,13 @@ describe('api/stock', () => {
expect(result).toEqual({ status: 'already_gone' }); expect(result).toEqual({ status: 'already_gone' });
}); });
it('useStockItem falls back to delete on 404/405', async () => { it('useStockItem returns already_gone on 404', async () => {
apiRequestMock apiRequestMock.mockRejectedValueOnce({ status: 404 });
.mockRejectedValueOnce({ status: 404 })
.mockResolvedValueOnce(null);
const result = await useStockItem({ config: { database: 'db' } }, 'item-1'); const result = await useStockItem({ config: { database: 'db' } }, 'item-1');
expect(result).toEqual({ status: 'fallback_delete' }); expect(result).toEqual({ status: 'already_gone' });
expect(apiRequestMock).toHaveBeenNthCalledWith( expect(apiRequestMock).toHaveBeenCalledTimes(1);
2,
{ config: { database: 'db' } },
'kitchen/items/item-1',
{ method: 'DELETE' },
);
}); });
it('useStockItem does not fallback on unrelated client errors', async () => { it('useStockItem does not fallback on unrelated client errors', async () => {
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
const listKitchenChangesMock = vi.fn(); const listKitchenChangesMock = vi.fn();
const getStockEntryMock = vi.fn(); const getStockEntryMock = vi.fn();
@@ -16,6 +16,12 @@ vi.mock('../../../src/api/locations.js', () => ({
const { dashboardPageData, renderDashboardPage } = await import('../../../src/features/dashboard/dashboard-page.js'); const { dashboardPageData, renderDashboardPage } = await import('../../../src/features/dashboard/dashboard-page.js');
describe('features/dashboard/dashboard-page', () => { describe('features/dashboard/dashboard-page', () => {
beforeEach(() => {
listKitchenChangesMock.mockReset();
getStockEntryMock.mockReset();
fetchLocationsMock.mockReset();
});
it('renders dashboard with recent changes section', () => { it('renders dashboard with recent changes section', () => {
const html = renderDashboardPage(); const html = renderDashboardPage();
expect(html).toContain('Recent changes'); expect(html).toContain('Recent changes');
@@ -107,6 +113,50 @@ describe('features/dashboard/dashboard-page', () => {
expect(getStockEntryMock).toHaveBeenCalledWith(expect.anything(), 'item-uuid-1'); expect(getStockEntryMock).toHaveBeenCalledWith(expect.anything(), 'item-uuid-1');
}); });
it('retries stock event item lookup with allowInactive after 404', async () => {
listKitchenChangesMock.mockResolvedValueOnce({
since: null,
nextCursor: null,
changes: [{
type: 'stock',
action: 'upsert',
timestamp: '2026-04-10T10:00:00Z',
stock: {
item_uuid_b64: 'item-uuid-2',
quantity: 1,
uom_symbol: 'pcs',
},
}],
});
getStockEntryMock
.mockRejectedValueOnce(Object.assign(new Error('Not found'), { status: 404 }))
.mockResolvedValueOnce({
uuid_b64: 'item-uuid-2',
name: 'Archived pasta',
stock_type: 'measured',
});
fetchLocationsMock.mockResolvedValueOnce({ flat: [] });
const store = {
isConnected: true,
setActiveKitchen: vi.fn(),
addAlert: vi.fn(),
};
const data = dashboardPageData(store);
await data.refreshChanges();
expect(getStockEntryMock).toHaveBeenNthCalledWith(1, store, 'item-uuid-2');
expect(getStockEntryMock).toHaveBeenNthCalledWith(
2,
store,
'item-uuid-2',
{ allowInactive: true },
);
expect(data.changeHeadline(data.recentChanges[0])).toBe('Stock saved: Archived pasta');
expect(data.changeStateLine(data.recentChanges[0])).toContain('Quantity: 1 pcs');
});
it('keeps empty state when API returns no changes', async () => { it('keeps empty state when API returns no changes', async () => {
listKitchenChangesMock.mockResolvedValueOnce({ listKitchenChangesMock.mockResolvedValueOnce({
since: null, since: null,
+177 -1
View File
@@ -1,8 +1,33 @@
import { describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const applyItemUpsertMock = vi.fn(); const applyItemUpsertMock = vi.fn();
const previewItemUpsertMock = vi.fn(); const previewItemUpsertMock = vi.fn();
const printItemLabelMock = vi.fn(); const printItemLabelMock = vi.fn();
const LABEL_DRAFT_STORAGE_KEY = 'lonc.labels.draft';
let localStorageState;
let localStorageMock;
function createWindowStorageMock(initialState = {}) {
const state = new Map(Object.entries(initialState));
const localStorage = {
getItem: vi.fn((key) => (state.has(key) ? state.get(key) : null)),
setItem: vi.fn((key, value) => {
state.set(key, String(value));
}),
removeItem: vi.fn((key) => {
state.delete(key);
}),
};
vi.stubGlobal('window', { localStorage });
return { state, localStorage };
}
function readStoredLabelDraft() {
const raw = localStorageState.get(LABEL_DRAFT_STORAGE_KEY);
return raw ? JSON.parse(raw) : null;
}
vi.mock('../../../src/api/stock.js', () => ({ vi.mock('../../../src/api/stock.js', () => ({
applyItemUpsert: (...args) => applyItemUpsertMock(...args), applyItemUpsert: (...args) => applyItemUpsertMock(...args),
@@ -23,6 +48,23 @@ vi.mock('../../../src/api/locations.js', () => ({
const { labelCreatePageData } = await import('../../../src/features/labels/label-create-page.js'); const { labelCreatePageData } = await import('../../../src/features/labels/label-create-page.js');
describe('label create upsert-first submit', () => { describe('label create upsert-first submit', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-04-12T12:00:00Z'));
applyItemUpsertMock.mockReset();
previewItemUpsertMock.mockReset();
printItemLabelMock.mockReset();
const storageMock = createWindowStorageMock();
localStorageState = storageMock.state;
localStorageMock = storageMock.localStorage;
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('defaults print checkbox to enabled', () => { it('defaults print checkbox to enabled', () => {
const data = labelCreatePageData({ const data = labelCreatePageData({
isConnected: false, isConnected: false,
@@ -32,6 +74,132 @@ describe('label create upsert-first submit', () => {
expect(data.printLabelOnSave).toBe(true); expect(data.printLabelOnSave).toBe(true);
}); });
it('restores a fresh enveloped draft when inactivity is below 30 minutes', () => {
localStorageState.set(
LABEL_DRAFT_STORAGE_KEY,
JSON.stringify({
form: {
name: 'Draft yogurt',
productionDate: '2026-04-11',
stockType: 'descriptive',
},
savedAt: Date.now() - (29 * 60 * 1000),
}),
);
const data = labelCreatePageData({
isConnected: false,
activeKitchen: { id: 1 },
addAlert: vi.fn(),
});
expect(data.form.name).toBe('Draft yogurt');
expect(data.form.productionDate).toBe('2026-04-11');
expect(data.form.stockType).toBe('descriptive');
});
it('drops stale enveloped drafts at 30 minutes inactivity and loads a clean form', () => {
localStorageState.set(
LABEL_DRAFT_STORAGE_KEY,
JSON.stringify({
form: {
name: 'Old draft',
description: 'Should be removed',
productionDate: '2026-04-10',
stockType: 'measured',
quantity: '4',
uom: 'kg',
},
savedAt: Date.now() - (30 * 60 * 1000),
}),
);
const data = labelCreatePageData({
isConnected: false,
activeKitchen: { id: 1 },
addAlert: vi.fn(),
});
expect(data.form.name).toBe('');
expect(data.form.description).toBe('');
expect(data.form.stockType).toBe('binary');
expect(data.form.quantity).toBe('');
expect(data.form.uom).toBe('g');
expect(data.form.productionDate).toBe('2026-04-12');
});
it('keeps draft when day changes but inactivity stays below 30 minutes', () => {
vi.setSystemTime(new Date('2026-04-12T00:10:00Z'));
localStorageState.set(
LABEL_DRAFT_STORAGE_KEY,
JSON.stringify({
form: {
name: 'Day-changed draft',
productionDate: '2026-04-11',
},
savedAt: Date.now() - (10 * 60 * 1000),
}),
);
const data = labelCreatePageData({
isConnected: false,
activeKitchen: { id: 1 },
addAlert: vi.fn(),
});
expect(data.form.name).toBe('Day-changed draft');
expect(data.form.productionDate).toBe('2026-04-11');
});
it('loads legacy plain-object drafts without forcing discard', () => {
localStorageState.set(
LABEL_DRAFT_STORAGE_KEY,
JSON.stringify({
name: 'Legacy draft',
productionDate: '2026-04-05',
}),
);
const data = labelCreatePageData({
isConnected: false,
activeKitchen: { id: 1 },
addAlert: vi.fn(),
});
expect(data.form.name).toBe('Legacy draft');
expect(data.form.productionDate).toBe('2026-04-05');
});
it('writes enveloped draft payload from persist and reset save paths', () => {
const data = labelCreatePageData({
isConnected: false,
activeKitchen: { id: 1 },
addAlert: vi.fn(),
});
data.form = {
...data.form,
name: 'Persisted entry',
search: 'temp search value',
};
data.persistDraft();
const persistedDraft = readStoredLabelDraft();
expect(persistedDraft.savedAt).toBe(Date.now());
expect(persistedDraft.form.name).toBe('Persisted entry');
expect(persistedDraft.form.search).toBe('');
vi.setSystemTime(new Date('2026-04-12T12:05:00Z'));
data.form.name = 'Reset me';
data.$refs = {};
data.reset(false);
const resetDraft = readStoredLabelDraft();
expect(resetDraft.savedAt).toBe(Date.now());
expect(resetDraft.form.name).toBe('');
expect(resetDraft.form.productionDate).toBe('2026-04-12');
});
it('builds upsert payload with selected template uuid', () => { it('builds upsert payload with selected template uuid', () => {
const store = { const store = {
isConnected: false, isConnected: false,
@@ -96,6 +264,13 @@ describe('label create upsert-first submit', () => {
type: 'success', type: 'success',
message: 'Rice was updated successfully.', message: 'Rice was updated successfully.',
}); });
const savedDraft = readStoredLabelDraft();
expect(savedDraft).toMatchObject({
form: {
name: 'Rice',
},
});
expect(savedDraft.savedAt).toBeTypeOf('number');
}); });
it('create shows parsed print issue warning when printing fails', async () => { it('create shows parsed print issue warning when printing fails', async () => {
@@ -129,5 +304,6 @@ describe('label create upsert-first submit', () => {
type: 'warning', type: 'warning',
message: 'Beans was created, but printing has an issue: Printer is unavailable.', message: 'Beans was created, but printing has an issue: Printer is unavailable.',
}); });
expect(localStorageMock.setItem).toHaveBeenCalled();
}); });
}); });
+63 -1
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const useStockItemMock = vi.fn(); const useStockItemMock = vi.fn();
const getStockEntryMock = vi.fn(); const getStockEntryMock = vi.fn();
const listGroupedStockEntriesMock = vi.fn();
vi.mock('../../../src/api/stock.js', () => ({ vi.mock('../../../src/api/stock.js', () => ({
useStockItem: (...args) => useStockItemMock(...args), useStockItem: (...args) => useStockItemMock(...args),
@@ -10,7 +11,7 @@ vi.mock('../../../src/api/stock.js', () => ({
lookupItemDetails: vi.fn(), lookupItemDetails: vi.fn(),
patchStockItem: vi.fn(), patchStockItem: vi.fn(),
listStockEntries: vi.fn(), listStockEntries: vi.fn(),
listGroupedStockEntries: vi.fn(), listGroupedStockEntries: (...args) => listGroupedStockEntriesMock(...args),
updateStockItem: vi.fn(), updateStockItem: vi.fn(),
})); }));
@@ -25,6 +26,7 @@ describe('stock mark-gone behavior', () => {
beforeEach(() => { beforeEach(() => {
useStockItemMock.mockReset(); useStockItemMock.mockReset();
getStockEntryMock.mockReset(); getStockEntryMock.mockReset();
listGroupedStockEntriesMock.mockReset();
globalThis.window = { globalThis.window = {
__loncApp: { __loncApp: {
navigate: vi.fn(), navigate: vi.fn(),
@@ -70,4 +72,64 @@ describe('stock mark-gone behavior', () => {
message: 'Flour was marked gone and removed from the list.', message: 'Flour was marked gone and removed from the list.',
}); });
}); });
it('stock list grouped markGone removes item from grouped and flat collections', async () => {
useStockItemMock.mockResolvedValueOnce({ status: 'used' });
listGroupedStockEntriesMock.mockResolvedValueOnce([]);
const addAlert = vi.fn();
const store = { addAlert, isConnected: true };
const data = stockListPageData(store);
data.groupedLoaded = true;
data.groupedEntries = [
{
id: 10,
uuid_b64: 'group-10',
name: 'Beans',
stock_type: 'measured',
location_initial_uuid_b64: null,
date: '2026-04-12',
expire_date: '2026-04-20',
items: [
{
id: 11,
uuid_b64: 'item-11',
name: 'Beans',
stock_type: 'measured',
quantity: 1,
location_initial_uuid_b64: null,
date: '2026-04-12',
expire_date: '2026-04-20',
},
],
},
].map((group) => data.indexGroup(group));
data.entries = [
data.indexEntry({
id: 11,
uuid_b64: 'item-11',
name: 'Beans',
stock_type: 'measured',
quantity: 1,
location_initial_uuid_b64: null,
date: '2026-04-12',
expire_date: '2026-04-20',
}),
];
data.entriesVersion = 1;
data.groupedVersion = 1;
data.editForms = { 11: { level: 'plenty', quantity: 1 } };
data.editErrors = {};
await data.markGoneFromGroup(data.groupedEntries[0].items[0], data.groupedEntries[0]);
expect(data.entries).toEqual([]);
expect(data.groupedEntries).toEqual([]);
expect(addAlert).toHaveBeenCalledWith({
type: 'success',
message: 'Beans was marked gone and removed from the group.',
});
expect(listGroupedStockEntriesMock).toHaveBeenCalledTimes(1);
expect(listGroupedStockEntriesMock).toHaveBeenCalledWith(store, { expanded: 0 });
});
}); });
@@ -0,0 +1,433 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const listStockEntriesMock = vi.fn();
const listGroupedStockEntriesMock = vi.fn();
const listKitchenChangesMock = vi.fn();
const getStockEntryMock = vi.fn();
const updateStockItemMock = vi.fn();
const useStockItemMock = vi.fn();
const fetchLocationsMock = vi.fn();
vi.mock('../../../src/api/stock.js', () => ({
listStockEntries: (...args) => listStockEntriesMock(...args),
listGroupedStockEntries: (...args) => listGroupedStockEntriesMock(...args),
listKitchenChanges: (...args) => listKitchenChangesMock(...args),
getStockEntry: (...args) => getStockEntryMock(...args),
updateStockItem: (...args) => updateStockItemMock(...args),
useStockItem: (...args) => useStockItemMock(...args),
}));
vi.mock('../../../src/api/locations.js', () => ({
fetchLocations: (...args) => fetchLocationsMock(...args),
}));
const { stockListPageData } = await import('../../../src/features/stock/stock-list-page.js');
function createGroupedSummary() {
return [
{
id: 10,
uuid_b64: 'group-10',
name: 'Rice',
description: 'Basmati',
stock_type: 'measured',
level: 'good',
quantity: 1,
uom_symbol: 'kg',
location_initial_uuid_b64: 'loc-root',
date: '2026-04-10',
expire_date: '2026-04-25',
first_expire_date: '2026-04-25',
first_production_date: '2026-04-10',
items_count: 1,
items: [{ id: 100 }],
},
];
}
function createGroupedExpanded() {
return [
{
...createGroupedSummary()[0],
items: [
{
id: 100,
uuid_b64: 'item-100',
name: 'Rice',
description: 'Open bag',
stock_type: 'measured',
level: 'good',
quantity: 1,
uom_symbol: 'kg',
location_initial_uuid_b64: 'loc-root',
date: '2026-04-10',
expire_date: '2026-04-25',
expire_in: 13,
},
],
},
];
}
function createWindowMock() {
const intervals = new Map();
let nextId = 1;
const storage = new Map();
return {
location: { hash: '#/stock' },
scrollY: 1,
setInterval: vi.fn((fn) => {
const id = nextId;
nextId += 1;
intervals.set(id, fn);
return id;
}),
clearInterval: vi.fn((id) => {
intervals.delete(id);
}),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
matchMedia: vi.fn(() => ({ matches: false })),
scrollTo: vi.fn(),
localStorage: {
getItem: vi.fn((key) => storage.get(key) ?? null),
setItem: vi.fn((key, value) => {
storage.set(key, value);
}),
removeItem: vi.fn((key) => {
storage.delete(key);
}),
},
__intervals: intervals,
};
}
describe('stock list grouped-first behavior', () => {
beforeEach(() => {
listStockEntriesMock.mockReset();
listGroupedStockEntriesMock.mockReset();
listKitchenChangesMock.mockReset();
getStockEntryMock.mockReset();
updateStockItemMock.mockReset();
useStockItemMock.mockReset();
fetchLocationsMock.mockReset();
globalThis.window = createWindowMock();
globalThis.requestAnimationFrame = (callback) => callback();
globalThis.HTMLDetailsElement = class MockDetailsElement {};
});
afterEach(() => {
vi.restoreAllMocks();
delete globalThis.window;
delete globalThis.requestAnimationFrame;
delete globalThis.HTMLDetailsElement;
delete globalThis.structuredClone;
});
it('defaults to grouped mode and loads grouped summary before lazy item list', async () => {
listGroupedStockEntriesMock
.mockResolvedValueOnce(createGroupedSummary())
.mockResolvedValueOnce(createGroupedExpanded());
listStockEntriesMock.mockResolvedValueOnce([]);
listKitchenChangesMock.mockResolvedValue({ since: null, nextCursor: null, changes: [] });
fetchLocationsMock.mockResolvedValue({ flat: [], tree: [] });
const store = { isConnected: true, addAlert: vi.fn() };
const data = stockListPageData(store);
data.$nextTick = vi.fn(async () => {});
await data.init();
expect(data.viewMode).toBe('grouped');
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(1, store, { expanded: 0 });
expect(listStockEntriesMock).not.toHaveBeenCalled();
await Promise.resolve();
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(2, store, { expanded: 1 });
await data.switchView('items');
expect(listStockEntriesMock).toHaveBeenCalledTimes(1);
await data.switchView('grouped');
await data.switchView('items');
expect(listStockEntriesMock).toHaveBeenCalledTimes(1);
});
it('hydrates grouped children in background and merges into existing groups', async () => {
listGroupedStockEntriesMock
.mockResolvedValueOnce(createGroupedSummary())
.mockResolvedValueOnce(createGroupedExpanded());
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
await data.loadGroupedEntries({ expanded: 0, resetVisible: true });
expect(data.groupDisplayItems(data.groupedEntries[0])).toEqual([]);
expect(data.hasGroupedChildStubs(data.groupedEntries[0])).toBe(true);
await data.hydrateGroupedEntriesInBackground();
expect(data.groupedHydrated).toBe(true);
expect(data.groupDisplayItems(data.groupedEntries[0])).toHaveLength(1);
expect(data.hasGroupedChildStubs(data.groupedEntries[0])).toBe(false);
});
it('preserves hydrated child details when summary refresh returns id stubs', async () => {
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
data.applyGroupedSummary(createGroupedSummary());
data.applyGroupedHydration(createGroupedExpanded());
expect(data.groupDisplayItems(data.groupedEntries[0])).toHaveLength(1);
data.applyGroupedSummary(createGroupedSummary());
expect(data.groupDisplayItems(data.groupedEntries[0])).toHaveLength(1);
});
it('memoizes filtered results and invalidates when filters change', () => {
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
data.entries = [
data.indexEntry({
id: 1,
uuid_b64: 'item-1',
name: 'Milk',
description: 'Fresh',
location_initial_uuid_b64: null,
stock_type: 'binary',
level: 'good',
}),
];
data.entriesVersion = 1;
const first = data.filteredEntries;
const second = data.filteredEntries;
expect(second).toBe(first);
data.filters.search = 'milk';
const third = data.filteredEntries;
expect(third).not.toBe(first);
expect(third).toHaveLength(1);
});
it('keeps grouped data visible while background summary refresh is in progress', async () => {
let resolveRefresh;
const refreshPromise = new Promise((resolve) => {
resolveRefresh = resolve;
});
listGroupedStockEntriesMock.mockImplementationOnce(() => refreshPromise);
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
data.groupedLoaded = true;
data.groupedEntries = createGroupedSummary().map((group) => data.indexGroup(group));
const pending = data.loadGroupedEntries({ expanded: 0, background: true });
expect(data.state.isRefreshing).toBe(true);
expect(data.groupedEntries).toHaveLength(1);
resolveRefresh(createGroupedSummary());
await pending;
expect(data.state.isRefreshing).toBe(false);
expect(data.groupedEntries).toHaveLength(1);
});
it('poll refreshes view only when new changes exist', async () => {
listKitchenChangesMock
.mockResolvedValueOnce({ since: 'a', nextCursor: 'b', changes: [] })
.mockResolvedValueOnce({
since: 'b',
nextCursor: 'c',
changes: [{ type: 'stock', action: 'use', timestamp: '2026-04-12T08:00:00Z' }],
});
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
const refreshSpy = vi.fn(async () => {});
data.refreshCurrentView = refreshSpy;
await data.pollKitchenChanges();
expect(refreshSpy).not.toHaveBeenCalled();
await data.pollKitchenChanges();
expect(refreshSpy).toHaveBeenCalledTimes(1);
expect(refreshSpy).toHaveBeenCalledWith({ background: true });
});
it('tracks grouped card open state from details toggle events', () => {
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
class MockDetails extends HTMLDetailsElement {
constructor() {
super();
this.open = true;
this.dataset = { groupId: '10' };
}
querySelector() {
return {
scrollIntoView: vi.fn(),
};
}
}
const details = new MockDetails();
data.handleGroupedToggle({ target: details });
expect(data.isGroupedCardOpen(10)).toBe(true);
details.open = false;
data.handleGroupedToggle({ target: details });
expect(data.isGroupedCardOpen(10)).toBe(false);
});
it('restores from runtime cache on back navigation and refreshes only focused item', async () => {
listKitchenChangesMock.mockResolvedValue({ since: null, nextCursor: null, changes: [] });
getStockEntryMock.mockResolvedValueOnce({
id: 100,
uuid_b64: 'item-100',
name: 'Rice',
description: 'Open bag',
stock_type: 'measured',
level: 'good',
quantity: 2,
uom_symbol: 'kg',
location_initial_uuid_b64: 'loc-root',
date: '2026-04-12',
expire_date: '2026-04-20',
expire_in: 8,
});
const store = {
isConnected: true,
addAlert: vi.fn(),
activeKitchen: { id: 1 },
};
const firstVisit = stockListPageData(store);
firstVisit.entries = [
firstVisit.indexEntry({
id: 100,
uuid_b64: 'item-100',
name: 'Rice',
description: 'Open bag',
stock_type: 'measured',
level: 'good',
quantity: 1,
uom_symbol: 'kg',
location_initial_uuid_b64: 'loc-root',
date: '2026-04-10',
expire_date: '2026-04-25',
expire_in: 13,
}),
];
firstVisit.entriesVersion = 1;
firstVisit.itemsLoaded = true;
firstVisit.groupedEntries = createGroupedExpanded().map((group) => firstVisit.indexGroup(group));
firstVisit.groupedVersion = 1;
firstVisit.groupedLoaded = true;
firstVisit.groupedHydrated = true;
firstVisit.locations = [
{
id: 1,
uuid_b64: 'loc-root',
name: 'Pantry',
pathLabel: 'Pantry',
depth: 0,
type: 'storage',
lineage_uuid_b64: ['loc-root'],
},
];
firstVisit.locationsVersion = 1;
firstVisit.locationMap = { 'loc-root': 'Pantry' };
firstVisit.locationDescendants = { 'loc-root': ['loc-root'] };
firstVisit.locationLineage = { 'loc-root': ['loc-root'] };
firstVisit.viewMode = 'grouped';
firstVisit.filters.search = 'rice';
firstVisit.rememberStockListContext('item-100');
const returnVisit = stockListPageData(store);
returnVisit.$nextTick = vi.fn(async () => {});
await returnVisit.init();
await Promise.resolve();
await Promise.resolve();
expect(listGroupedStockEntriesMock).not.toHaveBeenCalled();
expect(listStockEntriesMock).not.toHaveBeenCalled();
expect(fetchLocationsMock).not.toHaveBeenCalled();
expect(getStockEntryMock).toHaveBeenCalledWith(store, 'item-100');
expect(returnVisit.entries[0].quantity).toBe(2);
expect(returnVisit.groupedEntries[0].items[0].quantity).toBe(2);
expect(returnVisit.groupedEntries[0].quantity).toBe(2);
expect(returnVisit.groupedEntries[0].first_expire_date).toBe('2026-04-20');
expect(returnVisit.groupedEntries[0].date).toBe('2026-04-12');
});
it('tracks item-level refresh state while focused item refresh is in progress', async () => {
let resolveEntry;
getStockEntryMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveEntry = resolve;
}),
);
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
data.entries = [
data.indexEntry({
id: 100,
uuid_b64: 'item-100',
name: 'Rice',
description: 'Open bag',
stock_type: 'measured',
level: 'good',
quantity: 1,
uom_symbol: 'kg',
location_initial_uuid_b64: 'loc-root',
date: '2026-04-10',
expire_date: '2026-04-25',
}),
];
data.entriesVersion = 1;
data.itemsLoaded = true;
const pending = data.refreshFocusedItemInBackground('item-100');
expect(data.isItemRefreshing('item-100')).toBe(true);
resolveEntry({
...data.entries[0],
quantity: 3,
});
await pending;
expect(data.isItemRefreshing('item-100')).toBe(false);
expect(data.entries[0].quantity).toBe(3);
});
it('falls back when structuredClone throws during runtime cache snapshot', async () => {
globalThis.structuredClone = vi.fn(() => {
throw new Error('The object can not be cloned.');
});
listGroupedStockEntriesMock
.mockResolvedValueOnce(createGroupedSummary())
.mockResolvedValueOnce(createGroupedExpanded());
listKitchenChangesMock.mockResolvedValue({ since: null, nextCursor: null, changes: [] });
fetchLocationsMock.mockResolvedValue({ flat: [], tree: [] });
const store = { isConnected: true, addAlert: vi.fn() };
const data = stockListPageData(store);
data.$nextTick = vi.fn(async () => {});
await data.init();
await Promise.resolve();
expect(data.state.error).toBe('');
expect(data.groupedEntries.length).toBeGreaterThan(0);
});
});