Add label printing functionality and error handling in stock and label flows
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful

This commit is contained in:
2026-04-10 22:08:01 +02:00
parent 1dc1bb4912
commit e1383c4d56
10 changed files with 627 additions and 21 deletions
+290 -2
View File
@@ -3,10 +3,86 @@ import {
getStockEntry,
useStockItem,
} from '../../api/stock.js';
import { formatPrintErrorMessage, printItemLabel } from '../../api/labels.js';
import { fetchLocations } from '../../api/locations.js';
import { getRouteContext } from '../../app/router.js';
import { createAsyncState, runAsyncState } from '../shared/ui-state.js';
import { formatDate } from '../shared/date-utils.js';
function todayAtMidnight() {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
}
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 expirationInfo(entry) {
if (!entry?.expire_date) {
return {
key: 'none',
label: 'No expiration date',
detail: 'No expiration date',
};
}
const expireDate = parseDateValue(entry.expire_date);
const expireIn =
typeof entry.expire_in === 'number'
? entry.expire_in
: expireDate
? Math.round((expireDate - todayAtMidnight()) / (24 * 60 * 60 * 1000))
: null;
if (expireIn === null) {
return {
key: 'none',
label: 'No expiration date',
detail: 'No expiration date',
};
}
if (expireIn < 0) {
return {
key: 'expired',
label: 'Expired',
detail: `Expired ${Math.abs(expireIn)} day${Math.abs(expireIn) === 1 ? '' : 's'} ago`,
};
}
if (expireIn <= 2) {
return {
key: 'use-first',
label: expireIn === 0 ? 'Use today' : 'Use first',
detail: expireIn === 0 ? 'Expires today' : `Expires in ${expireIn} day${expireIn === 1 ? '' : 's'}`,
};
}
if (expireIn <= 7) {
return {
key: 'upcoming',
label: 'Upcoming expiration',
detail: `Expires in ${expireIn} days`,
};
}
return {
key: 'within-date',
label: 'Within date',
detail: `Expires in ${expireIn} days`,
};
}
export function renderStockDetailPage() {
return `
<section class="container-xxl py-4 py-lg-5" x-data="stockDetailPage()" x-init="init()">
@@ -42,14 +118,45 @@ export function renderStockDetailPage() {
<dt class="col-5">Quantity</dt>
<dd class="col-7" x-text="formatQuantity(entry)"></dd>
<dt class="col-5">Location</dt>
<dd class="col-7" x-text="entry.location_initial_uuid_b64 || 'Unassigned'"></dd>
<dd class="col-7" x-text="locationLabel(entry)"></dd>
<dt class="col-5">Production date</dt>
<dd class="col-7" x-text="formatDate(entry.date)"></dd>
<dt class="col-5">Expiration date</dt>
<dd class="col-7" x-text="formatDate(entry.expire_date)"></dd>
<dt class="col-5">Expiration status</dt>
<dd class="col-7">
<div class="d-flex align-items-center gap-2 mb-1">
<span class="badge rounded-pill" :class="expirationBadgeClass(entry)" x-text="expirationFor(entry).label"></span>
</div>
<div class="small text-body-secondary" x-text="expirationFor(entry).detail"></div>
</dd>
<dt class="col-5">Stock type</dt>
<dd class="col-7" x-text="entry.stock_type || 'Stored'"></dd>
</dl>
<div class="mt-4">
<h3 class="h6 mb-3">Nutrition</h3>
<dl class="row mb-0 detail-grid">
<dt class="col-5">Nutri-Score</dt>
<dd class="col-7" x-text="nutriScoreLabel(entry)"></dd>
<dt class="col-5">Nutriments</dt>
<dd class="col-7">
<template x-if="nutritionFactsRows(entry).length">
<ul class="list-unstyled mb-0 small d-grid gap-1">
<template x-for="fact in nutritionFactsRows(entry)" :key="fact.key">
<li>
<span class="text-body-secondary" x-text="fact.label + ':'"></span>
<span class="fw-semibold" x-text="fact.value"></span>
</li>
</template>
</ul>
</template>
<template x-if="!nutritionFactsRows(entry).length">
<span class="text-body-secondary">Not available</span>
</template>
</dd>
</dl>
</div>
</div>
</div>
</div>
@@ -83,12 +190,23 @@ export function renderStockDetailPage() {
<template x-if="adjustmentState.error">
<div class="alert alert-danger mb-0" x-text="adjustmentState.error"></div>
</template>
<template x-if="printFeedback.message">
<div
class="alert mb-0"
:class="printFeedback.type === 'success' ? 'alert-success' : 'alert-warning'"
x-text="printFeedback.message"
></div>
</template>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-primary" type="submit" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Save quantity</span>
<span x-show="adjustmentState.isLoading">Saving...</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>
<button class="btn btn-outline-danger" type="button" @click="markGone()" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark gone</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
@@ -114,12 +232,23 @@ export function renderStockDetailPage() {
<template x-if="adjustmentState.error">
<div class="alert alert-danger mb-0" x-text="adjustmentState.error"></div>
</template>
<template x-if="printFeedback.message">
<div
class="alert mb-0"
:class="printFeedback.type === 'success' ? 'alert-success' : 'alert-warning'"
x-text="printFeedback.message"
></div>
</template>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-primary" type="submit" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Save stock level</span>
<span x-show="adjustmentState.isLoading">Saving...</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>
<button class="btn btn-outline-danger" type="button" @click="markGone()" :disabled="adjustmentState.isLoading">
<span x-show="!adjustmentState.isLoading">Mark gone</span>
<span x-show="adjustmentState.isLoading">Removing...</span>
@@ -137,11 +266,22 @@ export function renderStockDetailPage() {
<template x-if="adjustmentState.error">
<div class="alert alert-danger mb-0" x-text="adjustmentState.error"></div>
</template>
<template x-if="printFeedback.message">
<div
class="alert mb-0"
:class="printFeedback.type === 'success' ? 'alert-success' : 'alert-warning'"
x-text="printFeedback.message"
></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>
<span x-show="adjustmentState.isLoading">Removing...</span>
</button>
<button class="btn btn-outline-secondary align-self-start" 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>
@@ -157,7 +297,13 @@ export function stockDetailPageData(store) {
return {
state: createAsyncState(),
adjustmentState: createAsyncState(),
printState: createAsyncState(),
printFeedback: {
type: '',
message: '',
},
entry: null,
locationPathByUuid: {},
adjustment: {
mode: 'increment',
quantity: '1',
@@ -170,7 +316,16 @@ export function stockDetailPageData(store) {
const { params } = getRouteContext();
await runAsyncState(this.state, async () => {
this.entry = await getStockEntry(store, params.id);
const [entry, locations] = await Promise.all([
getStockEntry(store, params.id),
fetchLocations(store).catch(() => ({ flat: [] })),
]);
this.entry = entry;
this.locationPathByUuid = Object.fromEntries(
(locations.flat || [])
.filter((location) => location.uuid_b64)
.map((location) => [location.uuid_b64, location.pathLabel || location.name]),
);
this.adjustment.level = this.entry?.level || 'plenty';
}).catch(() => {});
},
@@ -236,11 +391,144 @@ export function stockDetailPageData(store) {
window.__loncApp.navigate('/stock');
}).catch(() => {});
},
async printLabel() {
if (!this.entry?.uuid_b64) {
return;
}
this.printFeedback = {
type: '',
message: '',
};
await runAsyncState(this.printState, async () => {
try {
await printItemLabel(store, this.entry.uuid_b64);
this.printFeedback = {
type: 'success',
message: 'Label printed successfully.',
};
store.addAlert({
type: 'success',
message: `${this.entry.name} label sent to printer.`,
});
} catch (error) {
const parsed = formatPrintErrorMessage(error);
this.printFeedback = {
type: 'warning',
message: parsed,
};
store.addAlert({
type: 'warning',
message: `Could not print ${this.entry.name} label: ${parsed}`,
});
}
}).catch(() => {});
},
quickAdjust(step) {
const current = Number(this.adjustment.quantity || 0);
this.adjustment.quantity = String(Math.max(current + step, 0));
},
formatDate,
expirationFor(entry) {
return expirationInfo(entry);
},
expirationBadgeClass(entry) {
const key = this.expirationFor(entry).key;
if (key === 'expired') {
return 'text-bg-danger';
}
if (key === 'use-first') {
return 'text-bg-warning';
}
if (key === 'upcoming') {
return 'text-bg-secondary';
}
if (key === 'within-date') {
return 'text-bg-success';
}
return 'text-bg-light border';
},
locationLabel(entry) {
const locationUuid = entry?.location_initial_uuid_b64;
if (!locationUuid) {
return 'Unassigned';
}
return this.locationPathByUuid[locationUuid] || 'Location not resolved';
},
nutriScoreLabel(entry) {
const value = entry?.nutriscore_grade;
if (!value) {
return 'Not available';
}
return String(value).toUpperCase();
},
nutritionFactsRows(entry) {
const facts = entry?.nutrition_facts;
if (!facts || typeof facts !== 'object' || Array.isArray(facts)) {
return [];
}
const preferredOrder = [
'per',
'serving_size',
'energy_kj',
'energy_kcal',
'fat',
'saturated_fat',
'carbohydrates',
'sugars',
'fibers',
'proteins',
'salt',
'sodium',
];
const rankByKey = new Map(preferredOrder.map((key, index) => [key, index]));
return Object.entries(facts)
.sort(([leftKey], [rightKey]) => {
const leftRank = rankByKey.has(leftKey) ? rankByKey.get(leftKey) : Number.POSITIVE_INFINITY;
const rightRank = rankByKey.has(rightKey) ? rankByKey.get(rightKey) : Number.POSITIVE_INFINITY;
if (leftRank !== rightRank) {
return leftRank - rightRank;
}
return leftKey.localeCompare(rightKey);
})
.map(([key, value]) => ({
key,
label: this.nutritionLabel(key),
value: this.formatNutritionValue(value),
}));
},
nutritionLabel(key) {
const labels = {
per: 'Per',
serving_size: 'Serving size',
energy_kj: 'Energy (kJ)',
energy_kcal: 'Energy (kcal)',
fat: 'Fat',
saturated_fat: 'Saturated fat',
carbohydrates: 'Carbohydrates',
sugars: 'Sugars',
fibers: 'Fibers',
proteins: 'Proteins',
salt: 'Salt',
sodium: 'Sodium',
};
return labels[key] || key.replace(/_/g, ' ');
},
formatNutritionValue(value) {
if (value === null || value === undefined || value === '') {
return 'n/a';
}
return String(value);
},
formatQuantity(entry) {
return `${entry.quantity ?? 0} ${entry.uom_symbol || ''}`.trim();
},
+46 -2
View File
@@ -660,7 +660,7 @@ export function renderStockListPage() {
<div class="grouped-stock-items">
<template x-for="item in group.items" :key="item.id">
<a class="grouped-stock-item text-decoration-none" :class="groupedItemClass(item)" :href="detailHref(item)">
<div class="grouped-stock-item" :class="groupedItemClass(item)">
<div class="d-flex flex-column flex-lg-row justify-content-between gap-2">
<div>
<div class="fw-semibold" x-text="item.name"></div>
@@ -669,6 +669,7 @@ export function renderStockListPage() {
<span class="grouped-stock-subline-separator" aria-hidden="true">•</span>
<span x-text="shortDescription(item.description)"></span>
</div>
<a class="small text-decoration-none fw-semibold" :href="detailHref(item)">View item</a>
</div>
<div class="d-flex flex-wrap gap-3 small text-body-secondary grouped-stock-item-meta">
<span x-text="quantityLabel(item)"></span>
@@ -678,9 +679,13 @@ export function renderStockListPage() {
<span x-text="formatDate(item.expire_date)"></span>
</span>
<span class="font-monospace" x-text="shortId(item)"></span>
<button class="btn btn-sm btn-outline-danger grouped-stock-mark-gone" type="button" @click="markGoneFromGroup(item, group)">Mark gone</button>
</div>
</div>
</a>
<template x-if="editErrors[item.id]">
<div class="small text-danger mt-2" x-text="editErrors[item.id]"></div>
</template>
</div>
</template>
</div>
@@ -1231,6 +1236,26 @@ export function stockListPageData(store) {
async markGone(entry) {
await this.useEntry(entry);
},
async markGoneFromGroup(item, group) {
this.editErrors[item.id] = '';
try {
const result = await useStockItem(store, item.uuid_b64);
const alreadyGone = result.status === 'already_gone';
this.removeGroupedItem(group.id, item.id);
this.entries = this.entries.filter((candidate) => candidate.id !== item.id);
delete this.editForms[item.id];
delete this.editErrors[item.id];
store.addAlert({
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.`,
});
} catch (error) {
this.editErrors[item.id] = error.message || 'Mark gone failed.';
}
},
async saveEntryUpdate(entry, payload, localPatch) {
this.editErrors[entry.id] = '';
@@ -1273,5 +1298,24 @@ export function stockListPageData(store) {
quantity: nextEntry.quantity ?? '',
};
},
removeGroupedItem(groupId, itemId) {
this.groupedEntries = this.groupedEntries
.map((group) => {
if (group.id !== groupId) {
return group;
}
const nextItems = (group.items || []).filter((candidate) => candidate.id !== itemId);
if (!nextItems.length) {
return null;
}
return {
...group,
items: nextItems,
};
})
.filter(Boolean);
},
};
}