fix(frontend): #37 punti 1,4,5,6 - 502 backend giù, barcode quotato, apici Alpine, paginazione ricette

1. api_client.py: ConnectionError/Timeout restituisce status_code=502 invece
   di 0 (nessuna route confrontava == 0, verificato); i proxy che inoltrano
   resp.get("status_code", 500) ereditano il fix senza altre modifiche.
4. measure.py lookup_barcode: code non stringa -> 400 (prima 500 su
   code.strip()); urllib.parse.quote(code, safe="") prima di comporre l'URL
   verso il backend - un barcode con '/' o '../' non spezza più il path né
   raggiunge altri GET con i permessi dell'utente.
5. Ogni "'{{ _(...) }}'" dentro un attributo Alpine (x-text, :title,
   :placeholder, @click) sostituito con "{{ _(...)|tojson_attr }}": la
   traduzione EN di admin/stations.html:105 ("Clear the station's recipes")
   ha un apostrofo che l'IT non ha, e rompeva quel binding e basta - non è
   un XSS, ma stessa classe di difetto di #10. File toccati: admin/stations,
   admin/users, maker/recipe_list, maker/recipe_editor, maker/task_editor,
   maker/task_drawing, components/caliper_status, measure/select_recipe.
   Le occorrenze dentro <script>...</script> (non attributi) sono fuori
   perimetro per questo punto.
6. statistics.py dashboard(): ciclo sulle pagine (per_page=100, il massimo
   del backend) invece di un'unica chiamata che troncava la tendina ricette
   alla centesima.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 23:03:06 +02:00
