Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9677e47680 | |||
| bbb5bd4dea |
@@ -171,10 +171,6 @@ Expected shapes today:
|
|||||||
Returns `{ since, next_cursor, changes }` feed payload for item/stock updates.
|
Returns `{ since, next_cursor, changes }` feed payload for item/stock updates.
|
||||||
- `POST /{database}/kitchen/items/upsert?mode=preview|apply`
|
- `POST /{database}/kitchen/items/upsert?mode=preview|apply`
|
||||||
Used by label submit flow for create-or-update behavior and conflict-safe matching.
|
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`
|
- `POST /{database}/kitchen/items?label=1`
|
||||||
Used for label image preview rendering.
|
Used for label image preview rendering.
|
||||||
- `POST /{database}/kitchen/items?label=1&preview=1`
|
- `POST /{database}/kitchen/items?label=1&preview=1`
|
||||||
@@ -187,8 +183,6 @@ Expected shapes today:
|
|||||||
Prints label for an existing item; called from the save flow when `Print` is enabled.
|
Prints label for an existing item; called from the save flow when `Print` is enabled.
|
||||||
- `DELETE /{database}/kitchen/items/{uuid_b64}`
|
- `DELETE /{database}/kitchen/items/{uuid_b64}`
|
||||||
Compatibility fallback when `/use` is not available on the backend.
|
Compatibility fallback when `/use` is not available on the backend.
|
||||||
- `PATCH /{database}/kitchen/items/{uuid_b64}`
|
|
||||||
Used for item-level edits from stock detail (for example identifier code updates).
|
|
||||||
- `GET /{database}/kitchen/locations`
|
- `GET /{database}/kitchen/locations`
|
||||||
Returns a nested location tree.
|
Returns a nested location tree.
|
||||||
|
|
||||||
@@ -199,4 +193,3 @@ Expected shapes today:
|
|||||||
- Kitchen context now lives in the URL path instead of a custom header.
|
- Kitchen context now lives in the URL path instead of a custom header.
|
||||||
- The API client now builds database-scoped kitchen routes by default; it always keeps bearer authentication handling separate from URL shaping.
|
- The API client now builds database-scoped kitchen routes by default; it always keeps bearer authentication handling separate from URL shaping.
|
||||||
- Label submit uses upsert-first apply semantics and an optional `Print` checkbox (default on for the current page session).
|
- Label submit uses upsert-first apply semantics and an optional `Print` checkbox (default on for the current page session).
|
||||||
- Stock detail supports inline identifier editing and OpenFoodFacts refresh/apply actions with rate-limit and cache-freshness hints.
|
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "lonc-web",
|
"name": "lonc-web",
|
||||||
"version": "0.2.0",
|
"version": "0.1.4",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "lonc-web",
|
"name": "lonc-web",
|
||||||
"version": "0.2.0",
|
"version": "0.1.4",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@zxing/browser": "^0.1.5",
|
"@zxing/browser": "^0.1.5",
|
||||||
"alpinejs": "^3.14.9",
|
"alpinejs": "^3.14.9",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "lonc-web",
|
"name": "lonc-web",
|
||||||
"version": "0.2.0",
|
"version": "0.1.4",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -77,26 +77,6 @@ function normalizeIdentifierLookupResponse(payload) {
|
|||||||
identifierType: payload?.identifier_type || null,
|
identifierType: payload?.identifier_type || null,
|
||||||
item: payload?.item || null,
|
item: payload?.item || null,
|
||||||
payloadFetchedAt: payload?.payload_fetched_at || null,
|
payloadFetchedAt: payload?.payload_fetched_at || null,
|
||||||
retryAfterSeconds:
|
|
||||||
Number.isInteger(payload?.retry_after_seconds) ? payload.retry_after_seconds : null,
|
|
||||||
staleCache: Boolean(payload?.stale_cache),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeItemLookupResponse(payload) {
|
|
||||||
return {
|
|
||||||
status: payload?.status || null,
|
|
||||||
found: Boolean(payload?.found),
|
|
||||||
update: Boolean(payload?.update),
|
|
||||||
identifierCode: payload?.identifier_code || null,
|
|
||||||
identifierType: payload?.identifier_type || null,
|
|
||||||
preview: payload?.preview || null,
|
|
||||||
updatedFields: Array.isArray(payload?.updated_fields) ? payload.updated_fields : [],
|
|
||||||
offPayloadFetchedAt: payload?.off_payload_fetched_at || null,
|
|
||||||
retryAfterSeconds:
|
|
||||||
Number.isInteger(payload?.retry_after_seconds) ? payload.retry_after_seconds : null,
|
|
||||||
staleCache: Boolean(payload?.stale_cache),
|
|
||||||
item: payload?.item || null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,23 +111,6 @@ export async function lookupItemByIdentifier(store, identifierCode) {
|
|||||||
return normalizeIdentifierLookupResponse(payload);
|
return normalizeIdentifierLookupResponse(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function lookupItemDetails(store, uuidB64, { update = false } = {}) {
|
|
||||||
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/lookup`, {
|
|
||||||
method: 'POST',
|
|
||||||
query: { update: update ? 1 : 0 },
|
|
||||||
});
|
|
||||||
|
|
||||||
return normalizeItemLookupResponse(payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function patchStockItem(store, uuidB64, body) {
|
|
||||||
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
body,
|
|
||||||
});
|
|
||||||
return unwrapEntryPayload(payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateStockItem(store, uuidB64, body) {
|
export async function updateStockItem(store, uuidB64, body) {
|
||||||
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, {
|
const payload = await apiRequest(store, `${getPath('items')}/${uuidB64}/stock`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
export const APP_NAME = 'Lonc';
|
export const APP_NAME = 'Lonc';
|
||||||
export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.2.0';
|
export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.1.2';
|
||||||
export const TRYTON_APPLICATION = 'kitchen';
|
export const TRYTON_APPLICATION = 'kitchen';
|
||||||
|
|
||||||
export const CONNECTION_STATES = {
|
export const CONNECTION_STATES = {
|
||||||
|
|||||||
@@ -739,67 +739,8 @@ export function labelCreatePageData(store) {
|
|||||||
return 'Lookup failed on the server. You can still fill the form manually.';
|
return 'Lookup failed on the server. You can still fill the form manually.';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === 'rate_limited') {
|
|
||||||
return 'Lookup is temporarily rate-limited. Try again shortly.';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'Lookup response could not be applied to this form.';
|
return 'Lookup response could not be applied to this form.';
|
||||||
},
|
},
|
||||||
lookupStatusMessageWithDetails(response, identifierCode) {
|
|
||||||
const base = this.lookupStatusMessage(response?.status, identifierCode);
|
|
||||||
if (response?.status !== 'rate_limited') {
|
|
||||||
return base;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Number.isInteger(response?.retryAfterSeconds) || response.retryAfterSeconds <= 0) {
|
|
||||||
return base;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${base} Retry in ${response.retryAfterSeconds}s.`;
|
|
||||||
},
|
|
||||||
lookupSourceLabel(source) {
|
|
||||||
if (!source) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
const labels = {
|
|
||||||
item: 'existing item',
|
|
||||||
cache: 'cache',
|
|
||||||
openfoodfacts: 'OpenFoodFacts',
|
|
||||||
};
|
|
||||||
|
|
||||||
return labels[source] || source;
|
|
||||||
},
|
|
||||||
lookupSuccessMessage(response) {
|
|
||||||
const parts = ['Lookup applied product details'];
|
|
||||||
const metadata = [];
|
|
||||||
|
|
||||||
if (response?.source) {
|
|
||||||
metadata.push(`source: ${this.lookupSourceLabel(response.source)}`);
|
|
||||||
}
|
|
||||||
if (response?.cacheHit) {
|
|
||||||
metadata.push('cache hit');
|
|
||||||
}
|
|
||||||
if (response?.staleCache) {
|
|
||||||
metadata.push('stale cache');
|
|
||||||
}
|
|
||||||
if (response?.payloadFetchedAt) {
|
|
||||||
const fetchedAt = new Date(response.payloadFetchedAt);
|
|
||||||
metadata.push(
|
|
||||||
`fetched: ${
|
|
||||||
Number.isNaN(fetchedAt.getTime())
|
|
||||||
? response.payloadFetchedAt
|
|
||||||
: fetchedAt.toLocaleString()
|
|
||||||
}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (metadata.length) {
|
|
||||||
parts.push(`(${metadata.join(', ')})`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${parts.join(' ')}.`;
|
|
||||||
},
|
|
||||||
normalizeScannerError(error) {
|
normalizeScannerError(error) {
|
||||||
const message = String(error?.message || '');
|
const message = String(error?.message || '');
|
||||||
const normalized = message.toLowerCase();
|
const normalized = message.toLowerCase();
|
||||||
@@ -843,6 +784,9 @@ export function labelCreatePageData(store) {
|
|||||||
|
|
||||||
this.stopScanner();
|
this.stopScanner();
|
||||||
this.scannerState.isLoading = true;
|
this.scannerState.isLoading = true;
|
||||||
|
const shouldLogDecodeErrors = import.meta.env.DEV;
|
||||||
|
let lastDecodeErrorName = '';
|
||||||
|
let lastDecodeErrorAt = 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!this.scannerReader) {
|
if (!this.scannerReader) {
|
||||||
@@ -863,13 +807,20 @@ export function labelCreatePageData(store) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!error || error?.name === 'NotFoundException') {
|
if (error) {
|
||||||
|
// Continuous decode emits expected per-frame misses/errors before a valid barcode is found.
|
||||||
|
// Keep the modal quiet and only surface startup failures from the outer catch block.
|
||||||
|
if (shouldLogDecodeErrors) {
|
||||||
|
const errorName = String(error?.name || 'UnknownError');
|
||||||
|
const now = Date.now();
|
||||||
|
if (errorName !== lastDecodeErrorName || now - lastDecodeErrorAt > 2000) {
|
||||||
|
console.debug('[scanner] Ignoring frame decode error while scanning:', errorName, error?.message || '');
|
||||||
|
lastDecodeErrorName = errorName;
|
||||||
|
lastDecodeErrorAt = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.scannerState.error) {
|
|
||||||
this.scannerState.error = this.normalizeScannerError(error);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -934,7 +885,7 @@ export function labelCreatePageData(store) {
|
|||||||
await runAsyncState(this.lookupState, async () => {
|
await runAsyncState(this.lookupState, async () => {
|
||||||
const response = await lookupItemByIdentifier(store, identifierCode);
|
const response = await lookupItemByIdentifier(store, identifierCode);
|
||||||
if (response.status !== 'ok') {
|
if (response.status !== 'ok') {
|
||||||
const message = this.lookupStatusMessageWithDetails(response, identifierCode);
|
const message = this.lookupStatusMessage(response.status, identifierCode);
|
||||||
this.lookupState.error = message;
|
this.lookupState.error = message;
|
||||||
store.addAlert({
|
store.addAlert({
|
||||||
type: response.status === 'not_found' ? 'info' : 'warning',
|
type: response.status === 'not_found' ? 'info' : 'warning',
|
||||||
@@ -991,9 +942,11 @@ export function labelCreatePageData(store) {
|
|||||||
this.suggestions = [];
|
this.suggestions = [];
|
||||||
this.persistDraft();
|
this.persistDraft();
|
||||||
|
|
||||||
|
const sourceSuffix = response.source ? ` (${response.source})` : '';
|
||||||
|
const cacheSuffix = response.cacheHit ? ', cache hit' : '';
|
||||||
store.addAlert({
|
store.addAlert({
|
||||||
type: 'success',
|
type: 'success',
|
||||||
message: this.lookupSuccessMessage(response),
|
message: `Lookup applied product details${sourceSuffix}${cacheSuffix}.`,
|
||||||
});
|
});
|
||||||
}).catch((error) => {
|
}).catch((error) => {
|
||||||
store.addAlert({
|
store.addAlert({
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
adjustStockEntry,
|
adjustStockEntry,
|
||||||
getStockEntry,
|
getStockEntry,
|
||||||
lookupItemDetails,
|
updateStockItem,
|
||||||
patchStockItem,
|
|
||||||
useStockItem,
|
useStockItem,
|
||||||
} from '../../api/stock.js';
|
} from '../../api/stock.js';
|
||||||
|
import { BrowserMultiFormatReader } from '@zxing/browser';
|
||||||
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
|
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
|
||||||
import { fetchLocations } from '../../api/locations.js';
|
import { fetchLocations } from '../../api/locations.js';
|
||||||
import { getRouteContext } from '../../app/router.js';
|
import { getRouteContext } from '../../app/router.js';
|
||||||
@@ -147,6 +147,7 @@ export function renderStockDetailPage() {
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
type="text"
|
type="text"
|
||||||
x-model="identifierDraft"
|
x-model="identifierDraft"
|
||||||
|
@input="identifierState.error = ''"
|
||||||
inputmode="numeric"
|
inputmode="numeric"
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
placeholder="EAN / UPC / GTIN"
|
placeholder="EAN / UPC / GTIN"
|
||||||
@@ -160,44 +161,18 @@ export function renderStockDetailPage() {
|
|||||||
<span x-show="!identifierState.isLoading">Save identifier</span>
|
<span x-show="!identifierState.isLoading">Save identifier</span>
|
||||||
<span x-show="identifierState.isLoading">Saving...</span>
|
<span x-show="identifierState.isLoading">Saving...</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
<div class="form-text">Used for OpenFoodFacts lookups and product metadata refresh.</div>
|
|
||||||
<template x-if="identifierState.error">
|
|
||||||
<div class="small text-danger mt-1" x-text="identifierState.error"></div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mt-4">
|
|
||||||
<h3 class="h6 mb-2">OpenFoodFacts</h3>
|
|
||||||
<div class="d-flex flex-wrap gap-2">
|
|
||||||
<button
|
<button
|
||||||
class="btn btn-outline-secondary"
|
class="btn btn-outline-secondary"
|
||||||
type="button"
|
type="button"
|
||||||
@click="runItemLookup(false)"
|
@click="openScanner()"
|
||||||
:disabled="lookupDetailsState.isLoading || !hasIdentifierCode()"
|
x-show="scannerState.hasCamera"
|
||||||
>
|
>
|
||||||
<span x-show="!lookupDetailsState.isLoading">Refresh details</span>
|
Camera
|
||||||
<span x-show="lookupDetailsState.isLoading">Refreshing...</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
class="btn btn-outline-primary"
|
|
||||||
type="button"
|
|
||||||
@click="runItemLookup(true)"
|
|
||||||
:disabled="lookupDetailsState.isLoading || !hasIdentifierCode()"
|
|
||||||
>
|
|
||||||
<span x-show="!lookupDetailsState.isLoading">Apply missing fields</span>
|
|
||||||
<span x-show="lookupDetailsState.isLoading">Applying...</span>
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<template x-if="!hasIdentifierCode()">
|
<div class="form-text">Used for product identifier tracking and metadata lookups.</div>
|
||||||
<div class="small text-body-secondary mt-2">Save an identifier code first to enable lookup refresh.</div>
|
<template x-if="identifierState.error">
|
||||||
</template>
|
<div class="small text-danger mt-1" x-text="identifierState.error"></div>
|
||||||
<template x-if="offLookupFeedback.message">
|
|
||||||
<div
|
|
||||||
class="alert mt-3 mb-0"
|
|
||||||
:class="offLookupFeedback.type === 'success' ? 'alert-success' : 'alert-warning'"
|
|
||||||
x-text="offLookupFeedback.message"
|
|
||||||
></div>
|
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -356,6 +331,39 @@ export function renderStockDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="scanner-modal-backdrop"
|
||||||
|
x-show="scannerState.isOpen"
|
||||||
|
@click.self="closeScanner()"
|
||||||
|
@keydown.escape.window="closeScanner()"
|
||||||
|
>
|
||||||
|
<div class="scanner-modal card border-0 shadow-lg">
|
||||||
|
<div class="card-body p-3 p-md-4">
|
||||||
|
<div class="d-flex align-items-center justify-content-between gap-3 mb-3">
|
||||||
|
<div>
|
||||||
|
<h2 class="h5 mb-1">Scan barcode</h2>
|
||||||
|
<p class="text-body-secondary small mb-0">Point your camera at the barcode to fill the identifier field.</p>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-sm btn-outline-secondary" type="button" @click="closeScanner()">Close</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="scanner-video-shell mb-3">
|
||||||
|
<video class="scanner-video" x-ref="scannerVideo" autoplay muted playsinline></video>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex flex-wrap align-items-center gap-2">
|
||||||
|
<div class="small text-body-secondary" x-show="scannerState.isLoading">Starting camera...</div>
|
||||||
|
<div class="small text-success" x-show="scannerState.lastDetectedCode" x-text="'Detected: ' + scannerState.lastDetectedCode"></div>
|
||||||
|
<button class="btn btn-outline-secondary btn-sm" type="button" @click="startScanner()" :disabled="scannerState.isLoading">Retry</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template x-if="scannerState.error">
|
||||||
|
<div class="alert alert-warning py-2 mt-3 mb-0" x-text="scannerState.error"></div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
@@ -366,12 +374,16 @@ export function stockDetailPageData(store) {
|
|||||||
adjustmentState: createAsyncState(),
|
adjustmentState: createAsyncState(),
|
||||||
printState: createAsyncState(),
|
printState: createAsyncState(),
|
||||||
identifierState: createAsyncState(),
|
identifierState: createAsyncState(),
|
||||||
lookupDetailsState: createAsyncState(),
|
scannerReader: null,
|
||||||
printFeedback: {
|
scannerControls: null,
|
||||||
type: '',
|
scannerState: {
|
||||||
message: '',
|
isOpen: false,
|
||||||
|
isLoading: false,
|
||||||
|
hasCamera: false,
|
||||||
|
error: '',
|
||||||
|
lastDetectedCode: '',
|
||||||
},
|
},
|
||||||
offLookupFeedback: {
|
printFeedback: {
|
||||||
type: '',
|
type: '',
|
||||||
message: '',
|
message: '',
|
||||||
},
|
},
|
||||||
@@ -384,6 +396,7 @@ export function stockDetailPageData(store) {
|
|||||||
level: 'plenty',
|
level: 'plenty',
|
||||||
},
|
},
|
||||||
async init() {
|
async init() {
|
||||||
|
this.scannerState.hasCamera = this.canUseCameraScanner();
|
||||||
if (!store.isConnected) {
|
if (!store.isConnected) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -404,72 +417,146 @@ export function stockDetailPageData(store) {
|
|||||||
this.adjustment.level = this.entry?.level || 'plenty';
|
this.adjustment.level = this.entry?.level || 'plenty';
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
},
|
},
|
||||||
normalizedIdentifierDraft() {
|
destroy() {
|
||||||
return normalizeIdentifierCode(this.identifierDraft);
|
this.stopScanner();
|
||||||
},
|
},
|
||||||
hasIdentifierCode() {
|
canUseCameraScanner() {
|
||||||
return Boolean(this.normalizedIdentifierDraft());
|
return Boolean(
|
||||||
|
typeof navigator !== 'undefined'
|
||||||
|
&& navigator.mediaDevices
|
||||||
|
&& typeof navigator.mediaDevices.getUserMedia === 'function',
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async reloadEntry(uuidB64) {
|
normalizeScannerError(error) {
|
||||||
const refreshed = await getStockEntry(store, uuidB64);
|
const message = String(error?.message || '');
|
||||||
this.entry = refreshed;
|
const normalized = message.toLowerCase();
|
||||||
this.identifierDraft = normalizeIdentifierCode(refreshed?.identifier_code);
|
|
||||||
this.adjustment.level = this.entry?.level || 'plenty';
|
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.';
|
||||||
},
|
},
|
||||||
itemLookupStatusMessage(response) {
|
async openScanner() {
|
||||||
const retryAfter = Number.isInteger(response?.retryAfterSeconds) && response.retryAfterSeconds > 0
|
this.scannerState.error = '';
|
||||||
? ` Retry in ${response.retryAfterSeconds}s.`
|
this.scannerState.lastDetectedCode = '';
|
||||||
: '';
|
this.scannerState.isOpen = true;
|
||||||
|
await this.$nextTick();
|
||||||
if (response?.status === 'missing_identifier') {
|
await this.startScanner();
|
||||||
return 'Save an identifier code before running lookup.';
|
|
||||||
}
|
|
||||||
if (response?.status === 'not_found') {
|
|
||||||
return `No OpenFoodFacts result found for code ${this.normalizedIdentifierDraft() || 'unknown'}.`;
|
|
||||||
}
|
|
||||||
if (response?.status === 'rate_limited') {
|
|
||||||
return `OpenFoodFacts lookup is temporarily rate-limited.${retryAfter}`;
|
|
||||||
}
|
|
||||||
if (response?.status === 'lookup_failed') {
|
|
||||||
return 'OpenFoodFacts lookup failed. Try again shortly or continue manually.';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'Lookup response could not be applied.';
|
|
||||||
},
|
},
|
||||||
itemLookupSuccessMessage(response) {
|
async startScanner() {
|
||||||
const parts = [
|
this.scannerState.error = '';
|
||||||
response?.update
|
this.scannerState.lastDetectedCode = '';
|
||||||
? 'Applied missing fields from OpenFoodFacts.'
|
|
||||||
: 'Fetched OpenFoodFacts details preview.',
|
|
||||||
];
|
|
||||||
const source = response?.item?.external_source || this.entry?.external_source;
|
|
||||||
|
|
||||||
if (source) {
|
if (!this.canUseCameraScanner()) {
|
||||||
parts.push(`Source: ${source}.`);
|
this.scannerState.hasCamera = false;
|
||||||
|
this.scannerState.error = 'Camera scanning is not supported in this browser. Enter the identifier code manually.';
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(response?.updatedFields) && response.updatedFields.length) {
|
const videoElement = this.$refs.scannerVideo;
|
||||||
parts.push(`Updated: ${response.updatedFields.join(', ')}.`);
|
if (!videoElement) {
|
||||||
|
this.scannerState.error = 'Scanner video element is unavailable. Close and reopen scanner.';
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response?.staleCache) {
|
this.stopScanner();
|
||||||
parts.push('Using stale cache data.');
|
this.scannerState.isLoading = true;
|
||||||
} else {
|
const shouldLogDecodeErrors = import.meta.env.DEV;
|
||||||
parts.push('Cache freshness: current.');
|
let lastDecodeErrorName = '';
|
||||||
}
|
let lastDecodeErrorAt = 0;
|
||||||
|
|
||||||
if (response?.offPayloadFetchedAt) {
|
try {
|
||||||
const fetchedAt = new Date(response.offPayloadFetchedAt);
|
if (!this.scannerReader) {
|
||||||
parts.push(
|
this.scannerReader = new BrowserMultiFormatReader();
|
||||||
`Fetched at: ${
|
}
|
||||||
Number.isNaN(fetchedAt.getTime())
|
|
||||||
? response.offPayloadFetchedAt
|
this.scannerControls = await this.scannerReader.decodeFromConstraints(
|
||||||
: fetchedAt.toLocaleString()
|
{
|
||||||
}.`,
|
audio: false,
|
||||||
|
video: {
|
||||||
|
facingMode: { ideal: 'environment' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
videoElement,
|
||||||
|
(result, error) => {
|
||||||
|
if (result) {
|
||||||
|
this.onBarcodeDetected(result.getText?.() || '');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
// Continuous decode emits expected per-frame misses/errors before a valid barcode is found.
|
||||||
|
// Keep the modal quiet and only surface startup failures from the outer catch block.
|
||||||
|
if (shouldLogDecodeErrors) {
|
||||||
|
const errorName = String(error?.name || 'UnknownError');
|
||||||
|
const now = Date.now();
|
||||||
|
if (errorName !== lastDecodeErrorName || now - lastDecodeErrorAt > 2000) {
|
||||||
|
console.debug('[scanner] Ignoring frame decode error while scanning:', errorName, error?.message || '');
|
||||||
|
lastDecodeErrorName = errorName;
|
||||||
|
lastDecodeErrorAt = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.scannerState.error = this.normalizeScannerError(error);
|
||||||
|
} finally {
|
||||||
|
this.scannerState.isLoading = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
stopScanner() {
|
||||||
|
try {
|
||||||
|
this.scannerControls?.stop?.();
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors when scanner is already stopped.
|
||||||
|
}
|
||||||
|
this.scannerControls = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.scannerReader?.reset?.();
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors from stale reader state.
|
||||||
}
|
}
|
||||||
|
|
||||||
return parts.join(' ');
|
const videoElement = this.$refs.scannerVideo;
|
||||||
|
const stream = videoElement?.srcObject;
|
||||||
|
if (stream && typeof stream.getTracks === 'function') {
|
||||||
|
stream.getTracks().forEach((track) => track.stop());
|
||||||
|
}
|
||||||
|
if (videoElement) {
|
||||||
|
videoElement.srcObject = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
closeScanner() {
|
||||||
|
this.stopScanner();
|
||||||
|
this.scannerState.isOpen = false;
|
||||||
|
this.scannerState.isLoading = false;
|
||||||
|
this.scannerState.error = '';
|
||||||
|
},
|
||||||
|
onBarcodeDetected(rawCode) {
|
||||||
|
const code = normalizeIdentifierCode(rawCode);
|
||||||
|
if (!code || !this.scannerState.isOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.identifierDraft = code;
|
||||||
|
this.scannerState.lastDetectedCode = code;
|
||||||
|
this.closeScanner();
|
||||||
|
store.addAlert({
|
||||||
|
type: 'success',
|
||||||
|
message: `Scanned identifier code: ${code}`,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
async saveIdentifierCode() {
|
async saveIdentifierCode() {
|
||||||
if (!this.entry?.uuid_b64) {
|
if (!this.entry?.uuid_b64) {
|
||||||
@@ -478,17 +565,13 @@ export function stockDetailPageData(store) {
|
|||||||
|
|
||||||
this.identifierState.error = '';
|
this.identifierState.error = '';
|
||||||
await runAsyncState(this.identifierState, async () => {
|
await runAsyncState(this.identifierState, async () => {
|
||||||
const identifierCode = this.normalizedIdentifierDraft();
|
const identifierCode = normalizeIdentifierCode(this.identifierDraft);
|
||||||
const updated = await patchStockItem(store, this.entry.uuid_b64, {
|
const updated = await updateStockItem(store, this.entry.uuid_b64, {
|
||||||
identifier_code: identifierCode || null,
|
identifier_code: identifierCode || null,
|
||||||
});
|
});
|
||||||
|
|
||||||
this.entry = updated;
|
this.entry = updated;
|
||||||
this.identifierDraft = normalizeIdentifierCode(updated?.identifier_code || identifierCode);
|
this.identifierDraft = normalizeIdentifierCode(updated?.identifier_code || identifierCode);
|
||||||
this.offLookupFeedback = {
|
|
||||||
type: '',
|
|
||||||
message: '',
|
|
||||||
};
|
|
||||||
store.addAlert({
|
store.addAlert({
|
||||||
type: 'success',
|
type: 'success',
|
||||||
message: identifierCode
|
message: identifierCode
|
||||||
@@ -497,56 +580,6 @@ export function stockDetailPageData(store) {
|
|||||||
});
|
});
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
},
|
},
|
||||||
async runItemLookup(update) {
|
|
||||||
if (!this.entry?.uuid_b64) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const identifierCode = this.normalizedIdentifierDraft();
|
|
||||||
if (!identifierCode) {
|
|
||||||
this.offLookupFeedback = {
|
|
||||||
type: 'warning',
|
|
||||||
message: 'Save an identifier code before running lookup refresh.',
|
|
||||||
};
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lookupDetailsState.error = '';
|
|
||||||
await runAsyncState(this.lookupDetailsState, async () => {
|
|
||||||
const response = await lookupItemDetails(store, this.entry.uuid_b64, { update });
|
|
||||||
if (response.status !== 'ok') {
|
|
||||||
const message = this.itemLookupStatusMessage(response);
|
|
||||||
this.offLookupFeedback = {
|
|
||||||
type: 'warning',
|
|
||||||
message,
|
|
||||||
};
|
|
||||||
store.addAlert({ type: 'warning', message });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (update) {
|
|
||||||
await this.reloadEntry(this.entry.uuid_b64);
|
|
||||||
} else if (response.item) {
|
|
||||||
this.entry = response.item;
|
|
||||||
this.identifierDraft = normalizeIdentifierCode(response.item.identifier_code || identifierCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
const message = this.itemLookupSuccessMessage(response);
|
|
||||||
this.offLookupFeedback = {
|
|
||||||
type: 'success',
|
|
||||||
message,
|
|
||||||
};
|
|
||||||
store.addAlert({
|
|
||||||
type: 'success',
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
}).catch((error) => {
|
|
||||||
this.offLookupFeedback = {
|
|
||||||
type: 'warning',
|
|
||||||
message: error?.message || 'OpenFoodFacts lookup failed.',
|
|
||||||
};
|
|
||||||
});
|
|
||||||
},
|
|
||||||
async submitMeasuredAdjustment() {
|
async submitMeasuredAdjustment() {
|
||||||
if (!this.entry) {
|
if (!this.entry) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -15,10 +15,7 @@ vi.mock('../../src/api/client.js', () => ({
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
applyItemUpsert,
|
applyItemUpsert,
|
||||||
lookupItemByIdentifier,
|
|
||||||
lookupItemDetails,
|
|
||||||
listKitchenChanges,
|
listKitchenChanges,
|
||||||
patchStockItem,
|
|
||||||
previewItemUpsert,
|
previewItemUpsert,
|
||||||
useStockItem,
|
useStockItem,
|
||||||
} = await import('../../src/api/stock.js');
|
} = await import('../../src/api/stock.js');
|
||||||
@@ -115,101 +112,6 @@ describe('api/stock', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('lookupItemByIdentifier normalizes lookup metadata fields', async () => {
|
|
||||||
apiRequestMock.mockResolvedValueOnce({
|
|
||||||
status: 'rate_limited',
|
|
||||||
source: 'openfoodfacts',
|
|
||||||
cache_hit: true,
|
|
||||||
identifier_code: '1234',
|
|
||||||
identifier_type: 'ean_13',
|
|
||||||
retry_after_seconds: 42,
|
|
||||||
payload_fetched_at: '2026-04-11T08:00:00Z',
|
|
||||||
stale_cache: true,
|
|
||||||
item: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await lookupItemByIdentifier(
|
|
||||||
{ config: { database: 'db' } },
|
|
||||||
'1234',
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(response).toEqual({
|
|
||||||
status: 'rate_limited',
|
|
||||||
source: 'openfoodfacts',
|
|
||||||
cacheHit: true,
|
|
||||||
identifierCode: '1234',
|
|
||||||
identifierType: 'ean_13',
|
|
||||||
retryAfterSeconds: 42,
|
|
||||||
payloadFetchedAt: '2026-04-11T08:00:00Z',
|
|
||||||
staleCache: true,
|
|
||||||
item: null,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lookupItemDetails maps item lookup response and query flag', async () => {
|
|
||||||
apiRequestMock.mockResolvedValueOnce({
|
|
||||||
status: 'ok',
|
|
||||||
found: true,
|
|
||||||
update: true,
|
|
||||||
identifier_code: '555',
|
|
||||||
identifier_type: 'ean_13',
|
|
||||||
preview: { name: 'Milk' },
|
|
||||||
updated_fields: ['name'],
|
|
||||||
off_payload_fetched_at: '2026-04-11T09:00:00Z',
|
|
||||||
retry_after_seconds: null,
|
|
||||||
stale_cache: false,
|
|
||||||
item: { uuid_b64: 'item-1', name: 'Milk' },
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await lookupItemDetails(
|
|
||||||
{ config: { database: 'db' } },
|
|
||||||
'item-1',
|
|
||||||
{ update: true },
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(apiRequestMock).toHaveBeenCalledWith(
|
|
||||||
{ config: { database: 'db' } },
|
|
||||||
'kitchen/items/item-1/lookup',
|
|
||||||
{ method: 'POST', query: { update: 1 } },
|
|
||||||
);
|
|
||||||
expect(response).toEqual({
|
|
||||||
status: 'ok',
|
|
||||||
found: true,
|
|
||||||
update: true,
|
|
||||||
identifierCode: '555',
|
|
||||||
identifierType: 'ean_13',
|
|
||||||
preview: { name: 'Milk' },
|
|
||||||
updatedFields: ['name'],
|
|
||||||
offPayloadFetchedAt: '2026-04-11T09:00:00Z',
|
|
||||||
retryAfterSeconds: null,
|
|
||||||
staleCache: false,
|
|
||||||
item: { uuid_b64: 'item-1', name: 'Milk' },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('patchStockItem sends PATCH to item endpoint', async () => {
|
|
||||||
apiRequestMock.mockResolvedValueOnce({
|
|
||||||
uuid_b64: 'item-1',
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await patchStockItem(
|
|
||||||
{ config: { database: 'db' } },
|
|
||||||
'item-1',
|
|
||||||
{ identifier_code: '3830012345678' },
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(apiRequestMock).toHaveBeenCalledWith(
|
|
||||||
{ config: { database: 'db' } },
|
|
||||||
'kitchen/items/item-1',
|
|
||||||
{ method: 'PATCH', body: { identifier_code: '3830012345678' } },
|
|
||||||
);
|
|
||||||
expect(response).toEqual({
|
|
||||||
uuid_b64: 'item-1',
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('useStockItem returns used on 204', async () => {
|
it('useStockItem returns used on 204', async () => {
|
||||||
apiRequestMock.mockResolvedValueOnce(null);
|
apiRequestMock.mockResolvedValueOnce(null);
|
||||||
|
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
|
||||||
|
|
||||||
const lookupItemByIdentifierMock = vi.fn();
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/stock.js', () => ({
|
|
||||||
applyItemUpsert: vi.fn(),
|
|
||||||
previewItemUpsert: vi.fn(),
|
|
||||||
searchItemDefinitions: vi.fn(async () => []),
|
|
||||||
lookupItemByIdentifier: (...args) => lookupItemByIdentifierMock(...args),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/labels.js', () => ({
|
|
||||||
previewLabel: vi.fn(async () => ({ objectUrl: 'blob:preview' })),
|
|
||||||
printItemLabel: vi.fn(async () => null),
|
|
||||||
formatPrintErrorMessage: (error) => error?.message || 'Printing failed.',
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/locations.js', () => ({
|
|
||||||
fetchLocations: vi.fn(async () => ({ flat: [], tree: [] })),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const { labelCreatePageData } = await import('../../../src/features/labels/label-create-page.js');
|
|
||||||
|
|
||||||
describe('label identifier lookup feedback', () => {
|
|
||||||
it('shows retry hint for rate-limited lookup responses', () => {
|
|
||||||
const data = labelCreatePageData({
|
|
||||||
isConnected: false,
|
|
||||||
activeKitchen: { id: 1 },
|
|
||||||
addAlert: vi.fn(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const message = data.lookupStatusMessageWithDetails(
|
|
||||||
{ status: 'rate_limited', retryAfterSeconds: 30 },
|
|
||||||
'3830012345678',
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(message).toContain('rate-limited');
|
|
||||||
expect(message).toContain('Retry in 30s');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('builds metadata-aware success message with source/cache/freshness context', () => {
|
|
||||||
const data = labelCreatePageData({
|
|
||||||
isConnected: false,
|
|
||||||
activeKitchen: { id: 1 },
|
|
||||||
addAlert: vi.fn(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const message = data.lookupSuccessMessage({
|
|
||||||
source: 'openfoodfacts',
|
|
||||||
cacheHit: true,
|
|
||||||
staleCache: true,
|
|
||||||
payloadFetchedAt: '2026-04-11T09:00:00Z',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(message).toContain('OpenFoodFacts');
|
|
||||||
expect(message).toContain('cache hit');
|
|
||||||
expect(message).toContain('stale cache');
|
|
||||||
expect(message).toContain('fetched:');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('applies non-ok lookup status as warning message with details', async () => {
|
|
||||||
lookupItemByIdentifierMock.mockResolvedValueOnce({
|
|
||||||
status: 'rate_limited',
|
|
||||||
retryAfterSeconds: 45,
|
|
||||||
source: 'openfoodfacts',
|
|
||||||
cacheHit: false,
|
|
||||||
staleCache: false,
|
|
||||||
item: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
const addAlert = vi.fn();
|
|
||||||
const data = labelCreatePageData({
|
|
||||||
isConnected: false,
|
|
||||||
activeKitchen: { id: 1 },
|
|
||||||
addAlert,
|
|
||||||
});
|
|
||||||
data.form.identifierCode = '3830012345678';
|
|
||||||
|
|
||||||
await data.lookupIdentifierDetails();
|
|
||||||
|
|
||||||
expect(data.lookupState.error).toContain('Retry in 45s');
|
|
||||||
expect(addAlert).toHaveBeenCalledWith({
|
|
||||||
type: 'warning',
|
|
||||||
message: data.lookupState.error,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -7,8 +7,6 @@ vi.mock('../../../src/api/stock.js', () => ({
|
|||||||
useStockItem: (...args) => useStockItemMock(...args),
|
useStockItem: (...args) => useStockItemMock(...args),
|
||||||
getStockEntry: (...args) => getStockEntryMock(...args),
|
getStockEntry: (...args) => getStockEntryMock(...args),
|
||||||
adjustStockEntry: vi.fn(),
|
adjustStockEntry: vi.fn(),
|
||||||
lookupItemDetails: vi.fn(),
|
|
||||||
patchStockItem: vi.fn(),
|
|
||||||
listStockEntries: vi.fn(),
|
listStockEntries: vi.fn(),
|
||||||
listGroupedStockEntries: vi.fn(),
|
listGroupedStockEntries: vi.fn(),
|
||||||
updateStockItem: vi.fn(),
|
updateStockItem: vi.fn(),
|
||||||
|
|||||||
@@ -1,127 +0,0 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
|
|
||||||
const lookupItemDetailsMock = vi.fn();
|
|
||||||
const patchStockItemMock = vi.fn();
|
|
||||||
const getStockEntryMock = vi.fn();
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/stock.js', () => ({
|
|
||||||
adjustStockEntry: vi.fn(),
|
|
||||||
getStockEntry: (...args) => getStockEntryMock(...args),
|
|
||||||
lookupItemDetails: (...args) => lookupItemDetailsMock(...args),
|
|
||||||
patchStockItem: (...args) => patchStockItemMock(...args),
|
|
||||||
useStockItem: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/labels.js', () => ({
|
|
||||||
printItemLabel: vi.fn(),
|
|
||||||
formatPrintErrorMessage: (error) => error?.message || 'Printing failed.',
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../../src/api/locations.js', () => ({
|
|
||||||
fetchLocations: vi.fn(async () => ({ flat: [], tree: [] })),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const { stockDetailPageData } = await import('../../../src/features/stock/stock-detail-page.js');
|
|
||||||
|
|
||||||
describe('stock detail identifier and OFF lookup', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
lookupItemDetailsMock.mockReset();
|
|
||||||
patchStockItemMock.mockReset();
|
|
||||||
getStockEntryMock.mockReset();
|
|
||||||
globalThis.window = {
|
|
||||||
__loncApp: {
|
|
||||||
navigate: vi.fn(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
delete globalThis.window;
|
|
||||||
});
|
|
||||||
|
|
||||||
it('saves normalized identifier code via PATCH', async () => {
|
|
||||||
patchStockItemMock.mockResolvedValueOnce({
|
|
||||||
uuid_b64: 'item-1',
|
|
||||||
name: 'Milk',
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
});
|
|
||||||
|
|
||||||
const addAlert = vi.fn();
|
|
||||||
const store = { addAlert, isConnected: false };
|
|
||||||
const data = stockDetailPageData(store);
|
|
||||||
data.entry = { uuid_b64: 'item-1', name: 'Milk', identifier_code: '' };
|
|
||||||
data.identifierDraft = ' 3830 0123 45678 ';
|
|
||||||
|
|
||||||
await data.saveIdentifierCode();
|
|
||||||
|
|
||||||
expect(patchStockItemMock).toHaveBeenCalledWith(store, 'item-1', {
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
});
|
|
||||||
expect(data.identifierDraft).toBe('3830012345678');
|
|
||||||
expect(addAlert).toHaveBeenCalledWith({
|
|
||||||
type: 'success',
|
|
||||||
message: 'Identifier code saved for Milk.',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refreshes OFF details and surfaces stale-cache metadata', async () => {
|
|
||||||
lookupItemDetailsMock.mockResolvedValueOnce({
|
|
||||||
status: 'ok',
|
|
||||||
update: false,
|
|
||||||
updatedFields: ['name', 'nutrition_facts'],
|
|
||||||
staleCache: true,
|
|
||||||
offPayloadFetchedAt: '2026-04-11T09:00:00Z',
|
|
||||||
item: {
|
|
||||||
uuid_b64: 'item-1',
|
|
||||||
name: 'Milk',
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const addAlert = vi.fn();
|
|
||||||
const store = { addAlert, isConnected: false };
|
|
||||||
const data = stockDetailPageData(store);
|
|
||||||
data.entry = { uuid_b64: 'item-1', name: 'Milk', identifier_code: '3830012345678' };
|
|
||||||
data.identifierDraft = '3830012345678';
|
|
||||||
|
|
||||||
await data.runItemLookup(false);
|
|
||||||
|
|
||||||
expect(lookupItemDetailsMock).toHaveBeenCalledWith(store, 'item-1', { update: false });
|
|
||||||
expect(data.offLookupFeedback.type).toBe('success');
|
|
||||||
expect(data.offLookupFeedback.message).toContain('Using stale cache data.');
|
|
||||||
expect(addAlert).toHaveBeenCalledWith({
|
|
||||||
type: 'success',
|
|
||||||
message: data.offLookupFeedback.message,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('apply missing fields reloads entry after successful lookup', async () => {
|
|
||||||
lookupItemDetailsMock.mockResolvedValueOnce({
|
|
||||||
status: 'ok',
|
|
||||||
update: true,
|
|
||||||
updatedFields: ['description'],
|
|
||||||
staleCache: false,
|
|
||||||
offPayloadFetchedAt: null,
|
|
||||||
item: null,
|
|
||||||
});
|
|
||||||
getStockEntryMock.mockResolvedValueOnce({
|
|
||||||
uuid_b64: 'item-1',
|
|
||||||
name: 'Milk',
|
|
||||||
identifier_code: '3830012345678',
|
|
||||||
description: 'Whole milk',
|
|
||||||
});
|
|
||||||
|
|
||||||
const addAlert = vi.fn();
|
|
||||||
const store = { addAlert, isConnected: false };
|
|
||||||
const data = stockDetailPageData(store);
|
|
||||||
data.entry = { uuid_b64: 'item-1', name: 'Milk', identifier_code: '3830012345678' };
|
|
||||||
data.identifierDraft = '3830012345678';
|
|
||||||
|
|
||||||
await data.runItemLookup(true);
|
|
||||||
|
|
||||||
expect(getStockEntryMock).toHaveBeenCalledWith(store, 'item-1');
|
|
||||||
expect(data.entry.description).toBe('Whole milk');
|
|
||||||
expect(data.offLookupFeedback.type).toBe('success');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -12,8 +12,6 @@ vi.mock('../../../src/api/stock.js', () => ({
|
|||||||
getStockEntry: vi.fn(),
|
getStockEntry: vi.fn(),
|
||||||
adjustStockEntry: vi.fn(),
|
adjustStockEntry: vi.fn(),
|
||||||
useStockItem: vi.fn(),
|
useStockItem: vi.fn(),
|
||||||
lookupItemDetails: vi.fn(),
|
|
||||||
patchStockItem: vi.fn(),
|
|
||||||
listStockEntries: vi.fn(async () => []),
|
listStockEntries: vi.fn(async () => []),
|
||||||
listGroupedStockEntries: vi.fn(async () => []),
|
listGroupedStockEntries: vi.fn(async () => []),
|
||||||
updateStockItem: vi.fn(),
|
updateStockItem: vi.fn(),
|
||||||
|
|||||||
Reference in New Issue
Block a user