12 Commits

Author SHA1 Message Date
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
11 changed files with 2545 additions and 446 deletions
+3 -1
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
@@ -165,6 +165,8 @@ Expected shapes today:
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.
- `GET /{database}/kitchen/items/grouped?expanded=0|1`
Returns grouped stock data; grouped review uses summary-first loading and hydrates item children in background.
- `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`
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "lonc-web", "name": "lonc-web",
"version": "0.2.0", "version": "0.2.1",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+37 -3
View File
@@ -21,7 +21,24 @@ 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 query = {};
const searchName = filters.searchName || filters.search_name;
if (searchName) {
query.search_name = searchName;
}
if (filters.limit !== undefined && filters.limit !== null) {
query.limit = filters.limit;
}
if (filters.offset !== undefined && filters.offset !== null) {
query.offset = filters.offset;
}
if (filters.cursor) {
query.cursor = filters.cursor;
}
const payload = await apiRequest(store, getPath('items'), {
query,
});
if (Array.isArray(payload)) { if (Array.isArray(payload)) {
return payload; return payload;
@@ -30,9 +47,26 @@ export async function listStockEntries(store, filters = {}) {
return payload?.data || payload?.entries || payload?.items || []; return payload?.data || payload?.entries || payload?.items || [];
} }
export async function listGroupedStockEntries(store) { export async function listGroupedStockEntries(store, options = {}) {
const query = {};
const expanded = options.expanded ?? 1;
query.expanded = expanded;
const searchName = options.searchName || options.search_name;
if (searchName) {
query.search_name = searchName;
}
if (options.limit !== undefined && options.limit !== null) {
query.limit = options.limit;
}
if (options.offset !== undefined && options.offset !== null) {
query.offset = options.offset;
}
if (options.cursor) {
query.cursor = options.cursor;
}
const payload = await apiRequest(store, `${getPath('items')}/grouped`, { const payload = await apiRequest(store, `${getPath('items')}/grouped`, {
query: { expanded: 1 }, query,
}); });
if (Array.isArray(payload)) { if (Array.isArray(payload)) {
+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.1';
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 = {
+15 -5
View File
@@ -843,6 +843,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,13 +866,20 @@ export function labelCreatePageData(store) {
return; return;
} }
if (!error || error?.name === 'NotFoundException') { 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; return;
} }
if (!this.scannerState.error) {
this.scannerState.error = this.normalizeScannerError(error);
}
}, },
); );
} catch (error) { } catch (error) {
+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
+290 -12
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;
} }
} }
+47
View File
@@ -15,6 +15,8 @@ vi.mock('../../src/api/client.js', () => ({
const { const {
applyItemUpsert, applyItemUpsert,
listGroupedStockEntries,
listStockEntries,
lookupItemByIdentifier, lookupItemByIdentifier,
lookupItemDetails, lookupItemDetails,
listKitchenChanges, listKitchenChanges,
@@ -28,6 +30,51 @@ describe('api/stock', () => {
apiRequestMock.mockReset(); apiRequestMock.mockReset();
}); });
it('listStockEntries forwards optional query filters', async () => {
apiRequestMock.mockResolvedValueOnce([]);
await listStockEntries(
{ config: { database: 'db' } },
{ searchName: 'Milk', limit: 20, offset: 40, cursor: 'cursor-1' },
);
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items',
{
query: {
search_name: 'Milk',
limit: 20,
offset: 40,
cursor: 'cursor-1',
},
},
);
});
it('listGroupedStockEntries defaults to expanded=1 and forwards options', async () => {
apiRequestMock.mockResolvedValueOnce([]);
await listGroupedStockEntries(
{ config: { database: 'db' } },
{ expanded: 0, searchName: 'Rice', limit: 10, offset: 0, cursor: 'cursor-2' },
);
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/grouped',
{
query: {
expanded: 0,
search_name: 'Rice',
limit: 10,
offset: 0,
cursor: 'cursor-2',
},
},
);
});
it('listKitchenChanges returns normalized changes payload', async () => { it('listKitchenChanges returns normalized changes payload', async () => {
apiRequestMock.mockResolvedValueOnce({ apiRequestMock.mockResolvedValueOnce({
since: 'cursor-1', since: 'cursor-1',
+55
View File
@@ -70,4 +70,59 @@ 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' });
const addAlert = vi.fn();
const data = stockListPageData({ addAlert, isConnected: false });
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.',
});
});
}); });
@@ -0,0 +1,418 @@
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: [],
},
];
}
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.groupedEntries[0].items).toEqual([]);
await data.hydrateGroupedEntriesInBackground();
expect(data.groupedHydrated).toBe(true);
expect(data.groupedEntries[0].items).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);
});
});