parent c0583da478
commit 72f0cb1f1b
15 changed files with 218 additions and 50 deletions
+13 -2
View File
@@ -1,4 +1,6 @@
"""MeasurementTec blueprint - recipe selection and measurement execution."""
import urllib.parse
from flask import (
Blueprint, abort, flash, jsonify, redirect, render_template,
request, session, url_for,
@@ -449,12 +451,21 @@ def task_complete(recipe_id: int):
def lookup_barcode():
"""Look up a recipe by barcode/code. Returns JSON for AJAX calls."""
data = request.get_json(silent=True) or {}
code = data.get("code", "").strip()
code = data.get("code", "")
# #37.4: a non-string "code" (e.g. {"code": 5}) crashed .strip() into a
# 500. A slash in the code (or "../") used to walk straight into the URL
# path unescaped - "AB/123" split into segments the backend never
# matched, and "../" could reach another GET endpoint with this user's
# permissions.
if not isinstance(code, str):
return jsonify({"error": True, "detail": _("Codice non valido")}), 400
code = code.strip()
if not code:
return jsonify({"error": True, "detail": _("Codice non fornito")}), 400
resp = api_client.get(f"/api/recipes/code/{code}")
resp = api_client.get(f"/api/recipes/code/{urllib.parse.quote(code, safe='')}")
if resp.get("error"):
return jsonify({
"error": True,
@@ -20,11 +20,22 @@ statistics_bp = Blueprint("statistics", __name__)
@role_required("Metrologist")
def dashboard():
"""SPC dashboard overview — loads recipes for filter dropdown."""
resp = api_client.get("/api/recipes", params={"per_page": 100})
if isinstance(resp, dict) and resp.get("error"):
recipes = []
else:
recipes = resp.get("items", []) if isinstance(resp, dict) else []
# #37.6: a single per_page=100 call silently dropped every recipe past
# the 100th from the filter dropdown. 100 is the backend's max per_page
# (routers/recipes.py), so a full listing needs a page loop, not a
# bigger number.
recipes = []
page = 1
while True:
resp = api_client.get("/api/recipes", params={"per_page": 100, "page": page})
if isinstance(resp, dict) and resp.get("error"):
break
page_items = resp.get("items", []) if isinstance(resp, dict) else []
recipes.extend(page_items)
total_pages = resp.get("pages", 1) if isinstance(resp, dict) else 1
if page >= total_pages or not page_items:
break
page += 1
return render_template("statistics/dashboard.html", recipes=recipes)
@@ -113,9 +113,13 @@ class APIClient:
)
return self._handle_response(response)
except (requests.ConnectionError, requests.Timeout) as e:
# 502, not 0 (#37.1): a route that forwards status_code straight to
# jsonify(...), status_code was answering with a made-up HTTP status
# that Werkzeug doesn't know ("0 UNKNOWN"), instead of a real one a
# fetch caller can branch on.
return {
"error": True,
"status_code": 0,
"status_code": 502,
"detail": f"Errore di connessione al server: {str(e)}"
}
@@ -146,7 +150,7 @@ class APIClient:
except (requests.ConnectionError, requests.Timeout) as e:
return {
"error": True,
"status_code": 0,
"status_code": 502,
"detail": f"Errore di connessione al server: {str(e)}"
}
@@ -163,7 +167,7 @@ class APIClient:
except (requests.ConnectionError, requests.Timeout) as e:
return {
"error": True,
"status_code": 0,
"status_code": 502,
"detail": f"Errore di connessione al server: {str(e)}"
}
@@ -179,7 +183,7 @@ class APIClient:
except (requests.ConnectionError, requests.Timeout) as e:
return {
"error": True,
"status_code": 0,
"status_code": 502,
"detail": f"Errore di connessione al server: {str(e)}"
}
@@ -86,13 +86,13 @@
:class="station.active
? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300'
: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300'"
x-text="station.active ? '{{ _('Attiva') }}' : '{{ _('Disattivata') }}'"></span>
x-text="station.active ? {{ _('Attiva')|tojson_attr }} : {{ _('Disattivata')|tojson_attr }}"></span>
</td>
<td class="px-4 py-3 text-right" @click.stop>
<div class="flex items-center justify-end gap-1">
<button @click="openAssignmentsModal(station)"
class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-primary hover:bg-primary-50 dark:hover:bg-primary-900/20 transition-colors"
:title="'{{ _('Gestisci ricette') }}'">
:title="{{ _('Gestisci ricette')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
</svg>
@@ -102,22 +102,22 @@
class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors
disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:text-[var(--text-secondary)] disabled:hover:bg-transparent"
:title="(station.recipes && station.recipes.length)
? '{{ _('Azzera le ricette della stazione') }}'
: '{{ _('Nessuna ricetta da azzerare') }}'">
? {{ _('Azzera le ricette della stazione')|tojson_attr }}
: {{ _('Nessuna ricetta da azzerare')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992V4.356m-.582 9.66a8.25 8.25 0 01-15.356 2.008M3.985 14.652h4.992v4.992m.581-9.66a8.25 8.25 0 0115.356-2.008"/>
</svg>
</button>
<button @click="openEditModal(station)"
class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-primary hover:bg-primary-50 dark:hover:bg-primary-900/20 transition-colors"
:title="'{{ _('Modifica') }}'">
:title="{{ _('Modifica')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
</svg>
</button>
<button @click="confirmDelete(station)"
class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
:title="'{{ _('Elimina') }}'">
:title="{{ _('Elimina')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"/>
</svg>
@@ -160,7 +160,7 @@
<div class="flex items-center justify-between px-6 py-4 border-b border-[var(--border-color)]">
<h2 class="text-lg font-semibold text-[var(--text-primary)]"
x-text="isEditing ? '{{ _('Modifica Stazione') }}' : '{{ _('Nuova Stazione') }}'"></h2>
x-text="isEditing ? {{ _('Modifica Stazione')|tojson_attr }} : {{ _('Nuova Stazione')|tojson_attr }}"></h2>
<button @click="closeModal()" class="p-1 rounded-lg text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] transition-colors">
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
@@ -237,7 +237,7 @@
:disabled="saving"
class="px-4 py-2 bg-primary text-white text-sm font-medium rounded-lg
hover:bg-primary-700 transition-colors shadow-sm disabled:opacity-50">
<span x-show="!saving" x-text="isEditing ? '{{ _('Salva Modifiche') }}' : '{{ _('Crea Stazione') }}'"></span>
<span x-show="!saving" x-text="isEditing ? {{ _('Salva Modifiche')|tojson_attr }} : {{ _('Crea Stazione')|tojson_attr }}"></span>
<span x-show="saving" x-cloak>{{ _('Salvataggio...') }}</span>
</button>
</div>
@@ -299,7 +299,7 @@
:disabled="saving"
class="ml-2 inline-flex items-center gap-1 px-2.5 py-1 bg-primary text-white text-xs font-medium rounded-md
hover:bg-primary-700 transition-colors shadow-sm disabled:opacity-50"
:title="'{{ _('Assegna a questa stazione') }}'">
:title="{{ _('Assegna a questa stazione')|tojson_attr }}">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/>
</svg>
@@ -332,7 +332,7 @@
<button @click="unassignRecipe(r.id)"
:disabled="saving"
class="ml-2 p-1.5 rounded-md text-[var(--text-secondary)] hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors disabled:opacity-50"
:title="'{{ _('Rimuovi assegnazione') }}'">
:title="{{ _('Rimuovi assegnazione')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
</svg>
@@ -93,11 +93,11 @@
:class="user.active
? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300'
: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300'"
x-text="user.active ? '{{ _('Attivo') }}' : '{{ _('Disattivato') }}'"></span>
x-text="user.active ? {{ _('Attivo')|tojson_attr }} : {{ _('Disattivato')|tojson_attr }}"></span>
</td>
<td class="px-4 py-3 text-right" @click.stop>
<div class="flex items-center justify-end gap-1">
<button @click="openEditModal(user)" class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-primary hover:bg-primary-50 dark:hover:bg-primary-900/20 transition-colors" :title="'{{ _('Modifica') }}'">
<button @click="openEditModal(user)" class="p-1.5 rounded-lg text-[var(--text-secondary)] hover:text-primary hover:bg-primary-50 dark:hover:bg-primary-900/20 transition-colors" :title="{{ _('Modifica')|tojson_attr }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
</svg>
@@ -106,7 +106,7 @@
:class="user.active
? 'text-[var(--text-secondary)] hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20'
: 'text-[var(--text-secondary)] hover:text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-900/20'"
:title="user.active ? '{{ _('Disattiva') }}' : '{{ _('Riattiva') }}'">
:title="user.active ? {{ _('Disattiva')|tojson_attr }} : {{ _('Riattiva')|tojson_attr }}">
<svg x-show="user.active" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
</svg>
@@ -158,7 +158,7 @@
<!-- Modal Header -->
<div class="flex items-center justify-between px-6 py-4 border-b border-[var(--border-color)]">
<h2 class="text-lg font-semibold text-[var(--text-primary)]"
x-text="isEditing ? '{{ _('Modifica Utente') }}' : '{{ _('Nuovo Utente') }}'"></h2>
x-text="isEditing ? {{ _('Modifica Utente')|tojson_attr }} : {{ _('Nuovo Utente')|tojson_attr }}"></h2>
<button @click="closeModal()" class="p-1 rounded-lg text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] transition-colors">
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
@@ -211,7 +211,7 @@
<input type="password" x-model="form.password"
class="w-full px-3 py-2 rounded-lg border border-[var(--border-color)] bg-[var(--bg-card)]
text-sm text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-colors"
:placeholder="isEditing ? '{{ _('Nuova password (opzionale)') }}' : '{{ _('Password') }}'"
:placeholder="isEditing ? {{ _('Nuova password (opzionale)')|tojson_attr }} : {{ _('Password')|tojson_attr }}"
minlength="6">
</div>
@@ -295,7 +295,7 @@
:disabled="saving"
class="px-4 py-2 bg-primary text-white text-sm font-medium rounded-lg
hover:bg-primary-700 transition-colors shadow-sm disabled:opacity-50">
<span x-show="!saving" x-text="isEditing ? '{{ _('Salva Modifiche') }}' : '{{ _('Crea Utente') }}'"></span>
<span x-show="!saving" x-text="isEditing ? {{ _('Salva Modifiche')|tojson_attr }} : {{ _('Crea Utente')|tojson_attr }}"></span>
<span x-show="saving" x-cloak>{{ _('Salvataggio...') }}</span>
</button>
</div>
@@ -310,7 +310,7 @@
x-transition
class="relative bg-[var(--bg-card)] rounded-xl border border-[var(--border-color)] shadow-xl w-full max-w-sm p-6">
<h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2"
x-text="toggleUser?.active ? '{{ _('Conferma Disattivazione') }}' : '{{ _('Conferma Riattivazione') }}'"></h3>
x-text="toggleUser?.active ? {{ _('Conferma Disattivazione')|tojson_attr }} : {{ _('Conferma Riattivazione')|tojson_attr }}"></h3>
<p class="text-sm text-[var(--text-secondary)] mb-4">
<span x-text="toggleUser?.active
? &quot;{{ _('Sei sicuro di voler disattivare l\'utente') }}&quot;
@@ -326,7 +326,7 @@
:disabled="saving"
class="px-4 py-2 text-sm font-medium text-white rounded-lg shadow-sm disabled:opacity-50 transition-colors"
:class="toggleUser?.active ? 'bg-red-600 hover:bg-red-700' : 'bg-emerald-600 hover:bg-emerald-700'">
<span x-text="toggleUser?.active ? '{{ _('Disattiva') }}' : '{{ _('Riattiva') }}'"></span>
<span x-text="toggleUser?.active ? {{ _('Disattiva')|tojson_attr }} : {{ _('Riattiva')|tojson_attr }}"></span>
</button>
</div>
</div>
@@ -12,8 +12,8 @@
? 'bg-green-50 dark:bg-green-900/20 border-green-300 dark:border-green-700 shadow-md shadow-green-100 dark:shadow-green-900/30'
: 'bg-[var(--bg-card)] border-[var(--border-color)]'"
:title="readingCount > 0
? '{{ _('Letture calibro') }}: ' + readingCount
: '{{ _('Calibro USB') }}'">
? {{ _('Letture calibro')|tojson_attr }} + ': ' + readingCount
: {{ _('Calibro USB')|tojson_attr }}">
<!-- Status dot -->
<span class="relative flex h-2.5 w-2.5">
@@ -43,7 +43,7 @@
<!-- Label -->
<span class="text-xs font-medium transition-colors duration-300"
:class="active ? 'text-green-700 dark:text-green-300' : 'text-slate-600 dark:text-slate-400'"
x-text="active ? '{{ _('Lettura calibro') }}' : '{{ _('Calibro USB') }}'"></span>
x-text="active ? {{ _('Lettura calibro')|tojson_attr }} : {{ _('Calibro USB')|tojson_attr }}"></span>
<!-- Last reading value (shows when active or when there's a recent reading) -->
<span x-show="lastReading !== null"
@@ -104,7 +104,7 @@
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
</svg>
<span x-text="saving ? '{{ _('Salvataggio...') }}' : '{{ _('Salva') }}'"></span>
<span x-text="saving ? {{ _('Salvataggio...')|tojson_attr }} : {{ _('Salva')|tojson_attr }}"></span>
</button>
{% if not is_new %}
@@ -487,7 +487,7 @@
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
</svg>
<span x-text="saving ? '{{ _('Salvataggio...') }}' : '{{ _('Salva Ricetta') }}'"></span>
<span x-text="saving ? {{ _('Salvataggio...')|tojson_attr }} : {{ _('Salva Ricetta')|tojson_attr }}"></span>
</button>
<a href="{{ url_for('maker.recipe_list') }}"
@@ -48,11 +48,11 @@
this.deleteTarget = null;
} else {
const data = await resp.json();
alert(data.error || '{{ _('Errore durante eliminazione') }}');
alert(data.error || {{ _('Errore durante eliminazione')|tojson_attr }});
}
} catch (err) {
console.error(err);
alert('{{ _('Errore di connessione') }}');
alert({{ _('Errore di connessione')|tojson_attr }});
}
},
@@ -121,7 +121,7 @@
<input type="text"
x-model="search"
class="tmf-input !pl-10"
:placeholder="'{{ _('Cerca per nome, codice o descrizione...') }}'">
:placeholder="{{ _('Cerca per nome, codice o descrizione...')|tojson_attr }}">
</div>
</div>
@@ -141,7 +141,7 @@
<div class="mb-5">
<p class="text-sm text-[var(--text-secondary)]">
<span x-text="filteredRecipes.length"></span>
<span x-text="filteredRecipes.length === 1 ? '{{ _('ricetta trovata') }}' : '{{ _('ricette trovate') }}'"></span>
<span x-text="filteredRecipes.length === 1 ? {{ _('ricetta trovata')|tojson_attr }} : {{ _('ricette trovate')|tojson_attr }}"></span>
</p>
</div>
@@ -183,7 +183,7 @@
<!-- Status Badge -->
<span class="badge"
:class="recipe.active ? 'badge-pass' : 'badge-fail'"
x-text="recipe.active ? '{{ _('Attiva') }}' : '{{ _('Disattivata') }}'">
x-text="recipe.active ? {{ _('Attiva')|tojson_attr }} : {{ _('Disattivata')|tojson_attr }}">
</span>
</div>
@@ -278,7 +278,7 @@
<!-- Clear All -->
<button type="button"
class="anno-btn text-red-500 hover:text-red-600"
@click="if (confirm('{{ _('Eliminare tutte le annotazioni?') }}')) clearAllAnnotations()"
@click="if (confirm({{ _('Eliminare tutte le annotazioni?')|tojson_attr }})) clearAllAnnotations()"
title="{{ _('Cancella tutto') }}">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round"
@@ -219,7 +219,7 @@
<div class="mb-4 flex items-center justify-between">
<p class="text-sm text-[var(--text-secondary)]">
<span x-text="tasks.length"></span>
<span x-text="tasks.length === 1 ? '{{ _('task') }}' : '{{ _('task') }}'"></span>
<span x-text="tasks.length === 1 ? {{ _('task')|tojson_attr }} : {{ _('task')|tojson_attr }}"></span>
</p>
<div class="flex items-center gap-2">
<button @click="showAddTask = true; $nextTick(() => $refs.newTaskTitle && $refs.newTaskTitle.focus())"
@@ -679,7 +679,7 @@
x-transition
class="p-3 rounded-lg bg-[var(--bg-secondary)] border border-[var(--border-color)]">
<p class="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wide mb-3"
x-text="editingSubtaskId ? '{{ _('Modifica Misurazione') }}' : '{{ _('Nuova Misurazione') }}'">
x-text="editingSubtaskId ? {{ _('Modifica Misurazione')|tojson_attr }} : {{ _('Nuova Misurazione')|tojson_attr }}">
</p>
<div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3">
<!-- Marker Number -->
@@ -791,7 +791,7 @@
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
</svg>
<span x-text="editingSubtaskId ? '{{ _('Aggiorna Misurazione') }}' : '{{ _('Aggiungi Misurazione') }}'"></span>
<span x-text="editingSubtaskId ? {{ _('Aggiorna Misurazione')|tojson_attr }} : {{ _('Aggiungi Misurazione')|tojson_attr }}"></span>
</button>
</div>
</div>
@@ -27,8 +27,8 @@
when the production opens - this is only the earlier answer. */
missingTraceability(recipe) {
const missing = [];
if (recipe.requires_lot && !this.lot_number.trim()) missing.push('{{ _('lotto') }}');
if (recipe.requires_serial && !this.serial_number.trim()) missing.push('{{ _('seriale') }}');
if (recipe.requires_lot && !this.lot_number.trim()) missing.push({{ _('lotto')|tojson_attr }});
if (recipe.requires_serial && !this.serial_number.trim()) missing.push({{ _('seriale')|tojson_attr }});
return missing;
},
/* Straight into the first task. Choosing a recipe used to open the full
@@ -57,14 +57,14 @@
});
const data = await resp.json();
if (data.error) {
this.barcodeError = data.detail || '{{ _("Ricetta non trovata") }}';
this.barcodeError = data.detail || {{ _("Ricetta non trovata")|tojson_attr }};
} else {
// The scanner is a way in like any other: a recipe that demands a lot
// demands it here too, or the rule would last exactly as long as it
// took someone to reach for the barcode reader.
const missing = this.missingTraceability(data);
if (missing.length) {
this.barcodeError = '{{ _("Compila prima:") }} ' + missing.join(', ');
this.barcodeError = {{ _("Compila prima:")|tojson_attr }} + ' ' + missing.join(', ');
return;
}
this.barcodeModal = false;
@@ -72,7 +72,7 @@
window.location.href = this.buildTaskUrl(data.id);
}
} catch (e) {
this.barcodeError = '{{ _("Errore di connessione") }}';
this.barcodeError = {{ _("Errore di connessione")|tojson_attr }};
} finally {
this.barcodeLoading = false;
}
@@ -239,7 +239,7 @@
<!-- Description -->
<p class="mt-1 text-sm text-[var(--text-secondary)] line-clamp-2 leading-relaxed"
x-text="recipe.description || '{{ _('Nessuna descrizione disponibile') }}'">
x-text="recipe.description || {{ _('Nessuna descrizione disponibile')|tojson_attr }}">
</p>
</div>
</div>
@@ -277,7 +277,7 @@
<svg class="w-3.5 h-3.5 shrink-0 mt-px" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/>
</svg>
<span x-text="'{{ _('Compila prima:') }} ' + missingTraceability(recipe).join(', ')"></span>
<span x-text="{{ _('Compila prima:')|tojson_attr }} + ' ' + missingTraceability(recipe).join(', ')"></span>
</p>
</template>
@@ -0,0 +1,43 @@
"""#37.1: the backend being unreachable must surface as a real HTTP status.
api_client used to answer a ConnectionError/Timeout with status_code: 0,
which every proxy route forwards straight through
(``jsonify(resp), resp.get("status_code", 500)``) as the response's actual
HTTP status - and 0 is not a valid one (Werkzeug renders it "0 UNKNOWN").
502 Bad Gateway is what it actually is: this server reached out to another
one and got nothing back.
"""
import requests
import pytest
from unittest.mock import patch
from services.api_client import api_client
@pytest.mark.parametrize("exc", [requests.ConnectionError("refused"), requests.Timeout("timed out")])
@pytest.mark.parametrize("method,mocked,call_kwargs", [
("get", "services.api_client.requests.get", {}),
("post", "services.api_client.requests.post", {"data": {}}),
("put", "services.api_client.requests.put", {"data": {}}),
("delete", "services.api_client.requests.delete", {}),
])
def test_backend_unreachable_returns_502(flask_app, method, mocked, call_kwargs, exc):
with flask_app.test_request_context("/"):
with patch(mocked, side_effect=exc):
result = getattr(api_client, method)("/api/whatever", **call_kwargs)
assert result["error"] is True
assert result["status_code"] == 502
assert result["status_code"] != 0
def test_pending_authorisation_route_surfaces_502(logged_in_client):
with patch(
"services.api_client.requests.get",
side_effect=requests.ConnectionError("refused"),
):
resp = logged_in_client.get(
"/measure/api/measurements/pending-authorisation?version_id=5",
)
assert resp.status_code == 502
assert resp.get_json()["error"] is True
@@ -472,3 +472,43 @@ class TestSaveMeasurement:
assert resp.status_code == 400
data = resp.get_json()
assert data["error"] is True
class TestLookupBarcode:
"""POST /measure/lookup-barcode tests (#37.4)."""
def test_non_string_code_returns_400_not_500(self, logged_in_client, mock_api_client):
"""{"code": 5} used to reach code.strip() on an int and crash to a 500."""
resp = logged_in_client.post(
"/measure/lookup-barcode", json={"code": 5},
)
assert resp.status_code == 400
assert resp.get_json()["error"] is True
mock_api_client.get.assert_not_called()
def test_code_with_slash_is_url_quoted(
self, logged_in_client, mock_api_client, monkeypatch,
):
""""AB/123" must reach the backend as one path segment, not two."""
monkeypatch.setattr("blueprints.measure.Config.STATION_CODE", "ST-TEST")
mock_api_client.get_station_recipes.return_value = [{"id": 1}]
mock_api_client.get.return_value = {"id": 1, "code": "AB/123"}
resp = logged_in_client.post(
"/measure/lookup-barcode", json={"code": "AB/123"},
)
assert resp.status_code == 200
endpoint = mock_api_client.get.call_args[0][0]
assert endpoint == "/api/recipes/code/AB%2F123"
def test_code_with_path_traversal_is_quoted_not_walked(
self, logged_in_client, mock_api_client,
):
mock_api_client.get.return_value = {"error": True, "status_code": 404}
resp = logged_in_client.post(
"/measure/lookup-barcode", json={"code": "../users"},
)
assert resp.status_code == 404
endpoint = mock_api_client.get.call_args[0][0]
assert endpoint == "/api/recipes/code/..%2Fusers"
@@ -27,6 +27,32 @@ class TestDashboard:
assert resp.status_code == 302
assert "/auth/login" in resp.headers["Location"]
def test_dashboard_pages_past_the_first_hundred_recipes(
self, logged_in_client, mock_api_client,
):
"""#37.6: a single per_page=100 call used to drop every recipe past #100."""
page1 = {
"items": [{"id": i, "code": f"REC-{i:03d}"} for i in range(100)],
"total": 101,
"pages": 2,
}
page2 = {
"items": [{"id": 100, "code": "REC-100"}],
"total": 101,
"pages": 2,
}
mock_api_client.get.side_effect = [page1, page2]
resp = logged_in_client.get("/statistics/dashboard")
assert resp.status_code == 200
assert mock_api_client.get.call_count == 2
assert "REC-100" in resp.get_data(as_text=True)
first_call = mock_api_client.get.call_args_list[0]
second_call = mock_api_client.get.call_args_list[1]
assert first_call.kwargs["params"]["page"] == 1
assert second_call.kwargs["params"]["page"] == 2
class TestRoleRequired:
"""Metrologist role enforcement tests."""
@@ -197,6 +197,39 @@ def test_admin_stations_inline_js_is_valid(logged_in_client, mock_admin_api):
_check_alpine_attributes(html, "/admin/stations")
def test_admin_stations_inline_js_is_valid_in_english(logged_in_client, mock_admin_api):
"""gitea#37.5: the EN catalog is where this page's apostrophe actually is.
translations/en/LC_MESSAGES/messages.po: msgid "Azzera le ricette della
stazione" -> msgstr "Clear the station's recipes" (admin/stations.html:105).
The IT source string has no apostrophe, so test_admin_stations_inline_js_is_valid
(IT-only) would never have caught this - #37.5's own TEST note calls out
the EN render specifically.
"""
mock_admin_api.get.side_effect = [
[{
"id": 1, "code": "ST-DEFAULT", "name": "Default Station",
"location": None, "notes": None, "active": True,
"created_by": 1, "created_at": "2026-04-25T10:00:00",
}],
[{"id": 1, "code": "DEMO-001", "name": "Demo Recipe", "active": True}],
]
with logged_in_client.session_transaction() as sess:
sess["language"] = "en"
resp = logged_in_client.get("/admin/stations")
assert resp.status_code == 200, resp.data[:300]
html = resp.data.decode("utf-8")
assert "station" in html.lower(), "sanity check: the EN string did render"
scripts = _INLINE_SCRIPT_RX.findall(html)
for i, body in enumerate(scripts):
_node_check(body, f"/admin/stations (en) script[{i}]")
_check_alpine_attributes(html, "/admin/stations (en)")
def test_admin_users_inline_js_is_valid(logged_in_client, mock_admin_api):
"""Same guard for /admin/users (reuses the userManagement Alpine pattern)."""
mock_admin_api.get.return_value = [{