11 Commits

Author SHA1 Message Date
bblaz f67d2c89be Merge pull request 'Refactor stock API to replace numeric flags with boolean values, add getItemLabel endpoint, and update tests/documentation' (#10) from codex/update-rest-api-integration into main
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #10
2026-05-02 20:52:10 +00:00
bblaz 054a7ad0dd Add category management: list API, UI integration, and search updates
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-05-02 22:47:46 +02:00
bblaz 1fe56a232b Refactor stock API to replace numeric flags with boolean values, add getItemLabel endpoint, and update tests/documentation
ci/woodpecker/push/woodpecker Pipeline was successful
2026-05-01 23:51:05 +02:00
bblaz 34e339eb44 Merge pull request 'Add scanner utility, modal, and stock scan page implementation' (#9) from codex/plan-item-scanning-flows into main
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #9
2026-05-01 21:36:40 +00:00
bblaz e63c8a2770 Refactor stock mark-gone tests to use markStockGoneMock instead of useStockItemMock and update alert messaging
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2026-05-01 23:35:39 +02:00
bblaz 47434db5b5 Add scanner utility, modal, and stock scan page implementation
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/pr/woodpecker Pipeline failed
2026-05-01 23:32:13 +02:00
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
27 changed files with 2801 additions and 432 deletions
+16 -10
View File
@@ -163,36 +163,42 @@ Expected shapes today:
Returns `{ data: [...] }` or `{ kitchens: [...] }`.
- `GET /{database}/kitchen/items?search_name=...`
Returns item definitions for autocomplete.
Item payloads now expose category links via `categories` (array of IDs).
- `GET /{database}/kitchen/items`
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/grouped?expanded=true|false`
Returns grouped stock data; grouped review uses summary-first loading (`expanded=false`) and hydrates item children in background (`expanded=true`).
With `expanded=false`, child `items` can be ID-only stubs (`{ id }`) instead of full item payloads.
- `GET /{database}/kitchen/items/{uuid_b64}`
Returns one item detail payload.
Supports `allow_inactive=true|false` query filtering when needed.
- `GET /{database}/kitchen/changes`
Returns `{ since, next_cursor, changes }` feed payload for item/stock updates.
- `POST /{database}/kitchen/items/upsert?mode=preview|apply`
Used by label submit flow for create-or-update behavior and conflict-safe matching.
- `POST /{database}/kitchen/items/lookup`
Identifier lookup response includes source/freshness metadata (`source`, `cache_hit`, `stale_cache`, `payload_fetched_at`, `retry_after_seconds`) used for richer user feedback.
- `POST /{database}/kitchen/items/{uuid_b64}/lookup?update=0|1`
Item-scoped OpenFoodFacts lookup used by stock detail to preview (`update=0`) or apply missing fields (`update=1`).
- `POST /{database}/kitchen/items?label=1`
Used for label image preview rendering.
- `POST /{database}/kitchen/items?label=1&preview=1`
- `POST /{database}/kitchen/items/{uuid_b64}/lookup?update=true|false`
Item-scoped OpenFoodFacts lookup used by stock detail to preview (`update=false`) or apply missing fields (`update=true`).
- `POST /{database}/kitchen/items?label=true&preview=true`
Returns an image blob, `{ imageUrl }`, or `{ imageSvg }` for in-browser preview.
- `GET /{database}/kitchen/items/{uuid_b64}/label`
Returns rendered label PNG for an existing item.
- `POST /{database}/kitchen/items/{uuid_b64}/stock`
Creates a stock event for measured or descriptive updates using `{ quantity }` or `{ level }`.
Creates a stock event for measured or descriptive updates using `{ quantity }` or `{ level }`,
and for non-consumed gone transitions (for example `{ level: "gone", gone_reason: "spoiled" }`).
Response shape is `{ status, stock }`; frontend re-fetches the item detail after successful update.
- `POST /{database}/kitchen/items/{uuid_b64}/use`
Marks an item used up (`gone`) via stock-event semantics.
Marks an item consumed/used up (`gone`) via stock-event semantics.
- `POST /{database}/kitchen/items/{uuid_b64}/print-label`
Prints label for an existing item; called from the save flow when `Print` is enabled.
- `PATCH /{database}/kitchen/items/{uuid_b64}`
Used for item-level edits from stock detail (for example identifier code updates).
- `GET /{database}/kitchen/locations`
Returns a nested location tree.
- `GET /{database}/kitchen/categories`
Returns categories (paged). Frontend now resolves category labels from
`categories_detail` when present, and falls back to this endpoint by ID.
## Notes
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lonc-web",
"version": "0.2.2",
"version": "0.2.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lonc-web",
"version": "0.2.2",
"version": "0.2.6",
"dependencies": {
"@zxing/browser": "^0.1.5",
"alpinejs": "^3.14.9",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "lonc-web",
"version": "0.2.2",
"version": "0.2.6",
"private": true,
"type": "module",
"scripts": {
+90
View File
@@ -0,0 +1,90 @@
import { apiRequest, getPath } from './client.js';
const DEFAULT_LIST_PAGE_LIMIT = 100;
function unwrapListPayload(payload) {
if (Array.isArray(payload)) {
return payload;
}
return payload?.data || payload?.entries || payload?.items || payload?.categories || [];
}
function hasExplicitPagination(filters = {}) {
return (
(filters.limit !== undefined && filters.limit !== null)
|| (filters.offset !== undefined && filters.offset !== null)
);
}
function buildCategoryQuery(filters = {}) {
const query = {};
const searchName = filters.searchName || filters.search_name;
if (searchName) {
query.search_name = searchName;
}
if (filters.active !== undefined && filters.active !== null && filters.active !== '') {
query.active = Boolean(filters.active);
}
if (filters.orderBy || filters.order_by) {
query.order_by = filters.orderBy || filters.order_by;
}
if (filters.orderDir || filters.order_dir) {
query.order_dir = filters.orderDir || filters.order_dir;
}
if (filters.expanded !== undefined && filters.expanded !== null && filters.expanded !== '') {
query.expanded = Boolean(filters.expanded);
}
return query;
}
async function fetchAllCategoryPages(store, baseQuery = {}) {
const items = [];
let offset = 0;
while (true) {
const payload = await apiRequest(store, getPath('categories'), {
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 listCategories(store, filters = {}) {
const baseQuery = buildCategoryQuery(filters);
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;
}
const payload = await apiRequest(store, getPath('categories'), {
query,
});
return unwrapListPayload(payload);
}
return fetchAllCategoryPages(store, baseQuery);
}
+14 -1
View File
@@ -42,7 +42,7 @@ export async function previewLabel(store, body) {
method: 'POST',
body,
accept: 'image/svg+xml, image/png, application/json',
query: { label: 1, preview: 1 },
query: { label: true, preview: true },
});
const image = normalizeLabelImagePayload(payload);
@@ -53,6 +53,19 @@ export async function previewLabel(store, body) {
throw new Error('Label preview response did not include an image.');
}
export async function getItemLabel(store, uuidB64) {
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/label`, {
method: 'GET',
accept: 'image/png, application/json',
});
const image = normalizeLabelImagePayload(payload);
if (image) {
return image;
}
throw new Error('Item label response did not include an image.');
}
export async function printItemLabel(store, uuidB64) {
return apiRequest(store, `${getPath('items')}/${uuidB64}/print-label`, {
method: 'POST',
+98 -7
View File
@@ -2,6 +2,35 @@ import { apiRequest, getPath } from './client.js';
const DEFAULT_LIST_PAGE_LIMIT = 100;
function toBooleanFlag(value, defaultValue = false) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value !== 0;
}
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
if (!normalized) {
return defaultValue;
}
if (['1', 'true', 'yes', 'y', 'on'].includes(normalized)) {
return true;
}
if (['0', 'false', 'no', 'n', 'off'].includes(normalized)) {
return false;
}
}
return Boolean(value);
}
function unwrapEntryPayload(payload) {
return payload?.data || payload?.entry || payload?.item || payload;
}
@@ -52,7 +81,7 @@ export async function searchItemDefinitions(store, query) {
}
const payload = await apiRequest(store, `${getPath('items')}/grouped`, {
query: { search_name: query, expanded: 0 },
query: { search_name: query, expanded: false },
});
if (Array.isArray(payload)) {
@@ -90,7 +119,7 @@ export async function listStockEntries(store, filters = {}) {
export async function listGroupedStockEntries(store, options = {}) {
const baseQuery = {};
const expanded = options.expanded ?? 1;
const expanded = toBooleanFlag(options.expanded, true);
baseQuery.expanded = expanded;
const searchName = options.searchName || options.search_name;
if (searchName) {
@@ -116,8 +145,11 @@ export async function listGroupedStockEntries(store, options = {}) {
return fetchAllListPages(store, `${getPath('items')}/grouped`, baseQuery);
}
export async function getStockEntry(store, stockId) {
const payload = await apiRequest(store, `${getPath('items')}/${stockId}`);
export async function getStockEntry(store, stockId, { allowInactive = false } = {}) {
const path = `${getPath('items')}/${stockId}`;
const payload = allowInactive
? await apiRequest(store, path, { query: { allow_inactive: true } })
: await apiRequest(store, path);
return unwrapEntryPayload(payload);
}
@@ -125,7 +157,7 @@ export async function createStockEntry(store, body) {
const payload = await apiRequest(store, getPath('items'), {
method: 'POST',
body,
query: { label: 1, print: 1 },
query: { label: true, print: true },
});
return unwrapEntryPayload(payload);
}
@@ -208,7 +240,7 @@ export async function lookupItemByIdentifier(store, identifierCode) {
export async function lookupItemDetails(store, uuidB64, { update = false } = {}) {
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/lookup`, {
method: 'POST',
query: { update: update ? 1 : 0 },
query: { update: toBooleanFlag(update, false) },
});
return normalizeItemLookupResponse(payload);
@@ -227,7 +259,66 @@ export async function updateStockItem(store, uuidB64, body) {
method: 'POST',
body,
});
return getStockEntry(store, uuidB64);
return getStockEntry(store, uuidB64, {
allowInactive: body?.level === 'gone' || Number(body?.quantity) <= 0,
});
}
export async function createStockEvent(store, uuidB64, body) {
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, {
method: 'POST',
body,
});
return payload?.stock || payload;
}
export async function listStockEvents(store, uuidB64, options = {}) {
const query = {};
if (options.allowInactive) {
query.allow_inactive = true;
}
if (options.limit !== undefined && options.limit !== null) {
query.limit = options.limit;
}
if (options.offset !== undefined && options.offset !== null) {
query.offset = options.offset;
}
if (options.orderBy || options.order_by) {
query.order_by = options.orderBy || options.order_by;
}
if (options.orderDir || options.order_dir) {
query.order_dir = options.orderDir || options.order_dir;
}
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, {
query,
});
return unwrapListPayload(payload);
}
export async function markStockGone(store, uuidB64, reason = 'consumed') {
try {
if (reason === 'consumed') {
const result = await useStockItem(store, uuidB64);
if (result.status === 'already_gone') {
return { status: 'already_gone', reason };
}
return { status: 'gone', reason };
}
await createStockEvent(store, uuidB64, {
level: 'gone',
gone_reason: reason,
});
return { status: 'gone', reason };
} catch (error) {
const status = error?.status || error?.cause?.status;
if (status === 409 || status === 404) {
return { status: 'already_gone', reason };
}
throw error;
}
}
export async function deleteStockItem(store, uuidB64) {
+3 -1
View File
@@ -1,5 +1,5 @@
export const APP_NAME = 'Lonc';
export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.2.2';
export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.2.6';
export const TRYTON_APPLICATION = 'kitchen';
export const CONNECTION_STATES = {
@@ -27,12 +27,14 @@ export const API_PATHS = {
kitchens: 'kitchen/kitchens',
items: 'kitchen/items',
locations: 'kitchen/locations',
categories: 'kitchen/categories',
changes: 'kitchen/changes',
};
export const ROUTES = {
login: '/login',
home: '/',
scan: '/scan',
stock: '/stock',
stockNew: '/stock/new',
stockDetail: '/stock/:id',
+15 -5
View File
@@ -6,10 +6,12 @@ import { renderLabelCreatePage } from '../features/labels/label-create-page.js';
import { renderSettingsPage } from '../features/auth/settings-page.js';
import { renderStockDetailPage } from '../features/stock/stock-detail-page.js';
import { renderStockListPage } from '../features/stock/stock-list-page.js';
import { renderStockScanPage } from '../features/stock/stock-scan-page.js';
const routeDefinitions = [
{ path: ROUTES.login, render: renderLoginPage, protected: false },
{ path: ROUTES.home, render: renderDashboardPage, protected: true },
{ path: ROUTES.scan, render: renderStockScanPage, protected: true },
{ path: ROUTES.stock, render: renderStockListPage, protected: true },
{ path: ROUTES.stockNew, render: renderLabelCreatePage, protected: true },
{ path: ROUTES.stockDetail, render: renderStockDetailPage, protected: true },
@@ -17,9 +19,13 @@ const routeDefinitions = [
{ path: ROUTES.settings, render: renderSettingsPage, protected: false },
];
function normalizeHashRoute() {
function parseHashRoute() {
const route = window.location.hash.replace(/^#/, '') || ROUTES.home;
return route.startsWith('/') ? route : `/${route}`;
const normalized = route.startsWith('/') ? route : `/${route}`;
const [pathnameRaw, search = ''] = normalized.split('?');
const pathname = pathnameRaw || ROUTES.home;
const query = Object.fromEntries(new URLSearchParams(search).entries());
return { pathname, query };
}
function matchRoute(pathname) {
@@ -52,12 +58,12 @@ export function navigate(path) {
}
export function getRouteContext() {
return window.__loncRouteContext || { path: ROUTES.home, params: {} };
return window.__loncRouteContext || { path: ROUTES.home, params: {}, query: {} };
}
export function createRouter({ Alpine, store, outlet }) {
const render = async () => {
const pathname = normalizeHashRoute();
const { pathname, query } = parseHashRoute();
const match = matchRoute(pathname);
if (!match) {
@@ -81,7 +87,11 @@ export function createRouter({ Alpine, store, outlet }) {
return;
}
window.__loncRouteContext = { path: pathname, params: match.params };
window.__loncRouteContext = {
path: pathname,
params: match.params,
query,
};
outlet.innerHTML = match.render();
Alpine.initTree(outlet);
};
+3
View File
@@ -17,6 +17,9 @@ export function navBar(appName) {
<li class="nav-item" x-show="$store.app.session?.state === 'connected'">
<a class="nav-link" href="#/labels/new">New Label</a>
</li>
<li class="nav-item" x-show="$store.app.session?.state === 'connected'">
<a class="nav-link" href="#/scan">Scan</a>
</li>
<li class="nav-item" x-show="$store.app.session?.state === 'connected'">
<a class="nav-link" href="#/stock">Stock</a>
</li>
+17 -5
View File
@@ -15,6 +15,7 @@ export function renderDashboardPage() {
</p>
<div class="d-flex flex-wrap gap-2">
<a href="#/labels/new" class="btn btn-primary btn-lg">Create label</a>
<a href="#/scan" class="btn btn-outline-primary btn-lg">Scan item</a>
<a href="#/stock" class="btn btn-outline-primary btn-lg">Browse stock</a>
</div>
</div>
@@ -70,10 +71,10 @@ export function renderDashboardPage() {
</a>
</div>
<div class="col-12 col-md-6 col-xl-3">
<a class="quick-card" href="#/stock">
<span class="quick-card-label">Adjustments</span>
<strong>Fast quantity updates</strong>
<span class="text-body-secondary">Apply increments, decrements, or exact counts with clear feedback.</span>
<a class="quick-card" href="#/scan">
<span class="quick-card-label">Scanning</span>
<strong>Use, spoil, or inspect</strong>
<span class="text-body-secondary">Scan a label or barcode and act on the matching item.</span>
</a>
</div>
<div class="col-12 col-md-6 col-xl-3">
@@ -165,7 +166,18 @@ export function dashboardPageData(store) {
if (missingItemUuids.length) {
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) => {
+380 -144
View File
@@ -1,10 +1,10 @@
import {
applyItemUpsert,
getStockEntry,
lookupItemByIdentifier,
previewItemUpsert,
searchItemDefinitions,
} from '../../api/stock.js';
import { BrowserMultiFormatReader } from '@zxing/browser';
import { mapLookupItemToForm } from './identifier-lookup-mapper.js';
import { fetchLocations } from '../../api/locations.js';
import {
@@ -15,6 +15,16 @@ import {
import { STORAGE_KEYS } from '../../app/config.js';
import { debounce, normalizeValidationError } from '../shared/form-utils.js';
import { loadStoredValue, saveStoredValue } from '../shared/storage.js';
import { renderScannerModal } from '../shared/scanner-modal.js';
import {
canUseCameraScanner,
createScannerReader,
normalizeIdentifierCode,
parseKitchenScanPayload,
normalizeScannerError,
startCameraScanner,
stopCameraScanner,
} from '../shared/scanner.js';
import { createAsyncState, runAsyncState } from '../shared/ui-state.js';
const STOCK_TYPE_OPTIONS = [
@@ -34,8 +44,42 @@ const STOCK_LEVEL_OPTIONS = [
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 LABEL_DRAFT_STALE_MS = 30 * 60 * 1000;
const SCANNER_ACTION_OPTIONS = [
{
key: 'lookup',
label: 'Lookup',
description: 'Lookup identifier data and prefill the label form.',
},
{
key: 'create',
label: 'Create',
description: 'Lookup data and create label immediately when required fields are complete.',
},
{
key: 'create_print',
label: 'Create & print',
description: 'Lookup data, create label, and print when required fields are complete.',
},
];
export function renderLabelCreatePage() {
const scannerOptionsMarkup = `
<div class="scan-label-mode-list mb-3">
<template x-for="action in scannerActionOptions" :key="'label-scanner-' + action.key">
<button
class="btn btn-sm scan-label-mode-btn"
type="button"
:class="scannerAction === action.key ? 'scan-label-mode-btn-active' : 'btn-outline-secondary'"
@click="scannerAction = action.key"
>
<span x-text="action.label"></span>
</button>
</template>
</div>
<div class="small text-body-secondary mb-3" x-text="activeScannerActionDescription()"></div>
`;
return `
<section class="container-xxl py-4 py-lg-5" x-data="labelCreatePage()" x-init="init()">
<div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-end mb-4">
@@ -120,7 +164,7 @@ export function renderLabelCreatePage() {
</button>
</div>
<div class="form-text">
Optional. Scan with camera or enter manually.
Optional. Scan with camera, use a hardware scanner, or enter manually.
</div>
<template x-if="lookupState.error">
<div class="small text-danger mt-1" x-text="lookupState.error"></div>
@@ -467,7 +511,19 @@ export function renderLabelCreatePage() {
</template>
<template x-if="printIssue">
<div class="alert alert-warning mb-0 py-2" x-text="printIssue"></div>
<div class="alert alert-warning mb-0 py-2 d-flex flex-wrap align-items-center justify-content-between gap-2">
<span x-text="printIssue"></span>
<button
class="btn btn-sm btn-outline-secondary"
type="button"
x-show="canRetryLastLabelPrint()"
@click="retryLastLabelPrint()"
:disabled="printState.isLoading"
>
<span x-show="!printState.isLoading">Reprint label</span>
<span x-show="printState.isLoading">Printing...</span>
</button>
</div>
</template>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 label-actions-row">
@@ -521,38 +577,16 @@ export function renderLabelCreatePage() {
</div>
</div>
<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>
${renderScannerModal({
title: 'Scan barcode',
subtitle: 'Point your camera at a product barcode or kitchen DataMatrix label.',
optionsMarkup: scannerOptionsMarkup,
manualCodeModel: 'scannerManualCode',
manualSubmitAction: 'processScannerManualCode()',
manualPlaceholder: 'Scan with hardware reader or paste code',
manualHelp: 'Use this with keyboard-style barcode scanners or for manual paste.',
manualDisabledExpression: 'lookupState.isLoading || createState.isLoading || scannerState.isLoading || scannerState.isProcessing',
})}
</section>
`;
}
@@ -607,9 +641,7 @@ function createDefaultForm() {
};
}
function loadLabelDraft() {
const draft = loadStoredValue(STORAGE_KEYS.labelDraft, createDefaultForm());
function normalizeLabelDraft(draft) {
return {
...createDefaultForm(),
...draft,
@@ -638,11 +670,50 @@ 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) {
return {
previewState: createAsyncState(),
createState: createAsyncState(),
lookupState: createAsyncState(),
printState: createAsyncState(),
scannerActionOptions: SCANNER_ACTION_OPTIONS,
scannerAction: 'lookup',
scannerManualCode: '',
stockTypeOptions: STOCK_TYPE_OPTIONS,
stockLevelOptions: STOCK_LEVEL_OPTIONS,
quantityUnitOptions: QUANTITY_UNIT_OPTIONS,
@@ -661,11 +732,14 @@ export function labelCreatePageData(store) {
upsertPreview: null,
printLabelOnSave: true,
printIssue: '',
lastCreatedLabelUuidB64: '',
lastCreatedLabelName: '',
scannerReader: null,
scannerControls: null,
scannerState: {
isOpen: false,
isLoading: false,
isProcessing: false,
hasCamera: false,
error: '',
lastDetectedCode: '',
@@ -712,14 +786,10 @@ export function labelCreatePageData(store) {
this.stopScanner();
},
canUseCameraScanner() {
return Boolean(
typeof navigator !== 'undefined'
&& navigator.mediaDevices
&& typeof navigator.mediaDevices.getUserMedia === 'function',
);
return canUseCameraScanner();
},
normalizeIdentifierCode(value) {
return String(value || '').replace(/\s+/g, '').trim();
return normalizeIdentifierCode(value);
},
hasLookupIdentifierCode() {
return Boolean(this.normalizeIdentifierCode(this.form.identifierCode));
@@ -801,26 +871,16 @@ export function labelCreatePageData(store) {
return `${parts.join(' ')}.`;
},
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.';
return normalizeScannerError(error);
},
activeScannerActionDescription() {
return this.scannerActionOptions.find((action) => action.key === this.scannerAction)?.description || '';
},
async openScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
this.scannerState.isProcessing = false;
this.scannerManualCode = this.form.identifierCode || '';
this.scannerState.isOpen = true;
await this.$nextTick();
await this.startScanner();
@@ -843,45 +903,19 @@ export function labelCreatePageData(store) {
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.scannerReader = createScannerReader();
}
this.scannerControls = await this.scannerReader.decodeFromConstraints(
{
audio: false,
video: {
facingMode: { ideal: 'environment' },
},
},
const session = await startCameraScanner({
reader: this.scannerReader,
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;
}
},
);
onDetected: (code) => this.onBarcodeDetected(code),
});
this.scannerReader = session.reader;
this.scannerControls = session.controls;
} catch (error) {
this.scannerState.error = this.normalizeScannerError(error);
} finally {
@@ -889,27 +923,12 @@ export function labelCreatePageData(store) {
}
},
stopScanner() {
try {
this.scannerControls?.stop?.();
} catch {
// Ignore cleanup errors when scanner is already stopped.
}
stopCameraScanner({
reader: this.scannerReader,
controls: this.scannerControls,
videoElement: this.$refs.scannerVideo,
});
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();
@@ -917,32 +936,41 @@ export function labelCreatePageData(store) {
this.scannerState.isLoading = false;
this.scannerState.error = '';
},
onBarcodeDetected(rawCode) {
const code = this.normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen) {
return;
async resolveIdentifierCodeFromScan(rawCode) {
const parsed = parseKitchenScanPayload(rawCode);
if (parsed.type === 'empty' || parsed.type === 'unknown') {
return {
identifierCode: '',
message: 'Scanned code could not be interpreted.',
level: 'warning',
};
}
this.form.identifierCode = code;
this.scannerState.lastDetectedCode = code;
this.closeScanner();
store.addAlert({
type: 'success',
message: `Scanned identifier code: ${code}`,
});
if (parsed.type === 'item') {
const item = await getStockEntry(store, parsed.uuidB64, { allowInactive: true });
const itemIdentifierCode = this.normalizeIdentifierCode(item?.identifier_code);
if (!itemIdentifierCode) {
return {
identifierCode: '',
message: `${item?.name || 'Scanned item'} has no identifier code. Add one first, then scan again.`,
level: 'info',
};
}
return {
identifierCode: itemIdentifierCode,
message: `Resolved identifier ${itemIdentifierCode} from ${item?.name || 'scanned item'}.`,
level: 'success',
};
}
return {
identifierCode: this.normalizeIdentifierCode(parsed.identifierCode),
message: '',
level: 'success',
};
},
async lookupIdentifierDetails() {
const identifierCode = this.normalizeIdentifierCode(this.form.identifierCode);
this.form.identifierCode = identifierCode;
this.lookupState.error = '';
if (!identifierCode) {
this.lookupState.error = 'Provide an identifier code before lookup.';
return;
}
await runAsyncState(this.lookupState, async () => {
const response = await lookupItemByIdentifier(store, identifierCode);
applyLookupResult(response, identifierCode, { announceSuccess = true } = {}) {
if (response.status !== 'ok') {
const message = this.lookupStatusMessageWithDetails(response, identifierCode);
this.lookupState.error = message;
@@ -950,7 +978,7 @@ export function labelCreatePageData(store) {
type: response.status === 'not_found' ? 'info' : 'warning',
message,
});
return;
return false;
}
if (!response.item || typeof response.item !== 'object') {
@@ -960,7 +988,7 @@ export function labelCreatePageData(store) {
type: 'warning',
message,
});
return;
return false;
}
const mapped = mapLookupItemToForm({
@@ -976,7 +1004,7 @@ export function labelCreatePageData(store) {
type: 'info',
message,
});
return;
return false;
}
this.form = {
@@ -1001,10 +1029,214 @@ export function labelCreatePageData(store) {
this.suggestions = [];
this.persistDraft();
if (announceSuccess) {
store.addAlert({
type: 'success',
message: this.lookupSuccessMessage(response),
});
}
return true;
},
async lookupIdentifierDetailsByCode(identifierCode, { announceSuccess = true } = {}) {
const normalizedCode = this.normalizeIdentifierCode(identifierCode);
this.form.identifierCode = normalizedCode;
this.lookupState.error = '';
if (!normalizedCode) {
this.lookupState.error = 'Provide an identifier code before lookup.';
return false;
}
const response = await lookupItemByIdentifier(store, normalizedCode);
return this.applyLookupResult(response, normalizedCode, { announceSuccess });
},
canAutoCreateFromForm() {
if (!String(this.form.name || '').trim()) {
return false;
}
if (!this.form.productionDate) {
return false;
}
if (!this.selectedLocation?.uuid_b64) {
return false;
}
if (this.form.stockType === 'measured') {
const quantity = Number(this.form.quantity);
if (Number.isNaN(quantity) || quantity <= 0) {
return false;
}
}
return true;
},
async createFromScannerAction({ shouldPrint = false } = {}) {
const entry = await applyItemUpsert(store, this.buildUpsertPayload());
const entryName = entry.item?.name || this.form.name;
const operationVerb = entry.operation === 'update' ? 'updated' : 'created';
const createdUuidB64 = entry.item?.uuid_b64 || null;
this.lastCreatedLabelUuidB64 = createdUuidB64 || '';
this.lastCreatedLabelName = entryName;
this.successMessage = `${entryName} was ${operationVerb} successfully.`;
this.upsertPreview = entry;
saveLabelDraft(this.form);
if (shouldPrint) {
if (!createdUuidB64) {
const message = `${entryName} was ${operationVerb}, but label printing is unavailable for this entry.`;
this.printIssue = message;
store.addAlert({
type: 'warning',
message,
});
return true;
}
try {
await printItemLabel(store, createdUuidB64);
const message = `${entryName} was ${operationVerb} and printed. Ready for next scan.`;
store.addAlert({
type: 'success',
message,
});
void this.openScanner().catch(() => {});
} catch (printError) {
const parsedPrintMessage = formatPrintErrorMessage(printError);
this.printIssue = `${entryName} was ${operationVerb}, but printing failed: ${parsedPrintMessage}`;
store.addAlert({
type: 'warning',
message: this.printIssue,
});
}
return true;
}
const message = `${entryName} was ${operationVerb}. Ready for next scan.`;
store.addAlert({
type: 'success',
message,
});
void this.openScanner().catch(() => {});
return true;
},
canRetryLastLabelPrint() {
return Boolean(this.lastCreatedLabelUuidB64);
},
async retryLastLabelPrint() {
if (!this.canRetryLastLabelPrint()) {
return;
}
await runAsyncState(this.printState, async () => {
await printItemLabel(store, this.lastCreatedLabelUuidB64);
this.printIssue = '';
store.addAlert({
type: 'success',
message: `${this.lastCreatedLabelName || 'Label'} sent to printer.`,
});
}).catch((printError) => {
const parsedPrintMessage = formatPrintErrorMessage(printError);
const itemName = this.lastCreatedLabelName || 'Label';
this.printIssue = `Could not print ${itemName}: ${parsedPrintMessage}`;
});
},
async runScannerActionForCode(rawCode) {
try {
const resolved = await this.resolveIdentifierCodeFromScan(rawCode);
if (!resolved.identifierCode) {
store.addAlert({
type: resolved.level || 'warning',
message: resolved.message || 'Scanned code could not be used for lookup.',
});
return;
}
this.form.identifierCode = resolved.identifierCode;
if (resolved.message) {
store.addAlert({
type: resolved.level || 'info',
message: resolved.message,
});
}
const didLookupApply = await this.lookupIdentifierDetailsByCode(resolved.identifierCode, {
announceSuccess: this.scannerAction === 'lookup',
});
if (!didLookupApply) {
return;
}
if (this.scannerAction === 'lookup') {
return;
}
if (!this.canAutoCreateFromForm()) {
const message = 'Lookup filled part of the form. Complete required fields, then save or print.';
this.lookupState.error = message;
store.addAlert({
type: 'info',
message,
});
return;
}
this.submitError = '';
this.fieldErrors = {};
this.printIssue = '';
await runAsyncState(this.createState, async () => {
await this.createFromScannerAction({
shouldPrint: this.scannerAction === 'create_print',
});
}).catch((error) => {
this.fieldErrors = normalizeValidationError(error);
this.submitError = error.message || 'Could not create from scanned lookup.';
});
} catch (error) {
store.addAlert({
type: 'warning',
message: `Scanner action failed: ${error.message || 'Unknown error.'}`,
});
}
},
processScannerManualCode() {
const code = this.normalizeIdentifierCode(this.scannerManualCode);
if (!code) {
this.scannerState.error = 'Scan or enter a code first.';
return;
}
this.scannerState.lastDetectedCode = code;
this.scannerState.isProcessing = true;
this.closeScanner();
this.runScannerActionForCode(code).finally(() => {
this.scannerState.isProcessing = false;
});
},
onBarcodeDetected(rawCode) {
const code = this.normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen || this.scannerState.isProcessing) {
return;
}
this.scannerState.lastDetectedCode = code;
this.scannerManualCode = code;
this.scannerState.isProcessing = true;
this.closeScanner();
this.runScannerActionForCode(rawCode).finally(() => {
this.scannerState.isProcessing = false;
});
},
async lookupIdentifierDetails() {
const identifierCode = this.normalizeIdentifierCode(this.form.identifierCode);
this.form.identifierCode = identifierCode;
this.lookupState.error = '';
if (!identifierCode) {
this.lookupState.error = 'Provide an identifier code before lookup.';
return;
}
await runAsyncState(this.lookupState, async () => {
await this.lookupIdentifierDetailsByCode(identifierCode, { announceSuccess: true });
}).catch((error) => {
store.addAlert({
type: 'warning',
@@ -1084,7 +1316,7 @@ export function labelCreatePageData(store) {
this.persistDraft();
},
persistDraft() {
saveStoredValue(STORAGE_KEYS.labelDraft, buildDraftPayload(this.form));
saveLabelDraft(this.form);
},
get filteredLocations() {
const query = this.locationSearch.trim().toLowerCase();
@@ -1467,16 +1699,18 @@ export function labelCreatePageData(store) {
const entryName = entry.item?.name || this.form.name;
const operationVerb = entry.operation === 'update' ? 'updated' : 'created';
const createdUuidB64 = entry.item?.uuid_b64 || null;
this.lastCreatedLabelUuidB64 = createdUuidB64 || '';
this.lastCreatedLabelName = entryName;
if (this.printLabelOnSave && createdUuidB64) {
try {
await printItemLabel(store, createdUuidB64);
} catch (printError) {
const parsedPrintMessage = formatPrintErrorMessage(printError);
this.printIssue = parsedPrintMessage;
this.printIssue = `${entryName} was ${operationVerb}, but printing failed: ${parsedPrintMessage}`;
store.addAlert({
type: 'warning',
message: `${entryName} was ${operationVerb}, but printing has an issue: ${parsedPrintMessage}`,
message: this.printIssue,
});
}
}
@@ -1487,7 +1721,7 @@ export function labelCreatePageData(store) {
message: `${entryName} was ${operationVerb} successfully.`,
});
this.upsertPreview = entry;
saveStoredValue(STORAGE_KEYS.labelDraft, buildDraftPayload(this.form));
saveLabelDraft(this.form);
} catch (error) {
this.fieldErrors = normalizeValidationError(error);
this.submitError = error.message;
@@ -1508,7 +1742,9 @@ export function labelCreatePageData(store) {
this.fieldErrors = {};
this.upsertPreview = null;
this.printIssue = '';
saveStoredValue(STORAGE_KEYS.labelDraft, this.form);
this.lastCreatedLabelUuidB64 = '';
this.lastCreatedLabelName = '';
saveLabelDraft(this.form);
if (revokePreview && this.previewUrl.startsWith('blob:')) {
URL.revokeObjectURL(this.previewUrl);
}
+2
View File
@@ -6,6 +6,7 @@ import { kitchenSelectorData } from './kitchens/kitchen-selector.js';
import { labelCreatePageData } from './labels/label-create-page.js';
import { stockDetailPageData } from './stock/stock-detail-page.js';
import { stockListPageData } from './stock/stock-list-page.js';
import { stockScanPageData } from './stock/stock-scan-page.js';
export function registerFeatureData(Alpine, store) {
Alpine.data('alertsData', () => alertsData(store));
@@ -14,6 +15,7 @@ export function registerFeatureData(Alpine, store) {
Alpine.data('dashboardPage', () => dashboardPageData(store));
Alpine.data('kitchenSelector', () => kitchenSelectorData(store));
Alpine.data('labelCreatePage', () => labelCreatePageData(store));
Alpine.data('stockScanPage', () => stockScanPageData(store));
Alpine.data('stockListPage', () => stockListPageData(store));
Alpine.data('stockDetailPage', () => stockDetailPageData(store));
}
+65
View File
@@ -0,0 +1,65 @@
export function renderScannerModal({
title = 'Scan barcode',
subtitle = 'Point your camera at the barcode.',
optionsMarkup = '',
manualCodeModel = 'scannerManualCode',
manualSubmitAction = 'processScannerManualCode()',
manualPlaceholder = 'Scan with hardware reader or paste code',
manualHelp = 'Manual entry works with keyboard-style barcode scanners.',
manualButtonLabel = 'Run',
manualDisabledExpression = 'scannerState.isLoading',
}) {
return `
<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">${title}</h2>
<p class="text-body-secondary small mb-0">${subtitle}</p>
</div>
<button class="btn btn-sm btn-outline-secondary" type="button" @click="closeScanner()">Close</button>
</div>
${optionsMarkup}
<form class="mb-3" @submit.prevent="${manualSubmitAction}">
<label class="form-label">Manual scan code</label>
<div class="input-group">
<input
class="form-control"
type="text"
x-model="${manualCodeModel}"
placeholder="${manualPlaceholder}"
autocomplete="off"
/>
<button class="btn btn-outline-primary" type="submit" :disabled="${manualDisabledExpression}">
${manualButtonLabel}
</button>
</div>
<div class="form-text">${manualHelp}</div>
</form>
<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>
`;
}
+151
View File
@@ -0,0 +1,151 @@
import {
BarcodeFormat,
BrowserMultiFormatReader,
} from '@zxing/browser';
import { DecodeHintType } from '@zxing/library';
const KITCHEN_ITEM_PREFIX = 'kitchen:item::';
const UUID_B64_PATTERN = /^[A-Za-z0-9_-]{22}$/;
const UUID_B64_WITH_PADDING_PATTERN = /^[A-Za-z0-9_-]{22}={0,2}$/;
const SCANNER_FORMATS = [
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.EAN_13,
BarcodeFormat.EAN_8,
BarcodeFormat.UPC_A,
BarcodeFormat.UPC_E,
BarcodeFormat.CODE_128,
BarcodeFormat.CODE_39,
BarcodeFormat.QR_CODE,
];
export function normalizeIdentifierCode(value) {
return String(value || '').replace(/\s+/g, '').trim();
}
export function parseKitchenScanPayload(rawValue) {
const value = normalizeIdentifierCode(rawValue);
if (!value) {
return { type: 'empty', raw: '' };
}
if (value.toLowerCase().startsWith(KITCHEN_ITEM_PREFIX)) {
const uuidB64 = value.slice(KITCHEN_ITEM_PREFIX.length).trim();
return uuidB64
? { type: 'item', uuidB64, raw: value }
: { type: 'unknown', raw: value };
}
// Backward compatibility: some labels/scanners provide the raw base64 UUID only.
if (UUID_B64_PATTERN.test(value) || UUID_B64_WITH_PADDING_PATTERN.test(value)) {
return {
type: 'item',
uuidB64: value.replace(/=+$/g, ''),
raw: value,
};
}
return { type: 'identifier', identifierCode: value, raw: value };
}
export function canUseCameraScanner() {
return Boolean(
typeof navigator !== 'undefined'
&& navigator.mediaDevices
&& typeof navigator.mediaDevices.getUserMedia === 'function',
);
}
export function createScannerReader() {
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, SCANNER_FORMATS);
return new BrowserMultiFormatReader(hints);
}
export 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 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 scanning. Enter the code manually.';
}
export async function startCameraScanner({
reader,
videoElement,
onDetected,
onDecodeError,
}) {
const activeReader = reader || createScannerReader();
const shouldLogDecodeErrors = import.meta.env.DEV;
let lastDecodeErrorName = '';
let lastDecodeErrorAt = 0;
const controls = await activeReader.decodeFromConstraints(
{
audio: false,
video: {
facingMode: { ideal: 'environment' },
},
},
videoElement,
(result, error) => {
if (result) {
onDetected?.(result.getText?.() || '');
return;
}
if (!error) {
return;
}
onDecodeError?.(error);
if (!shouldLogDecodeErrors) {
return;
}
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 { reader: activeReader, controls };
}
export function stopCameraScanner({ reader, controls, videoElement }) {
try {
controls?.stop?.();
} catch {
// Ignore cleanup errors when scanner is already stopped.
}
try {
reader?.reset?.();
} catch {
// Ignore cleanup errors from stale reader state.
}
const stream = videoElement?.srcObject;
if (stream && typeof stream.getTracks === 'function') {
stream.getTracks().forEach((track) => track.stop());
}
if (videoElement) {
videoElement.srcObject = null;
}
}
+77
View File
@@ -0,0 +1,77 @@
const LEVEL_TO_FACTOR = {
plenty: 0.75,
good: 0.50,
some: 0.25,
low: 0.10,
trace: 0.05,
gone: 0,
};
function levelFromRatio(ratio) {
if (ratio <= 0) {
return 'gone';
}
if (ratio >= 0.75) {
return 'plenty';
}
if (ratio >= 0.50) {
return 'good';
}
if (ratio >= 0.25) {
return 'some';
}
if (ratio >= 0.10) {
return 'low';
}
return 'trace';
}
export function buildGoneStockPayload(reason = 'consumed') {
return {
level: 'gone',
gone_reason: reason,
};
}
export function buildConsumeOneStockPayload(item) {
if (!item || item.active === false) {
return buildGoneStockPayload('consumed');
}
if (item.stock_type === 'binary') {
return buildGoneStockPayload('consumed');
}
const currentQuantity = Number(item.quantity || 0);
const nextQuantity = Math.max(currentQuantity - 1, 0);
if (item.stock_type === 'measured') {
return nextQuantity <= 0
? { quantity: 0, level: 'gone', gone_reason: 'consumed' }
: { quantity: nextQuantity };
}
if (item.stock_type === 'descriptive') {
const initialQuantity = Number(item.quantity_initial || 0);
if (!initialQuantity) {
return buildGoneStockPayload('consumed');
}
const nextLevel = levelFromRatio(nextQuantity / initialQuantity);
return nextLevel === 'gone'
? buildGoneStockPayload('consumed')
: { level: nextLevel };
}
const currentLevel = item.level || 'plenty';
const currentFactor = LEVEL_TO_FACTOR[currentLevel] ?? 1;
const initialQuantity = Number(item.quantity_initial || item.quantity || 1);
const estimatedQuantity = currentQuantity || currentFactor * initialQuantity;
const nextLevel = levelFromRatio(Math.max(estimatedQuantity - 1, 0) / initialQuantity);
return nextLevel === 'gone'
? buildGoneStockPayload('consumed')
: { level: nextLevel };
}
export function isGonePayload(payload) {
return payload?.level === 'gone' || Number(payload?.quantity) <= 0;
}
+281 -130
View File
@@ -1,14 +1,25 @@
import {
adjustStockEntry,
getStockEntry,
listStockEvents,
lookupItemDetails,
markStockGone,
patchStockItem,
useStockItem,
} from '../../api/stock.js';
import { BrowserMultiFormatReader } from '@zxing/browser';
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
import { fetchLocations } from '../../api/locations.js';
import { listCategories } from '../../api/categories.js';
import { getRouteContext } from '../../app/router.js';
import { renderScannerModal } from '../shared/scanner-modal.js';
import {
canUseCameraScanner,
createScannerReader,
normalizeIdentifierCode,
normalizeScannerError,
parseKitchenScanPayload,
startCameraScanner,
stopCameraScanner,
} from '../shared/scanner.js';
import { createAsyncState, runAsyncState } from '../shared/ui-state.js';
import { formatDate } from '../shared/date-utils.js';
@@ -30,10 +41,6 @@ function parseDateValue(value) {
return new Date(year, month - 1, day);
}
function normalizeIdentifierCode(value) {
return String(value || '').replace(/\s+/g, '').trim();
}
function expirationInfo(entry) {
if (!entry?.expire_date) {
return {
@@ -95,7 +102,7 @@ export function renderStockDetailPage() {
<section class="container-xxl py-4 py-lg-5" x-data="stockDetailPage()" x-init="init()">
<div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-center mb-4">
<div>
<a href="#/stock" class="link-secondary text-decoration-none small">&larr; Back to stock</a>
<a :href="backHref" class="link-secondary text-decoration-none small">&larr; <span x-text="backLabel"></span></a>
<h1 class="h3 mb-1 mt-2">Stock detail</h1>
<p class="text-body-secondary mb-0">Inspect the entry and update its quantity without leaving the workflow.</p>
</div>
@@ -139,6 +146,21 @@ export function renderStockDetailPage() {
</dd>
<dt class="col-5">Stock type</dt>
<dd class="col-7" x-text="entry.stock_type || 'Stored'"></dd>
<dt class="col-5">Main category</dt>
<dd class="col-7" x-text="mainCategoryLabel(entry) || 'Not set'"></dd>
<dt class="col-5">Categories</dt>
<dd class="col-7">
<template x-if="categoryLabels(entry).length">
<div class="d-flex flex-wrap gap-1">
<template x-for="label in categoryLabels(entry)" :key="label">
<span class="badge text-bg-light border" x-text="label"></span>
</template>
</div>
</template>
<template x-if="!categoryLabels(entry).length">
<span class="text-body-secondary">Uncategorized</span>
</template>
</dd>
</dl>
<div class="mt-4">
@@ -283,8 +305,12 @@ export function renderStockDetailPage() {
<span x-show="!printState.isLoading">Print label</span>
<span x-show="printState.isLoading">Printing...</span>
</button>
<button class="btn btn-outline-danger" type="button" @click="markGone()" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark gone</span>
<button class="btn btn-outline-danger" type="button" @click="markGone('consumed')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark used</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
<button class="btn btn-outline-danger" type="button" @click="markGone('spoiled')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Spoilt</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
</div>
@@ -325,8 +351,12 @@ export function renderStockDetailPage() {
<span x-show="!printState.isLoading">Print label</span>
<span x-show="printState.isLoading">Printing...</span>
</button>
<button class="btn btn-outline-danger" type="button" @click="markGone()" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark gone</span>
<button class="btn btn-outline-danger" type="button" @click="markGone('consumed')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark used</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
<button class="btn btn-outline-danger" type="button" @click="markGone('spoiled')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Spoilt</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
</div>
@@ -336,7 +366,7 @@ export function renderStockDetailPage() {
<template x-if="entry.stock_type === 'binary'">
<div class="vstack gap-3">
<p class="text-body-secondary mb-0">
Binary stock items can be marked gone from this screen.
Binary stock items can be marked used or spoilt from this screen.
</p>
<template x-if="adjustmentState.error">
@@ -350,54 +380,71 @@ export function renderStockDetailPage() {
></div>
</template>
<button class="btn btn-outline-danger align-self-start" type="button" @click="markGone()" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark gone</span>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-outline-danger" type="button" @click="markGone('consumed')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark used</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
<button class="btn btn-outline-secondary align-self-start" type="button" @click="printLabel()" :disabled="printState.isLoading">
<button class="btn btn-outline-danger" type="button" @click="markGone('spoiled')" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Spoilt</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
<button class="btn btn-outline-secondary" type="button" @click="printLabel()" :disabled="printState.isLoading">
<span x-show="!printState.isLoading">Print label</span>
<span x-show="printState.isLoading">Printing...</span>
</button>
</div>
</template>
</div>
</div>
</div>
</div>
</template>
</div>
</div>
<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 class="card border-0 shadow-sm mt-4">
<div class="card-body p-4">
<div class="d-flex justify-content-between align-items-center gap-2 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>
<p class="eyebrow mb-2">History</p>
<h2 class="h5 mb-0">Recent stock events</h2>
</div>
<button class="btn btn-sm btn-outline-secondary" type="button" @click="closeScanner()">Close</button>
<button class="btn btn-sm btn-outline-secondary" type="button" @click="loadStockHistory()" :disabled="stockHistoryState.isLoading">
<span x-show="!stockHistoryState.isLoading">Refresh</span>
<span x-show="stockHistoryState.isLoading">Refreshing...</span>
</button>
</div>
<div class="scanner-video-shell mb-3">
<video class="scanner-video" x-ref="scannerVideo" autoplay muted playsinline></video>
<template x-if="stockHistoryState.error">
<div class="alert alert-warning py-2" x-text="stockHistoryState.error"></div>
</template>
<template x-if="!stockHistoryState.error && !stockEvents.length">
<div class="text-body-secondary small">No stock events yet.</div>
</template>
<template x-if="stockEvents.length">
<div class="list-group list-group-flush">
<template x-for="event in stockEvents" :key="event.id">
<div class="list-group-item px-0">
<div class="d-flex justify-content-between gap-2">
<div class="fw-semibold" x-text="stockEventLabel(event)"></div>
<div class="small text-body-secondary" x-text="formatDate(event.date)"></div>
</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 class="small text-body-secondary" x-text="stockEventDetail(event)"></div>
</div>
</template>
</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>
</div>
</template>
${renderScannerModal({
title: 'Scan barcode',
subtitle: 'Point your camera at a product barcode or kitchen DataMatrix label.',
manualCodeModel: 'scannerManualCode',
manualSubmitAction: 'processScannerManualCode()',
manualPlaceholder: 'Scan with hardware reader or paste code',
manualHelp: 'Use this with keyboard-style barcode scanners or manual entry.',
manualDisabledExpression: 'identifierState.isLoading || scannerState.isLoading || scannerState.isProcessing',
})}
</section>
`;
}
@@ -408,11 +455,13 @@ export function stockDetailPageData(store) {
adjustmentState: createAsyncState(),
printState: createAsyncState(),
identifierState: createAsyncState(),
stockHistoryState: createAsyncState(),
scannerReader: null,
scannerControls: null,
scannerState: {
isOpen: false,
isLoading: false,
isProcessing: false,
hasCamera: false,
error: '',
lastDetectedCode: '',
@@ -426,9 +475,14 @@ export function stockDetailPageData(store) {
type: '',
message: '',
},
backHref: '#/stock',
backLabel: 'Back to stock',
entry: null,
stockEvents: [],
locationPathByUuid: {},
categoriesById: {},
identifierDraft: '',
scannerManualCode: '',
adjustment: {
mode: 'increment',
quantity: '1',
@@ -436,15 +490,21 @@ export function stockDetailPageData(store) {
},
async init() {
this.scannerState.hasCamera = this.canUseCameraScanner();
const routeContext = getRouteContext();
if (routeContext?.query?.from === 'scan') {
this.backHref = '#/scan';
this.backLabel = 'Back to scan';
}
if (!store.isConnected) {
return;
}
const { params } = getRouteContext();
await runAsyncState(this.state, async () => {
const [entry, locations] = await Promise.all([
const [entry, locations, categories] = await Promise.all([
getStockEntry(store, params.id),
fetchLocations(store).catch(() => ({ flat: [] })),
listCategories(store, { expanded: true }).catch(() => []),
]);
this.entry = entry;
this.identifierDraft = normalizeIdentifierCode(entry?.identifier_code);
@@ -453,40 +513,29 @@ export function stockDetailPageData(store) {
.filter((location) => location.uuid_b64)
.map((location) => [location.uuid_b64, location.pathLabel || location.name]),
);
this.categoriesById = Object.fromEntries(
categories
.filter((category) => category?.id !== undefined && category?.id !== null)
.map((category) => [String(category.id), category]),
);
this.adjustment.level = this.entry?.level || 'plenty';
}).catch(() => {});
this.loadStockHistory().catch(() => {});
},
destroy() {
this.stopScanner();
},
canUseCameraScanner() {
return Boolean(
typeof navigator !== 'undefined'
&& navigator.mediaDevices
&& typeof navigator.mediaDevices.getUserMedia === 'function',
);
return canUseCameraScanner();
},
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.';
return normalizeScannerError(error);
},
async openScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
this.scannerState.isProcessing = false;
this.scannerManualCode = normalizeIdentifierCode(this.identifierDraft);
this.scannerState.isOpen = true;
await this.$nextTick();
await this.startScanner();
@@ -509,45 +558,19 @@ export function stockDetailPageData(store) {
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.scannerReader = createScannerReader();
}
this.scannerControls = await this.scannerReader.decodeFromConstraints(
{
audio: false,
video: {
facingMode: { ideal: 'environment' },
},
},
const session = await startCameraScanner({
reader: this.scannerReader,
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;
}
},
);
onDetected: (code) => this.onBarcodeDetected(code),
});
this.scannerReader = session.reader;
this.scannerControls = session.controls;
} catch (error) {
this.scannerState.error = this.normalizeScannerError(error);
} finally {
@@ -555,27 +578,12 @@ export function stockDetailPageData(store) {
}
},
stopScanner() {
try {
this.scannerControls?.stop?.();
} catch {
// Ignore cleanup errors when scanner is already stopped.
}
stopCameraScanner({
reader: this.scannerReader,
controls: this.scannerControls,
videoElement: this.$refs.scannerVideo,
});
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();
@@ -583,18 +591,75 @@ export function stockDetailPageData(store) {
this.scannerState.isLoading = false;
this.scannerState.error = '';
},
onBarcodeDetected(rawCode) {
const code = normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen) {
async applyScannedCode(rawCode) {
const parsed = parseKitchenScanPayload(rawCode);
if (parsed.type === 'empty' || parsed.type === 'unknown') {
store.addAlert({
type: 'warning',
message: 'Scanned code could not be interpreted.',
});
return;
}
this.identifierDraft = code;
this.scannerState.lastDetectedCode = code;
this.closeScanner();
let identifierCode = '';
if (parsed.type === 'item') {
const scannedItem = await getStockEntry(store, parsed.uuidB64, { allowInactive: true });
identifierCode = normalizeIdentifierCode(scannedItem?.identifier_code);
if (!identifierCode) {
store.addAlert({
type: 'info',
message: `${scannedItem?.name || 'Scanned item'} has no identifier code saved.`,
});
return;
}
store.addAlert({
type: 'success',
message: `Scanned identifier code: ${code}`,
message: `Loaded identifier ${identifierCode} from ${scannedItem?.name || 'scanned item'}.`,
});
} else {
identifierCode = normalizeIdentifierCode(parsed.identifierCode);
}
if (!identifierCode) {
store.addAlert({
type: 'warning',
message: 'No identifier code found in scan.',
});
return;
}
this.identifierDraft = identifierCode;
this.scannerManualCode = identifierCode;
store.addAlert({
type: 'success',
message: `Scanned identifier code: ${identifierCode}`,
});
},
processScannerManualCode() {
const code = normalizeIdentifierCode(this.scannerManualCode);
if (!code) {
this.scannerState.error = 'Scan or enter a code first.';
return;
}
this.scannerState.lastDetectedCode = code;
this.scannerState.isProcessing = true;
this.closeScanner();
this.applyScannedCode(code).finally(() => {
this.scannerState.isProcessing = false;
});
},
onBarcodeDetected(rawCode) {
const code = normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen || this.scannerState.isProcessing) {
return;
}
this.scannerState.lastDetectedCode = code;
this.scannerManualCode = code;
this.scannerState.isProcessing = true;
this.closeScanner();
this.applyScannedCode(rawCode).finally(() => {
this.scannerState.isProcessing = false;
});
},
async saveIdentifierCode() {
@@ -761,6 +826,7 @@ export function stockDetailPageData(store) {
});
this.identifierDraft = normalizeIdentifierCode(this.entry?.identifier_code);
store.addAlert({ type: 'success', message: 'Stock quantity updated.' });
this.loadStockHistory().catch(() => {});
}).catch(() => {});
},
async submitLevelAdjustment() {
@@ -771,8 +837,13 @@ export function stockDetailPageData(store) {
await runAsyncState(this.adjustmentState, async () => {
if (this.adjustment.level === 'gone') {
const entryName = this.entry.name;
await useStockItem(store, this.entry.uuid_b64);
store.addAlert({ type: 'success', message: `${entryName} was marked gone.` });
const result = await markStockGone(store, this.entry.uuid_b64, 'consumed');
store.addAlert({
type: result.status === 'already_gone' ? 'info' : 'success',
message: result.status === 'already_gone'
? `${entryName} was already out of stock.`
: `${entryName} was marked used.`,
});
window.__loncApp.navigate('/stock');
return;
}
@@ -782,25 +853,76 @@ export function stockDetailPageData(store) {
});
this.identifierDraft = normalizeIdentifierCode(this.entry?.identifier_code);
store.addAlert({ type: 'success', message: 'Stock level updated.' });
this.loadStockHistory().catch(() => {});
}).catch(() => {});
},
async markGone() {
async markGone(reason = 'consumed') {
if (!this.entry) {
return;
}
await runAsyncState(this.adjustmentState, async () => {
const result = await useStockItem(store, this.entry.uuid_b64);
const entryName = this.entry.name;
const result = await markStockGone(store, this.entry.uuid_b64, reason);
const alreadyGone = result.status === 'already_gone';
const actionLabel = reason === 'spoiled' ? 'marked spoilt' : 'marked used';
store.addAlert({
type: alreadyGone ? 'info' : 'success',
message: alreadyGone
? `${this.entry.name} was already out of stock.`
: `${this.entry.name} was marked gone.`,
? `${entryName} was already out of stock.`
: `${entryName} was ${actionLabel}.`,
});
window.__loncApp.navigate('/stock');
}).catch(() => {});
},
async loadStockHistory() {
if (!this.entry?.uuid_b64) {
return;
}
await runAsyncState(this.stockHistoryState, async () => {
this.stockEvents = await listStockEvents(store, this.entry.uuid_b64, {
allowInactive: true,
limit: 8,
orderBy: 'date',
orderDir: 'desc',
});
}).catch(() => {});
},
goneReasonLabel(reason) {
if (reason === 'consumed') {
return 'Consumed';
}
if (reason === 'spoiled') {
return 'Spoilt';
}
if (reason === 'other') {
return 'Other removal';
}
return '';
},
stockEventLabel(event) {
if (event?.level === 'gone') {
return this.goneReasonLabel(event.gone_reason) || 'Gone';
}
if (event?.level) {
return `Level: ${event.level}`;
}
return 'Quantity updated';
},
stockEventDetail(event) {
const parts = [];
if (event?.quantity !== null && event?.quantity !== undefined) {
parts.push(`Quantity: ${event.quantity}${event.uom_symbol ? ` ${event.uom_symbol}` : ''}`);
}
if (event?.level && event.level !== 'gone') {
parts.push(`Level: ${event.level}`);
}
if (event?.gone_reason) {
parts.push(`Reason: ${this.goneReasonLabel(event.gone_reason).toLowerCase()}`);
}
return parts.join(' · ') || 'Stock event saved.';
},
async printLabel() {
if (!this.entry?.uuid_b64) {
return;
@@ -867,6 +989,35 @@ export function stockDetailPageData(store) {
return this.locationPathByUuid[locationUuid] || 'Location not resolved';
},
categoryLabel(category) {
if (!category || typeof category !== 'object') {
return '';
}
return String(category.path || category.name || '').trim();
},
mainCategoryLabel(entry) {
const categoryId = entry?.category;
if (categoryId === null || categoryId === undefined || categoryId === '') {
return '';
}
const mapped = this.categoryLabel(this.categoriesById[String(categoryId)]);
if (mapped) {
return mapped;
}
return String(categoryId).trim();
},
categoryLabels(entry) {
const categoryIds = Array.isArray(entry?.categories) ? entry.categories : [];
const labels = categoryIds.map((categoryId) => {
const mapped = this.categoryLabel(this.categoriesById[String(categoryId)]);
return mapped || String(categoryId || '').trim();
});
return [...new Set(labels.filter(Boolean))];
},
nutriScoreLabel(entry) {
const value = entry?.nutriscore_grade;
if (!value) {
+135 -36
View File
@@ -3,10 +3,11 @@ import {
listGroupedStockEntries,
listKitchenChanges,
listStockEntries,
markStockGone,
updateStockItem,
useStockItem,
} from '../../api/stock.js';
import { fetchLocations } from '../../api/locations.js';
import { listCategories } from '../../api/categories.js';
import { STORAGE_KEYS } from '../../app/config.js';
import { clearStoredValue, loadStoredValue, saveStoredValue } from '../shared/storage.js';
import { createAsyncState } from '../shared/ui-state.js';
@@ -221,13 +222,35 @@ function resolveLocationLabel(entry, locationMap) {
return locationMap[entry.location_initial_uuid_b64] || 'Location not resolved';
}
function searchBlob(entry, locationMap) {
function categoryLabel(category) {
if (!category || typeof category !== 'object') {
return '';
}
return String(category.name || category.path || '').trim();
}
function resolveMainCategoryLabel(entry, categoriesById = {}) {
const categoryId = entry?.category;
if (categoryId === null || categoryId === undefined || categoryId === '') {
return '';
}
const mapped = categoryLabel(categoriesById[String(categoryId)]);
if (mapped) {
return mapped;
}
return String(categoryId).trim();
}
function searchBlob(entry, locationMap, categoriesById = {}) {
return [
entry.name,
entry.description,
entry.level,
entry.stock_type,
resolveLocationLabel(entry, locationMap),
resolveMainCategoryLabel(entry, categoriesById),
entry.uuid_b64,
]
.filter(Boolean)
@@ -235,10 +258,10 @@ function searchBlob(entry, locationMap) {
.toLowerCase();
}
function groupSearchBlob(group, locationMap) {
function groupSearchBlob(group, locationMap, categoriesById = {}) {
return [
searchBlob(group, locationMap),
...(group.items || []).map((item) => searchBlob(item, locationMap)),
searchBlob(group, locationMap, categoriesById),
...(group.items || []).map((item) => searchBlob(item, locationMap, categoriesById)),
]
.filter(Boolean)
.join(' ')
@@ -544,6 +567,9 @@ export function renderStockListPage() {
<td>
<div class="fw-semibold" x-text="entry.name"></div>
<div class="small text-body-secondary" x-text="entry.description || 'No description'"></div>
<div class="small mt-1" x-show="mainCategoryLabel(entry)">
<span class="badge text-bg-light border" x-text="mainCategoryBadgeLabel(entry)"></span>
</div>
<div class="small font-monospace text-body-secondary" x-text="shortId(entry)"></div>
<a
class="small text-decoration-none fw-semibold"
@@ -578,7 +604,8 @@ export function renderStockListPage() {
<div class="quick-edit-stack">
<template x-if="entry.stock_type === 'binary'">
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="updateBinary(entry, 'gone')">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</template>
<template x-if="entry.stock_type === 'descriptive'">
@@ -589,14 +616,16 @@ export function renderStockListPage() {
</template>
</select>
<button class="btn btn-sm btn-primary" type="button" @click="saveLevel(entry)">Save</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry)">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</template>
<template x-if="entry.stock_type === 'measured'">
<div class="d-flex flex-wrap gap-2 align-items-center">
<input class="form-control form-control-sm quick-number" type="number" step="0.01" min="0" x-model="editForms[entry.id].quantity" />
<button class="btn btn-sm btn-primary" type="button" @click="saveQuantity(entry)">Save qty</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry)">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</template>
<template x-if="editErrors[entry.id]">
@@ -620,6 +649,9 @@ export function renderStockListPage() {
<div>
<div class="fw-semibold fs-5" x-text="entry.name"></div>
<div class="text-body-secondary small" x-text="entry.description || 'No description'"></div>
<div class="small mt-1" x-show="mainCategoryLabel(entry)">
<span class="badge text-bg-light border" x-text="mainCategoryBadgeLabel(entry)"></span>
</div>
<div class="text-body-secondary small font-monospace" x-text="shortId(entry)"></div>
<a
class="small text-decoration-none fw-semibold"
@@ -660,7 +692,8 @@ export function renderStockListPage() {
<div class="quick-edit-stack">
<template x-if="entry.stock_type === 'binary'">
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="updateBinary(entry, 'gone')">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</template>
<template x-if="entry.stock_type === 'descriptive'">
@@ -672,7 +705,8 @@ export function renderStockListPage() {
</select>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-sm btn-primary" type="button" @click="saveLevel(entry)">Save stock level</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry)">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</div>
</template>
@@ -681,7 +715,8 @@ export function renderStockListPage() {
<input class="form-control form-control-sm" type="number" step="0.01" min="0" x-model="editForms[entry.id].quantity" />
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-sm btn-primary" type="button" @click="saveQuantity(entry)">Save quantity</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry)">Mark gone</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger" type="button" :disabled="isItemRefreshing(entry)" @click="markGone(entry, 'spoiled')">Spoilt</button>
</div>
</div>
</template>
@@ -722,10 +757,16 @@ export function renderStockListPage() {
<div>
<div class="fw-semibold grouped-stock-summary-title" x-text="group.name"></div>
<div class="text-body-secondary small grouped-stock-summary-description" x-show="group.description" x-text="group.description"></div>
<div class="small mt-1" x-show="mainCategoryLabel(group)">
<span class="badge text-bg-light border" x-text="mainCategoryBadgeLabel(group)"></span>
</div>
<div class="d-flex flex-wrap small grouped-stock-summary-meta">
<span><span class="fw-semibold text-body" x-text="groupItemCount(group)"></span> item(s)</span>
<span><span class="text-body-secondary">Latest location:</span> <span class="fw-semibold text-body" x-text="locationLabel(group)"></span></span>
<span><span class="text-body-secondary">Quantity:</span> <span class="fw-semibold text-body" x-text="quantityLabel(group)"></span></span>
<span>
<span class="text-body-secondary" x-text="groupSummaryMetricLabel(group) + ':'"></span>
<span class="fw-semibold text-body" x-text="groupSummaryMetricValue(group)"></span>
</span>
</div>
</div>
<div class="grouped-stock-summary-status">
@@ -775,6 +816,12 @@ export function renderStockListPage() {
<span x-text="locationLabel(item)"></span>
<span class="grouped-stock-subline-separator" aria-hidden="true">•</span>
<span x-text="shortDescription(item.description)"></span>
<template x-if="mainCategoryLabel(item)">
<span>
<span class="grouped-stock-subline-separator" aria-hidden="true">•</span>
<span class="text-body-tertiary" x-text="'Main: ' + mainCategoryLabel(item)"></span>
</span>
</template>
</div>
</div>
<div class="small text-body-secondary grouped-stock-item-aux">
@@ -796,7 +843,8 @@ export function renderStockListPage() {
>
Details
</a>
<button class="btn btn-sm btn-outline-danger grouped-stock-mark-gone" type="button" :disabled="isItemRefreshing(item)" @click="markGoneFromGroup(item, group)">Mark gone</button>
<button class="btn btn-sm btn-outline-danger grouped-stock-mark-gone" type="button" :disabled="isItemRefreshing(item)" @click="markGoneFromGroup(item, group, 'consumed')">Mark used</button>
<button class="btn btn-sm btn-outline-danger grouped-stock-mark-gone" type="button" :disabled="isItemRefreshing(item)" @click="markGoneFromGroup(item, group, 'spoiled')">Spoilt</button>
<div class="small text-body-secondary stock-item-refresh-indicator" x-show="isItemRefreshing(item)">
Refreshing...
</div>
@@ -869,6 +917,7 @@ export function stockListPageData(store) {
locationMap: {},
locationDescendants: {},
locationLineage: {},
categoriesById: {},
editForms: {},
editErrors: {},
levelOptions: LEVEL_OPTIONS,
@@ -911,13 +960,13 @@ export function stockListPageData(store) {
: false;
if (!restoredFromRuntime) {
const initTasks = [this.loadLocations()];
const initTasks = [this.loadLocations(), this.loadCategories()];
if (this.viewMode === 'items') {
initTasks.push(this.loadEntries());
} else {
initTasks.push(
this.loadGroupedEntries({
expanded: 0,
expanded: false,
resetVisible: !restoredContext,
}),
);
@@ -930,6 +979,9 @@ export function stockListPageData(store) {
if (!restoredFromRuntime && this.viewMode === 'grouped') {
this.hydrateGroupedEntriesInBackground().catch(() => {});
}
if (restoredFromRuntime) {
this.refreshLoadedViewsInBackground().catch(() => {});
}
if (restoredFromRuntime && restoredContext?.focusedItemUuid) {
this.refreshFocusedItemInBackground(restoredContext.focusedItemUuid).catch(() => {});
}
@@ -1040,6 +1092,7 @@ export function stockListPageData(store) {
locationMap: this.locationMap,
locationDescendants: this.locationDescendants,
locationLineage: this.locationLineage,
categoriesById: this.categoriesById,
changeCursor: this.changeCursor,
}),
};
@@ -1099,6 +1152,9 @@ export function stockListPageData(store) {
this.locationLineage = payload.locationLineage && typeof payload.locationLineage === 'object'
? payload.locationLineage
: {};
this.categoriesById = payload.categoriesById && typeof payload.categoriesById === 'object'
? payload.categoriesById
: {};
this.changeCursor = payload.changeCursor || this.changeCursor;
if (this.itemsLoaded) {
@@ -1260,7 +1316,7 @@ export function stockListPageData(store) {
},
indexEntry(entry) {
const indexed = { ...entry };
indexed._searchBlob = searchBlob(indexed, this.locationMap);
indexed._searchBlob = searchBlob(indexed, this.locationMap, this.categoriesById);
return indexed;
},
indexGroup(group) {
@@ -1271,7 +1327,7 @@ export function stockListPageData(store) {
...group,
items: indexedItems,
};
indexed._searchBlob = groupSearchBlob(indexed, this.locationMap);
indexed._searchBlob = groupSearchBlob(indexed, this.locationMap, this.categoriesById);
return indexed;
},
reindexSearchData() {
@@ -1302,7 +1358,7 @@ export function stockListPageData(store) {
if (mode === 'grouped') {
if (!this.groupedLoaded) {
await this.loadGroupedEntries({ expanded: 0, resetVisible: true });
await this.loadGroupedEntries({ expanded: false, resetVisible: true });
}
this.hydrateGroupedEntriesInBackground().catch(() => {});
return;
@@ -1318,7 +1374,7 @@ export function stockListPageData(store) {
: this.itemsLoaded);
if (this.viewMode === 'grouped') {
await this.loadGroupedEntries({ expanded: 0, background: useBackground });
await this.loadGroupedEntries({ expanded: false, background: useBackground });
this.hydrateGroupedEntriesInBackground({ force: true }).catch(() => {});
return;
}
@@ -1410,7 +1466,7 @@ export function stockListPageData(store) {
this.invalidateMemo();
this.persistRuntimeCache();
},
async loadGroupedEntries({ expanded = 1, background = false, resetVisible = false } = {}) {
async loadGroupedEntries({ expanded = true, background = false, resetVisible = false } = {}) {
if (!store.isConnected) {
return;
}
@@ -1425,7 +1481,7 @@ export function stockListPageData(store) {
try {
const loadedGroups = await listGroupedStockEntries(store, { expanded });
if (expanded === 0) {
if (!expanded) {
this.applyGroupedSummary(loadedGroups, { resetVisible });
return;
}
@@ -1454,7 +1510,7 @@ export function stockListPageData(store) {
this.groupedHydrating = true;
try {
await this.loadGroupedEntries({ expanded: 1, background: true });
await this.loadGroupedEntries({ expanded: true, background: true });
} finally {
this.groupedHydrating = false;
}
@@ -1466,7 +1522,7 @@ export function stockListPageData(store) {
}
if (this.groupedLoaded) {
tasks.push(
this.loadGroupedEntries({ expanded: 0, background: true }).then(() =>
this.loadGroupedEntries({ expanded: false, background: true }).then(() =>
this.hydrateGroupedEntriesInBackground({ force: true }),
),
);
@@ -1506,6 +1562,25 @@ export function stockListPageData(store) {
this.persistRuntimeCache();
}
},
async loadCategories() {
if (!store.isConnected) {
return;
}
try {
const categories = await listCategories(store, { expanded: true });
this.categoriesById = Object.fromEntries(
categories
.filter((category) => category?.id !== undefined && category?.id !== null)
.map((category) => [String(category.id), category]),
);
} catch {
this.categoriesById = {};
} finally {
this.reindexSearchData();
this.persistRuntimeCache();
}
},
resetGroupedVisibleLimit() {
this.groupedVisibleLimit = this.groupedPageSize;
},
@@ -1519,6 +1594,28 @@ export function stockListPageData(store) {
return group.items.filter((item) => !isGroupedChildStub(item));
},
mainCategoryLabel(entry) {
return resolveMainCategoryLabel(entry, this.categoriesById);
},
mainCategoryBadgeLabel(entry) {
return `Main category: ${this.mainCategoryLabel(entry)}`;
},
groupSummaryMetricLabel(group) {
if (group?.stock_type === 'measured') {
return 'Quantity';
}
if (group?.stock_type === 'descriptive') {
return 'Stock level';
}
if (group?.stock_type === 'binary') {
return 'Stock state';
}
return 'Stock';
},
groupSummaryMetricValue(group) {
// Use backend-provided grouped fields as the single source of truth.
return quantityLabel(group);
},
hasGroupedChildStubs(group) {
if (!Array.isArray(group?.items)) {
return false;
@@ -2202,12 +2299,12 @@ export function stockListPageData(store) {
return;
}
await this.useEntry(entry);
await this.useEntry(entry, 'consumed');
},
async saveLevel(entry) {
const level = this.editForms[entry.id]?.level || 'plenty';
if (level === 'gone') {
await this.useEntry(entry);
await this.useEntry(entry, 'consumed');
return;
}
@@ -2234,14 +2331,14 @@ export function stockListPageData(store) {
{ quantity },
);
},
async markGone(entry) {
async markGone(entry, reason = 'consumed') {
if (this.isItemRefreshing(entry)) {
return;
}
await this.useEntry(entry);
await this.useEntry(entry, reason);
},
async markGoneFromGroup(item, group) {
async markGoneFromGroup(item, group, reason = 'consumed') {
if (this.isItemRefreshing(item)) {
return;
}
@@ -2249,8 +2346,9 @@ export function stockListPageData(store) {
this.editErrors[item.id] = '';
try {
const result = await useStockItem(store, item.uuid_b64);
const result = await markStockGone(store, item.uuid_b64, reason);
const alreadyGone = result.status === 'already_gone';
const actionLabel = reason === 'spoiled' ? 'marked spoilt' : 'marked used';
this.removeGroupedItem(group.id, item.id);
this.removeEntryLocally(item.id);
delete this.editForms[item.id];
@@ -2259,11 +2357,11 @@ export function stockListPageData(store) {
type: alreadyGone ? 'info' : 'success',
message: alreadyGone
? `${item.name} was already out of stock and removed from the group.`
: `${item.name} was marked gone and removed from the group.`,
: `${item.name} was ${actionLabel} and removed from the group.`,
});
this.refreshLoadedViewsInBackground().catch(() => {});
this.loadGroupedEntries({ expanded: false, background: true }).catch(() => {});
} catch (error) {
this.editErrors[item.id] = error.message || 'Mark gone failed.';
this.editErrors[item.id] = error.message || 'Removal failed.';
}
},
async saveEntryUpdate(entry, payload, localPatch) {
@@ -2281,7 +2379,7 @@ export function stockListPageData(store) {
this.editErrors[entry.id] = error.message || 'Update failed.';
}
},
async useEntry(entry) {
async useEntry(entry, reason = 'consumed') {
if (this.isItemRefreshing(entry)) {
return;
}
@@ -2289,8 +2387,9 @@ export function stockListPageData(store) {
this.editErrors[entry.id] = '';
try {
const result = await useStockItem(store, entry.uuid_b64);
const result = await markStockGone(store, entry.uuid_b64, reason);
const alreadyGone = result.status === 'already_gone';
const actionLabel = reason === 'spoiled' ? 'marked spoilt' : 'marked used';
this.removeEntryLocally(entry.id);
delete this.editForms[entry.id];
delete this.editErrors[entry.id];
@@ -2298,11 +2397,11 @@ export function stockListPageData(store) {
type: alreadyGone ? 'info' : 'success',
message: alreadyGone
? `${entry.name} was already out of stock and removed from the list.`
: `${entry.name} was marked gone and removed from the list.`,
: `${entry.name} was ${actionLabel} and removed from the list.`,
});
this.refreshLoadedViewsInBackground().catch(() => {});
} catch (error) {
this.editErrors[entry.id] = error.message || 'Mark gone failed.';
this.editErrors[entry.id] = error.message || 'Removal failed.';
}
},
removeEntryLocally(entryId) {
+825
View File
@@ -0,0 +1,825 @@
import {
applyItemUpsert,
createStockEvent,
getStockEntry,
listStockEntries,
lookupItemByIdentifier,
markStockGone,
} from '../../api/stock.js';
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
import { fetchLocations } from '../../api/locations.js';
import { STORAGE_KEYS } from '../../app/config.js';
import { mapLookupItemToForm } from '../labels/identifier-lookup-mapper.js';
import { saveStoredValue } from '../shared/storage.js';
import { createAsyncState, runAsyncState } from '../shared/ui-state.js';
import { formatDate } from '../shared/date-utils.js';
import { renderScannerModal } from '../shared/scanner-modal.js';
import {
canUseCameraScanner,
createScannerReader,
normalizeIdentifierCode,
normalizeScannerError,
parseKitchenScanPayload,
startCameraScanner,
stopCameraScanner,
} from '../shared/scanner.js';
import {
buildConsumeOneStockPayload,
isGonePayload,
} from '../shared/stock-actions.js';
const SCAN_MODES = [
{
key: 'details',
label: 'Open details',
description: 'Scan and inspect the exact item.',
},
{
key: 'consume',
label: 'Consume standard unit',
description: 'Reduce stock by one standard unit.',
},
{
key: 'used',
label: 'Mark used',
description: 'Mark the item gone because it was consumed.',
},
{
key: 'spoiled',
label: 'Mark spoiled',
description: 'Mark the item gone because it spoiled.',
},
{
key: 'label',
label: 'Label workflow',
description: 'Lookup product data and continue to label creation.',
},
];
const LABEL_SCAN_ACTIONS = [
{
key: 'lookup',
label: 'Lookup',
description: 'Open label form with prefilled lookup data.',
},
{
key: 'create',
label: 'Create',
description: 'Create stock label directly when lookup has enough data.',
},
{
key: 'create_print',
label: 'Create & print',
description: 'Create and print when data is sufficient.',
},
];
function parseDateValue(value) {
if (!value) {
return null;
}
const [year, month, day] = String(value).split('-').map(Number);
if (!year || !month || !day) {
return null;
}
return new Date(year, month - 1, day);
}
function sortByOperationalPriority(entries, locationMap) {
return [...entries].sort((left, right) => {
const leftDate = parseDateValue(left.expire_date)?.getTime() ?? Number.MAX_SAFE_INTEGER;
const rightDate = parseDateValue(right.expire_date)?.getTime() ?? Number.MAX_SAFE_INTEGER;
if (leftDate !== rightDate) {
return leftDate - rightDate;
}
const leftLocation = locationMap[left.location_initial_uuid_b64] || '';
const rightLocation = locationMap[right.location_initial_uuid_b64] || '';
if (leftLocation !== rightLocation) {
return leftLocation.localeCompare(rightLocation);
}
return (left.name || '').localeCompare(right.name || '');
});
}
function quantityLabel(entry) {
if (!entry) {
return '';
}
if (entry.stock_type === 'binary') {
return entry.level === 'gone' ? 'Gone' : 'Available';
}
const quantity = entry.quantity ?? null;
const uom = entry.uom_symbol || '';
const measured = quantity !== null && quantity !== undefined ? `${quantity} ${uom}`.trim() : '';
return measured || entry.level || 'No quantity';
}
function todayIsoDate() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function createLabelDraftBase() {
return {
itemId: '',
itemUuidB64: '',
identifierCode: '',
externalSource: '',
externalId: '',
search: '',
name: '',
description: '',
quantity: '',
uom: 'g',
stockType: 'binary',
level: 'plenty',
energy: '',
energyUnit: 'kcal (100g/ml)',
productionDate: todayIsoDate(),
expireDays: '',
expirationDate: '',
locationId: '',
};
}
export function renderStockScanPage() {
const scannerOptionsMarkup = `
<div class="scan-modal-mode-list mb-3">
<template x-for="mode in scanModes" :key="'modal-' + mode.key">
<button
class="btn btn-sm scan-modal-mode-btn"
type="button"
:class="scanMode === mode.key ? 'scan-modal-mode-btn-active' : 'btn-outline-secondary'"
@click="scanMode = mode.key"
>
<span x-text="mode.label"></span>
</button>
</template>
</div>
<template x-if="scanMode === 'label'">
<div class="scan-label-mode-list mb-3">
<template x-for="action in labelScanActions" :key="'modal-label-' + action.key">
<button
class="btn btn-sm scan-label-mode-btn"
type="button"
:class="labelScanAction === action.key ? 'scan-label-mode-btn-active' : 'btn-outline-secondary'"
@click="labelScanAction = action.key"
>
<span x-text="action.label"></span>
</button>
</template>
</div>
</template>
`;
return `
<section class="container-xxl py-4 py-lg-5" x-data="stockScanPage()" x-init="init()">
<div class="scan-hero card border-0 shadow-sm mb-4">
<div class="card-body p-4 p-lg-5">
<div class="d-flex flex-column flex-lg-row justify-content-between gap-4">
<div>
<p class="eyebrow mb-2">Scan operations</p>
<h1 class="h3 mb-2">Scan a label or barcode and act immediately.</h1>
<p class="text-body-secondary mb-0">
DataMatrix labels open the exact stock item. Product barcodes resolve matching active stock and ask when there is ambiguity.
</p>
</div>
<div class="d-flex align-items-start gap-2">
<button class="btn btn-primary btn-lg" type="button" @click="openScanner()" :disabled="!scannerState.hasCamera || actionState.isLoading">
Start camera
</button>
<a class="btn btn-outline-secondary btn-lg" href="#/stock">Browse stock</a>
</div>
</div>
</div>
</div>
<div class="row g-4">
<div class="col-12 col-xl-5">
<div class="card border-0 shadow-sm h-100">
<div class="card-body p-4">
<h2 class="h5 mb-3">Choose scan action</h2>
<div class="scan-mode-grid">
<template x-for="mode in scanModes" :key="mode.key">
<button
class="scan-mode-card"
type="button"
:class="scanMode === mode.key ? 'scan-mode-card-active' : ''"
@click="scanMode = mode.key"
>
<span class="fw-semibold" x-text="mode.label"></span>
<span class="small text-body-secondary" x-text="mode.description"></span>
</button>
</template>
</div>
<template x-if="scanMode === 'label'">
<div class="mt-3">
<label class="form-label mb-2">Label action</label>
<div class="scan-label-mode-list">
<template x-for="action in labelScanActions" :key="action.key">
<button
class="btn btn-sm scan-label-mode-btn"
type="button"
:class="labelScanAction === action.key ? 'scan-label-mode-btn-active' : 'btn-outline-secondary'"
@click="labelScanAction = action.key"
>
<span x-text="action.label"></span>
</button>
</template>
</div>
<div class="small text-body-secondary mt-2" x-text="activeLabelActionDescription()"></div>
</div>
</template>
<div class="mt-4">
<label class="form-label">Manual scan code</label>
<div class="input-group">
<input class="form-control" type="text" x-model="manualCode" placeholder="Scan with hardware reader or paste code" autocomplete="off" />
<button class="btn btn-outline-primary" type="button" @click="processManualCode()" :disabled="actionState.isLoading">Run</button>
</div>
<div class="form-text">Works with keyboard-style barcode scanners and manual paste.</div>
</div>
<template x-if="!scannerState.hasCamera">
<div class="alert alert-warning mt-4 mb-0">
Camera scanning is not available in this browser. Manual entry still works.
</div>
</template>
</div>
</div>
</div>
<div class="col-12 col-xl-7">
<div class="card border-0 shadow-sm h-100">
<div class="card-body p-4">
<div class="d-flex justify-content-between gap-3 align-items-start mb-3">
<div>
<h2 class="h5 mb-1">Scan result</h2>
<p class="text-body-secondary small mb-0">Last scanned code and the action outcome.</p>
</div>
<button class="btn btn-sm btn-outline-secondary" type="button" @click="clearResult()" x-show="result.item || result.message || candidateItems.length">Clear</button>
</div>
<template x-if="actionState.error">
<div class="alert alert-danger" x-text="actionState.error"></div>
</template>
<template x-if="result.message">
<div class="alert" :class="result.type === 'success' ? 'alert-success' : 'alert-info'" x-text="result.message"></div>
</template>
<template x-if="candidateItems.length">
<div>
<h3 class="h6 mb-2">Choose matching stock item</h3>
<div class="list-group scan-candidate-list">
<template x-for="item in candidateItems" :key="item.uuid_b64">
<button class="list-group-item list-group-item-action" type="button" @click="selectCandidate(item)">
<div class="d-flex justify-content-between gap-3">
<div>
<div class="fw-semibold" x-text="item.name"></div>
<div class="small text-body-secondary" x-text="locationLabel(item)"></div>
</div>
<div class="small text-end">
<div class="fw-semibold" x-text="quantityLabel(item)"></div>
<div class="text-body-secondary" x-text="formatDate(item.expire_date)"></div>
</div>
</div>
</button>
</template>
</div>
</div>
</template>
<template x-if="result.item">
<div class="scan-result-card">
<div class="d-flex flex-column flex-md-row justify-content-between gap-3">
<div>
<p class="eyebrow mb-2">Item</p>
<h3 class="h5 mb-1" x-text="result.item.name"></h3>
<p class="text-body-secondary mb-2" x-text="result.item.description || 'No description'"></p>
<div class="small text-body-secondary">
<span x-text="quantityLabel(result.item)"></span>
<span aria-hidden="true"> · </span>
<span x-text="locationLabel(result.item)"></span>
</div>
</div>
<div class="d-flex flex-wrap align-content-start gap-2">
<a class="btn btn-outline-primary btn-sm" :href="detailHref(result.item)">View item</a>
<button class="btn btn-outline-secondary btn-sm" type="button" @click="printResultLabel()" :disabled="printState.isLoading">
<span x-show="!printState.isLoading">Print label</span>
<span x-show="printState.isLoading">Printing...</span>
</button>
<button class="btn btn-primary btn-sm" type="button" @click="openScanner()" :disabled="!scannerState.hasCamera">Scan another</button>
</div>
</div>
</div>
</template>
<template x-if="!actionState.error && !result.message && !result.item && !candidateItems.length">
<div class="empty-state-inline">
Pick an action, scan a kitchen label or barcode, and the result will appear here.
</div>
</template>
</div>
</div>
</div>
</div>
${renderScannerModal({
title: 'Scan for <span x-text="activeModeLabel()"></span>',
subtitle: 'Point your camera at a DataMatrix label or product barcode.',
optionsMarkup: scannerOptionsMarkup,
manualCodeModel: 'scannerManualCode',
manualSubmitAction: 'processScannerManualCode()',
manualPlaceholder: 'Scan with hardware reader or paste code',
manualHelp: 'Works with keyboard-style barcode scanners and manual paste.',
manualDisabledExpression: 'actionState.isLoading || scannerState.isLoading',
})}
</section>
`;
}
export function stockScanPageData(store) {
return {
scanModes: SCAN_MODES,
labelScanActions: LABEL_SCAN_ACTIONS,
scanMode: 'details',
labelScanAction: 'lookup',
manualCode: '',
scannerManualCode: '',
scannerReader: null,
scannerControls: null,
scannerState: {
isOpen: false,
isLoading: false,
hasCamera: false,
error: '',
lastDetectedCode: '',
},
actionState: createAsyncState(),
printState: createAsyncState(),
result: {
type: '',
message: '',
item: null,
},
candidateItems: [],
locations: [],
locationPathByUuid: {},
async init() {
this.scannerState.hasCamera = canUseCameraScanner();
if (!store.isConnected) {
return;
}
const locations = await fetchLocations(store).catch(() => ({ flat: [] }));
this.locations = locations.flat || [];
this.locationPathByUuid = Object.fromEntries(
this.locations
.filter((location) => location.uuid_b64)
.map((location) => [location.uuid_b64, location.pathLabel || location.name]),
);
},
destroy() {
this.stopScanner();
},
activeModeLabel() {
return this.scanModes.find((mode) => mode.key === this.scanMode)?.label || 'scan';
},
activeLabelActionDescription() {
return this.labelScanActions.find((action) => action.key === this.labelScanAction)?.description || '';
},
async openScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
this.scannerManualCode = this.manualCode;
this.scannerState.isOpen = true;
await this.$nextTick();
await this.startScanner();
},
async startScanner() {
this.scannerState.error = '';
this.scannerState.lastDetectedCode = '';
if (!canUseCameraScanner()) {
this.scannerState.hasCamera = false;
this.scannerState.error = 'Camera scanning is not supported in this browser. Enter the 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;
try {
if (!this.scannerReader) {
this.scannerReader = createScannerReader();
}
const session = await startCameraScanner({
reader: this.scannerReader,
videoElement,
onDetected: (code) => this.onScanDetected(code),
});
this.scannerReader = session.reader;
this.scannerControls = session.controls;
} catch (error) {
this.scannerState.error = normalizeScannerError(error);
} finally {
this.scannerState.isLoading = false;
}
},
stopScanner() {
stopCameraScanner({
reader: this.scannerReader,
controls: this.scannerControls,
videoElement: this.$refs.scannerVideo,
});
this.scannerControls = null;
},
closeScanner() {
this.stopScanner();
this.scannerState.isOpen = false;
this.scannerState.isLoading = false;
this.scannerState.error = '';
},
onScanDetected(rawCode) {
const code = normalizeIdentifierCode(rawCode);
if (!code || !this.scannerState.isOpen) {
return;
}
this.scannerState.lastDetectedCode = code;
this.scannerManualCode = code;
this.closeScanner();
this.processScannedCode(code);
},
processScannerManualCode() {
const code = normalizeIdentifierCode(this.scannerManualCode);
if (!code) {
this.scannerState.error = 'Scan or enter a code first.';
return;
}
this.scannerState.lastDetectedCode = code;
this.manualCode = code;
this.closeScanner();
this.processScannedCode(code);
},
processManualCode() {
this.processScannedCode(this.manualCode);
},
async processScannedCode(rawCode) {
const parsed = parseKitchenScanPayload(rawCode);
this.clearResult();
if (parsed.type === 'empty') {
this.actionState.error = 'Scan or enter a code first.';
return;
}
if (this.scanMode === 'label') {
await runAsyncState(this.actionState, async () => {
await this.processLabelScan(parsed);
}).catch(() => {});
return;
}
await runAsyncState(this.actionState, async () => {
if (parsed.type === 'item') {
const item = await getStockEntry(store, parsed.uuidB64, { allowInactive: true });
await this.executeAction(item);
return;
}
const matches = await this.resolveIdentifierMatches(parsed.identifierCode);
if (!matches.length) {
this.result = {
type: 'info',
message: `No active stock item matched ${parsed.identifierCode}.`,
item: null,
};
return;
}
if (matches.length > 1) {
this.candidateItems = matches;
this.result = {
type: 'info',
message: `${matches.length} stock items match this barcode. Choose the one to ${this.activeModeLabel().toLowerCase()}.`,
item: null,
};
return;
}
await this.executeAction(matches[0]);
}).catch(() => {});
},
buildLabelDraftFromLookup(lookupItem, identifierCode) {
const mapped = mapLookupItemToForm({
form: {
...createLabelDraftBase(),
identifierCode: identifierCode || '',
},
lookupItem,
locations: this.locations,
});
const stockType = ['measured', 'descriptive', 'binary'].includes(lookupItem?.stock_type)
? lookupItem.stock_type
: mapped.form.stockType || 'binary';
const level = stockType === 'measured'
? ''
: (mapped.form.level || 'plenty');
return {
form: {
...mapped.form,
stockType,
level,
identifierCode: normalizeIdentifierCode(identifierCode || mapped.form.identifierCode),
},
locationSearch: mapped.locationSearch || '',
};
},
locationUuidFromDraft(form) {
const location = this.locations.find((entry) => String(entry.id) === String(form.locationId));
return location?.uuid_b64 || null;
},
canAutoCreateLabel(form) {
if (!String(form.name || '').trim()) {
return false;
}
if (!this.locationUuidFromDraft(form)) {
return false;
}
if (!form.productionDate) {
return false;
}
if (form.stockType === 'measured') {
const quantity = Number(form.quantity);
if (Number.isNaN(quantity) || quantity <= 0) {
return false;
}
}
return true;
},
buildUpsertPayloadFromDraft(form) {
const locationUuidB64 = this.locationUuidFromDraft(form);
const quantity = form.quantity === ''
? form.stockType === 'binary'
? 1
: null
: Number(form.quantity);
return {
uuid_b64: form.itemUuidB64 || null,
identifier_code: form.identifierCode || null,
external_source: form.externalSource || null,
external_id: form.externalId || null,
item: {
name: String(form.name || '').trim(),
description: String(form.description || '').trim(),
quantity_initial: Number.isNaN(quantity) ? null : quantity,
uom_symbol: String(form.uom || '').trim() || null,
calories: form.energy === '' ? null : Number(form.energy),
calories_unit: String(form.energyUnit || '').trim() || null,
stock_type: form.stockType,
level: form.stockType === 'measured' ? null : (form.level || null),
date: form.productionDate || null,
expire_date: form.expirationDate || null,
location_initial: locationUuidB64,
},
};
},
saveLabelDraftAndOpenForm(form) {
saveStoredValue(STORAGE_KEYS.labelDraft, {
form,
savedAt: Date.now(),
});
window.__loncApp.navigate('/labels/new');
},
async processLabelScan(parsed) {
let identifierCode = '';
if (parsed.type === 'item') {
const item = await getStockEntry(store, parsed.uuidB64, { allowInactive: true });
identifierCode = normalizeIdentifierCode(item?.identifier_code);
if (!identifierCode) {
this.result = {
type: 'info',
message: `${item?.name || 'Item'} has no identifier code. Open label form to complete it first.`,
item: item || null,
};
return;
}
} else {
identifierCode = normalizeIdentifierCode(parsed.identifierCode);
}
if (!identifierCode) {
throw new Error('No identifier code found in scan.');
}
const lookup = await lookupItemByIdentifier(store, identifierCode);
if (lookup.status !== 'ok' || !lookup.item) {
this.result = {
type: 'info',
message: `Lookup did not return a usable item for ${identifierCode}.`,
item: null,
};
return;
}
const draft = this.buildLabelDraftFromLookup(lookup.item, identifierCode);
if (this.labelScanAction === 'lookup') {
this.saveLabelDraftAndOpenForm(draft.form);
store.addAlert({
type: 'success',
message: `Lookup loaded for ${identifierCode}. Continue in label form.`,
});
return;
}
if (!this.canAutoCreateLabel(draft.form)) {
this.saveLabelDraftAndOpenForm(draft.form);
store.addAlert({
type: 'info',
message: 'Lookup data is incomplete for direct create. Please complete required fields in label form.',
});
return;
}
const upsertPayload = this.buildUpsertPayloadFromDraft(draft.form);
const entry = await applyItemUpsert(store, upsertPayload);
const entryName = entry.item?.name || draft.form.name;
const operationVerb = entry.operation === 'update' ? 'updated' : 'created';
if (this.labelScanAction === 'create_print') {
const createdUuidB64 = entry.item?.uuid_b64 || '';
if (!createdUuidB64) {
const message = `${entryName} was ${operationVerb}, but label printing is unavailable for this entry.`;
this.result = {
type: 'info',
message,
item: entry.item || null,
};
store.addAlert({
type: 'warning',
message,
});
return;
}
try {
await printItemLabel(store, createdUuidB64);
const message = `${entryName} was ${operationVerb} and printed. Ready for next scan.`;
this.result = {
type: 'success',
message,
item: entry.item || null,
};
store.addAlert({
type: 'success',
message,
});
void this.openScanner().catch(() => {});
} catch (error) {
const parsed = formatPrintErrorMessage(error);
const message = `${entryName} was ${operationVerb}, but printing failed: ${parsed} Use "Print label" to retry.`;
this.result = {
type: 'info',
message,
item: entry.item || null,
};
store.addAlert({
type: 'warning',
message: `${entryName} was ${operationVerb}, but printing failed: ${parsed}`,
});
}
return;
}
const message = `${entryName} was ${operationVerb}. Ready for next scan.`;
this.result = {
type: 'success',
message,
item: entry.item || null,
};
store.addAlert({
type: 'success',
message,
});
void this.openScanner().catch(() => {});
},
async resolveIdentifierMatches(identifierCode) {
const normalizedCode = normalizeIdentifierCode(identifierCode);
if (!normalizedCode) {
return [];
}
const entries = await listStockEntries(store).catch(() => []);
const matches = entries.filter((entry) =>
normalizeIdentifierCode(entry.identifier_code) === normalizedCode,
);
return sortByOperationalPriority(matches, this.locationPathByUuid);
},
async selectCandidate(item) {
this.candidateItems = [];
await runAsyncState(this.actionState, async () => {
await this.executeAction(item);
}).catch(() => {});
},
async executeAction(item) {
if (!item?.uuid_b64) {
throw new Error('Scanned item could not be resolved.');
}
if (this.scanMode === 'details') {
window.__loncApp.navigate(`/stock/${item.uuid_b64}?from=scan`);
return;
}
if (item.active === false) {
this.result = {
type: 'info',
message: `${item.name} is already out of stock.`,
item,
};
return;
}
if (this.scanMode === 'used' || this.scanMode === 'spoiled') {
const reason = this.scanMode === 'spoiled' ? 'spoiled' : 'consumed';
const result = await markStockGone(store, item.uuid_b64, reason);
const label = reason === 'spoiled' ? 'marked spoilt' : 'marked used';
this.result = {
type: result.status === 'already_gone' ? 'info' : 'success',
message: result.status === 'already_gone'
? `${item.name} was already out of stock.`
: `${item.name} was ${label}.`,
item: { ...item, active: false, level: 'gone', gone_reason: reason },
};
return;
}
const payload = buildConsumeOneStockPayload(item);
await createStockEvent(store, item.uuid_b64, payload);
const refreshed = await getStockEntry(store, item.uuid_b64, {
allowInactive: isGonePayload(payload),
}).catch(() => ({
...item,
active: false,
level: 'gone',
}));
this.result = {
type: 'success',
message: `${item.name} stock was reduced by one standard unit.`,
item: refreshed,
};
},
async printResultLabel() {
if (!this.result.item?.uuid_b64) {
return;
}
await runAsyncState(this.printState, async () => {
try {
await printItemLabel(store, this.result.item.uuid_b64);
store.addAlert({
type: 'success',
message: `${this.result.item.name} label sent to printer.`,
});
} catch (error) {
const parsed = formatPrintErrorMessage(error);
store.addAlert({
type: 'warning',
message: `Could not print ${this.result.item.name} label: ${parsed}`,
});
}
}).catch(() => {});
},
clearResult() {
this.actionState.error = '';
this.result = {
type: '',
message: '',
item: null,
};
this.candidateItems = [];
},
detailHref(item) {
return `#/stock/${item.uuid_b64}?from=scan`;
},
locationLabel(item) {
return this.locationPathByUuid[item?.location_initial_uuid_b64] || 'No location assigned';
},
quantityLabel,
formatDate,
};
}
+103
View File
@@ -1099,6 +1099,109 @@ button.legend-card:focus-visible {
object-fit: cover;
}
.scan-hero {
background:
radial-gradient(circle at 15% 20%, rgba(80, 180, 140, 0.18), transparent 28rem),
linear-gradient(145deg, rgba(255, 255, 255, 0.96), rgba(245, 250, 255, 0.92));
}
.scan-mode-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.8rem;
}
.scan-mode-card {
display: grid;
gap: 0.25rem;
min-height: 6rem;
padding: 1rem;
text-align: left;
color: inherit;
background: rgba(255, 255, 255, 0.74);
border: 1px solid var(--lonc-border);
border-radius: 1rem;
transition:
transform 160ms ease,
box-shadow 160ms ease,
border-color 160ms ease,
background-color 160ms ease;
}
.scan-mode-card:hover {
transform: translateY(-1px);
box-shadow: 0 12px 24px rgba(24, 42, 79, 0.08);
}
.scan-mode-card-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);
}
.scan-candidate-list {
max-height: 24rem;
overflow-y: auto;
}
.scan-modal-mode-list {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
}
.scan-modal-mode-btn {
border-radius: 999px;
}
.scan-modal-mode-btn-active {
color: #fff;
background: var(--lonc-primary);
border-color: var(--lonc-primary);
}
.scan-label-mode-list {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
}
.scan-label-mode-btn {
border-radius: 999px;
}
.scan-label-mode-btn-active {
color: #fff;
background: var(--lonc-primary-dark);
border-color: var(--lonc-primary-dark);
}
.scan-result-card {
padding: 1.25rem;
border-radius: 1.25rem;
border: 1px solid var(--lonc-border);
background:
linear-gradient(135deg, rgba(235, 243, 255, 0.78), rgba(255, 255, 255, 0.92));
}
.empty-state-inline {
display: grid;
min-height: 12rem;
place-items: center;
padding: 2rem;
color: var(--lonc-muted);
text-align: center;
border: 1px dashed rgba(31, 75, 153, 0.22);
border-radius: 1.25rem;
background: rgba(255, 255, 255, 0.58);
}
@media (max-width: 575.98px) {
.scan-mode-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 991.98px) {
.navbar {
backdrop-filter: blur(10px);
+67
View File
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const apiRequestMock = vi.fn();
vi.mock('../../src/api/client.js', () => ({
getPath(key) {
const paths = {
categories: 'kitchen/categories',
};
return paths[key];
},
apiRequest: (...args) => apiRequestMock(...args),
}));
const { listCategories } = await import('../../src/api/categories.js');
describe('api/categories', () => {
beforeEach(() => {
apiRequestMock.mockReset();
});
it('forwards explicit pagination and filters', async () => {
apiRequestMock.mockResolvedValueOnce([]);
await listCategories(
{ config: { database: 'db' } },
{ searchName: 'dairy', active: true, limit: 10, offset: 20, orderBy: 'name', orderDir: 'asc' },
);
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/categories',
{
query: {
search_name: 'dairy',
active: true,
order_by: 'name',
order_dir: 'asc',
limit: 10,
offset: 20,
},
},
);
});
it('aggregates category pages by default', async () => {
apiRequestMock
.mockResolvedValueOnce(Array.from({ length: 100 }, (_, id) => ({ id: id + 1 })))
.mockResolvedValueOnce([{ id: 101 }]);
const response = await listCategories({ config: { database: 'db' } }, {});
expect(response).toHaveLength(101);
expect(apiRequestMock).toHaveBeenNthCalledWith(
1,
{ config: { database: 'db' } },
'kitchen/categories',
{ query: { limit: 100, offset: 0 } },
);
expect(apiRequestMock).toHaveBeenNthCalledWith(
2,
{ config: { database: 'db' } },
'kitchen/categories',
{ query: { limit: 100, offset: 100 } },
);
});
});
+4 -4
View File
@@ -61,12 +61,12 @@ describe('api/client', () => {
const url = buildKitchenApiUrl(store, 'kitchen/items/grouped', {
search_name: 'Milk + eggs',
expanded: 1,
expanded: true,
ignored: '',
});
expect(url).toBe(
'https://api.example.com/my%20db/kitchen/items/grouped?search_name=Milk+%2B+eggs&expanded=1',
'https://api.example.com/my%20db/kitchen/items/grouped?search_name=Milk+%2B+eggs&expanded=true',
);
});
@@ -88,14 +88,14 @@ describe('api/client', () => {
name: 'Rice',
},
query: {
label: 1,
label: true,
},
});
expect(payload).toEqual({ ok: true });
const [url, request] = fetchSpy.mock.calls[0];
expect(url).toBe('/kitchen-db/kitchen/items?label=1');
expect(url).toBe('/kitchen-db/kitchen/items?label=true');
expect(request.method).toBe('POST');
expect(request.body).toBe('{"name":"Rice"}');
expect(request.headers.get('Accept')).toBe('application/json');
+68 -2
View File
@@ -1,6 +1,72 @@
import { describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { formatPrintErrorMessage } from '../../src/api/labels.js';
const apiRequestMock = vi.fn();
vi.mock('../../src/api/client.js', () => ({
getPath(key) {
const paths = {
items: 'kitchen/items',
};
return paths[key];
},
apiRequest: (...args) => apiRequestMock(...args),
}));
const {
formatPrintErrorMessage,
getItemLabel,
previewLabel,
} = await import('../../src/api/labels.js');
describe('api/labels', () => {
beforeEach(() => {
apiRequestMock.mockReset();
});
it('previewLabel uses boolean label/preview query flags', async () => {
apiRequestMock.mockResolvedValueOnce({
label: 'YWJj',
});
const response = await previewLabel({ config: { database: 'db' } }, { name: 'Rice' });
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items',
{
method: 'POST',
body: { name: 'Rice' },
accept: 'image/svg+xml, image/png, application/json',
query: { label: true, preview: true },
},
);
expect(response).toEqual({
objectUrl: 'data:image/png;base64,YWJj',
contentType: 'image/png',
});
});
it('getItemLabel fetches PNG from /label endpoint', async () => {
apiRequestMock.mockResolvedValueOnce({
label: 'YWJj',
});
const response = await getItemLabel({ config: { database: 'db' } }, 'item-1');
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-1/label',
{
method: 'GET',
accept: 'image/png, application/json',
},
);
expect(response).toEqual({
objectUrl: 'data:image/png;base64,YWJj',
contentType: 'image/png',
});
});
});
describe('api/labels formatPrintErrorMessage', () => {
it('maps printer_unavailable payload to user-friendly message', () => {
+63 -6
View File
@@ -16,9 +16,11 @@ vi.mock('../../src/api/client.js', () => ({
const {
adjustStockEntry,
applyItemUpsert,
getStockEntry,
listGroupedStockEntries,
listKitchenChanges,
listStockEntries,
markStockGone,
lookupItemByIdentifier,
lookupItemDetails,
patchStockItem,
@@ -83,7 +85,7 @@ describe('api/stock', () => {
await listGroupedStockEntries(
{ config: { database: 'db' } },
{ expanded: 0, searchName: 'Rice', limit: 10, offset: 0 },
{ expanded: false, searchName: 'Rice', limit: 10, offset: 0 },
);
expect(apiRequestMock).toHaveBeenCalledWith(
@@ -91,7 +93,7 @@ describe('api/stock', () => {
'kitchen/items/grouped',
{
query: {
expanded: 0,
expanded: false,
search_name: 'Rice',
limit: 10,
offset: 0,
@@ -107,7 +109,7 @@ describe('api/stock', () => {
const response = await listGroupedStockEntries(
{ config: { database: 'db' } },
{ expanded: 1, searchName: 'Rice' },
{ expanded: true, searchName: 'Rice' },
);
expect(response).toHaveLength(101);
@@ -115,13 +117,42 @@ describe('api/stock', () => {
1,
{ config: { database: 'db' } },
'kitchen/items/grouped',
{ query: { expanded: 1, search_name: 'Rice', limit: 100, offset: 0 } },
{ query: { expanded: true, 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 } },
{ query: { expanded: true, 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: true } },
);
});
@@ -267,7 +298,7 @@ describe('api/stock', () => {
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-1/lookup',
{ method: 'POST', query: { update: 1 } },
{ method: 'POST', query: { update: true } },
);
expect(response).toEqual({
status: 'ok',
@@ -396,4 +427,30 @@ describe('api/stock', () => {
});
expect(apiRequestMock).toHaveBeenCalledTimes(1);
});
it('markStockGone uses /use endpoint for consumed reason', async () => {
apiRequestMock.mockResolvedValueOnce(null);
const result = await markStockGone({ config: { database: 'db' } }, 'item-1', 'consumed');
expect(result).toEqual({ status: 'gone', reason: 'consumed' });
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-1/use',
{ method: 'POST' },
);
});
it('markStockGone uses /stock endpoint for non-consumed reasons', async () => {
apiRequestMock.mockResolvedValueOnce({ status: 'OK', stock: { id: 3 } });
const result = await markStockGone({ config: { database: 'db' } }, 'item-1', 'spoiled');
expect(result).toEqual({ status: 'gone', reason: 'spoiled' });
expect(apiRequestMock).toHaveBeenCalledWith(
{ config: { database: 'db' } },
'kitchen/items/item-1/stock',
{ method: 'POST', body: { level: 'gone', gone_reason: 'spoiled' } },
);
});
});
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const listKitchenChangesMock = 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');
describe('features/dashboard/dashboard-page', () => {
beforeEach(() => {
listKitchenChangesMock.mockReset();
getStockEntryMock.mockReset();
fetchLocationsMock.mockReset();
});
it('renders dashboard with recent changes section', () => {
const html = renderDashboardPage();
expect(html).toContain('Recent changes');
@@ -107,6 +113,50 @@ describe('features/dashboard/dashboard-page', () => {
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 () => {
listKitchenChangesMock.mockResolvedValueOnce({
since: null,
+180 -4
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 previewItemUpsertMock = 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', () => ({
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');
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', () => {
const data = labelCreatePageData({
isConnected: false,
@@ -32,6 +74,132 @@ describe('label create upsert-first submit', () => {
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', () => {
const store = {
isConnected: false,
@@ -96,6 +264,13 @@ describe('label create upsert-first submit', () => {
type: 'success',
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 () => {
@@ -124,10 +299,11 @@ describe('label create upsert-first submit', () => {
await data.create();
expect(data.printIssue).toBe('Printer is unavailable.');
expect(data.printIssue).toBe('Beans was created, but printing failed: Printer is unavailable.');
expect(addAlert).toHaveBeenCalledWith({
type: 'warning',
message: 'Beans was created, but printing has an issue: Printer is unavailable.',
});
message: 'Beans was created, but printing failed: Printer is unavailable.',
});
expect(localStorageMock.setItem).toHaveBeenCalled();
});
});
+22 -15
View File
@@ -1,16 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const useStockItemMock = vi.fn();
const markStockGoneMock = vi.fn();
const getStockEntryMock = vi.fn();
const listGroupedStockEntriesMock = vi.fn();
vi.mock('../../../src/api/stock.js', () => ({
useStockItem: (...args) => useStockItemMock(...args),
markStockGone: (...args) => markStockGoneMock(...args),
getStockEntry: (...args) => getStockEntryMock(...args),
adjustStockEntry: vi.fn(),
lookupItemDetails: vi.fn(),
patchStockItem: vi.fn(),
listStockEntries: vi.fn(),
listGroupedStockEntries: vi.fn(),
listGroupedStockEntries: (...args) => listGroupedStockEntriesMock(...args),
updateStockItem: vi.fn(),
}));
@@ -23,8 +24,9 @@ const { stockListPageData } = await import('../../../src/features/stock/stock-li
describe('stock mark-gone behavior', () => {
beforeEach(() => {
useStockItemMock.mockReset();
markStockGoneMock.mockReset();
getStockEntryMock.mockReset();
listGroupedStockEntriesMock.mockReset();
globalThis.window = {
__loncApp: {
navigate: vi.fn(),
@@ -37,15 +39,15 @@ describe('stock mark-gone behavior', () => {
delete globalThis.window;
});
it('stock detail markGone uses /use and shows info for already gone', async () => {
useStockItemMock.mockResolvedValueOnce({ status: 'already_gone' });
it('stock detail markGone posts gone event and shows info for already gone', async () => {
markStockGoneMock.mockResolvedValueOnce({ status: 'already_gone' });
const addAlert = vi.fn();
const data = stockDetailPageData({ addAlert });
data.entry = { uuid_b64: 'item-1', name: 'Rice' };
await data.markGone();
expect(useStockItemMock).toHaveBeenCalledWith({ addAlert }, 'item-1');
expect(markStockGoneMock).toHaveBeenCalledWith({ addAlert }, 'item-1', 'consumed');
expect(addAlert).toHaveBeenCalledWith({
type: 'info',
message: 'Rice was already out of stock.',
@@ -53,8 +55,8 @@ describe('stock mark-gone behavior', () => {
expect(globalThis.window.__loncApp.navigate).toHaveBeenCalledWith('/stock');
});
it('stock list markGone removes entry and uses /use path', async () => {
useStockItemMock.mockResolvedValueOnce({ status: 'used' });
it('stock list markGone removes entry and posts gone event', async () => {
markStockGoneMock.mockResolvedValueOnce({ status: 'ok' });
const addAlert = vi.fn();
const data = stockListPageData({ addAlert, isConnected: false });
data.entries = [{ id: 1, uuid_b64: 'item-1', name: 'Flour' }];
@@ -63,18 +65,21 @@ describe('stock mark-gone behavior', () => {
await data.markGone(data.entries[0]);
expect(useStockItemMock).toHaveBeenCalledWith({ addAlert, isConnected: false }, 'item-1');
expect(markStockGoneMock).toHaveBeenCalledWith({ addAlert, isConnected: false }, 'item-1', 'consumed');
expect(data.entries).toEqual([]);
expect(addAlert).toHaveBeenCalledWith({
type: 'success',
message: 'Flour was marked gone and removed from the list.',
message: 'Flour was marked used and removed from the list.',
});
});
it('stock list grouped markGone removes item from grouped and flat collections', async () => {
useStockItemMock.mockResolvedValueOnce({ status: 'used' });
markStockGoneMock.mockResolvedValueOnce({ status: 'ok' });
listGroupedStockEntriesMock.mockResolvedValueOnce([]);
const addAlert = vi.fn();
const data = stockListPageData({ addAlert, isConnected: false });
const store = { addAlert, isConnected: true };
const data = stockListPageData(store);
data.groupedLoaded = true;
data.groupedEntries = [
{
@@ -122,7 +127,9 @@ describe('stock mark-gone behavior', () => {
expect(data.groupedEntries).toEqual([]);
expect(addAlert).toHaveBeenCalledWith({
type: 'success',
message: 'Beans was marked gone and removed from the group.',
});
message: 'Beans was marked used and removed from the group.',
});
expect(listGroupedStockEntriesMock).toHaveBeenCalledTimes(1);
expect(listGroupedStockEntriesMock).toHaveBeenCalledWith(store, { expanded: false });
});
});
@@ -7,6 +7,7 @@ const getStockEntryMock = vi.fn();
const updateStockItemMock = vi.fn();
const useStockItemMock = vi.fn();
const fetchLocationsMock = vi.fn();
const listCategoriesMock = vi.fn();
vi.mock('../../../src/api/stock.js', () => ({
listStockEntries: (...args) => listStockEntriesMock(...args),
@@ -21,6 +22,10 @@ vi.mock('../../../src/api/locations.js', () => ({
fetchLocations: (...args) => fetchLocationsMock(...args),
}));
vi.mock('../../../src/api/categories.js', () => ({
listCategories: (...args) => listCategoriesMock(...args),
}));
const { stockListPageData } = await import('../../../src/features/stock/stock-list-page.js');
function createGroupedSummary() {
@@ -112,6 +117,8 @@ describe('stock list grouped-first behavior', () => {
updateStockItemMock.mockReset();
useStockItemMock.mockReset();
fetchLocationsMock.mockReset();
listCategoriesMock.mockReset();
listCategoriesMock.mockResolvedValue([]);
globalThis.window = createWindowMock();
globalThis.requestAnimationFrame = (callback) => callback();
@@ -133,6 +140,7 @@ describe('stock list grouped-first behavior', () => {
listStockEntriesMock.mockResolvedValueOnce([]);
listKitchenChangesMock.mockResolvedValue({ since: null, nextCursor: null, changes: [] });
fetchLocationsMock.mockResolvedValue({ flat: [], tree: [] });
listCategoriesMock.mockResolvedValue([]);
const store = { isConnected: true, addAlert: vi.fn() };
const data = stockListPageData(store);
@@ -141,12 +149,12 @@ describe('stock list grouped-first behavior', () => {
await data.init();
expect(data.viewMode).toBe('grouped');
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(1, store, { expanded: 0 });
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(1, store, { expanded: false });
expect(listStockEntriesMock).not.toHaveBeenCalled();
await Promise.resolve();
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(2, store, { expanded: 1 });
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(2, store, { expanded: true });
await data.switchView('items');
expect(listStockEntriesMock).toHaveBeenCalledTimes(1);
@@ -162,7 +170,7 @@ describe('stock list grouped-first behavior', () => {
.mockResolvedValueOnce(createGroupedExpanded());
const data = stockListPageData({ isConnected: true, addAlert: vi.fn() });
await data.loadGroupedEntries({ expanded: 0, resetVisible: true });
await data.loadGroupedEntries({ expanded: false, resetVisible: true });
expect(data.groupDisplayItems(data.groupedEntries[0])).toEqual([]);
expect(data.hasGroupedChildStubs(data.groupedEntries[0])).toBe(true);
@@ -226,7 +234,7 @@ describe('stock list grouped-first behavior', () => {
data.groupedLoaded = true;
data.groupedEntries = createGroupedSummary().map((group) => data.indexGroup(group));
const pending = data.loadGroupedEntries({ expanded: 0, background: true });
const pending = data.loadGroupedEntries({ expanded: false, background: true });
expect(data.state.isRefreshing).toBe(true);
expect(data.groupedEntries).toHaveLength(1);
@@ -357,8 +365,10 @@ describe('stock list grouped-first behavior', () => {
await Promise.resolve();
await Promise.resolve();
expect(listGroupedStockEntriesMock).not.toHaveBeenCalled();
expect(listStockEntriesMock).not.toHaveBeenCalled();
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(1, store, { expanded: false });
expect(listGroupedStockEntriesMock).toHaveBeenNthCalledWith(2, store, { expanded: true });
expect(listStockEntriesMock).toHaveBeenCalledTimes(1);
expect(listStockEntriesMock).toHaveBeenCalledWith(store);
expect(fetchLocationsMock).not.toHaveBeenCalled();
expect(getStockEntryMock).toHaveBeenCalledWith(store, 'item-100');
expect(returnVisit.entries[0].quantity).toBe(2);