From bce920e279bb95e3868156901b8e2be519d974ca Mon Sep 17 00:00:00 2001 From: diaco Date: Mon, 5 Oct 2026 11:48:59 +0330 Subject: [PATCH] Add interactive label calibration UI Co-authored-by: Cursor --- slips/api.py | 27 ++- slips/calibration.py | 138 ++++++++++++ slips/schemas.py | 20 ++ slips/static/slips/css/label_print.css | 54 +++-- slips/static/slips/js/calibrate.js | 292 +++++++++++++++++++++++++ slips/templates/slips/calibrate.html | 280 ++++++++++++++++++++---- slips/templates/slips/print_page.html | 3 + slips/views.py | 11 +- 8 files changed, 757 insertions(+), 68 deletions(-) create mode 100644 slips/calibration.py create mode 100644 slips/static/slips/js/calibrate.js diff --git a/slips/api.py b/slips/api.py index 66acd99..714d6d4 100644 --- a/slips/api.py +++ b/slips/api.py @@ -4,7 +4,11 @@ from django.utils import timezone from ninja import NinjaAPI, Query from .models import Product, Order -from .schemas import ProductOut, ProductIn, OrderOut, OrderIn, OrderStatusIn +from .schemas import ( + ProductOut, ProductIn, OrderOut, OrderIn, OrderStatusIn, + CalibrationIn, CalibrationOut, +) +from .calibration import load_calibration, save_calibration, DEFAULTS, for_api api = NinjaAPI(title='Lithium Label API', version='1.0.0', urls_namespace='slips_api') @@ -63,3 +67,24 @@ def delete_order(request, order_id: int): order = get_object_or_404(Order, id=order_id) order.delete() return 204, None + + +# ─── Calibration ───────────────────────────────────────── + +@api.get('/calibration', response=CalibrationOut, tags=['Calibration']) +def get_calibration(request): + return for_api(load_calibration()) + + +@api.put('/calibration', response=CalibrationOut, tags=['Calibration']) +def put_calibration(request, payload: CalibrationIn): + data = payload.dict() + # Drop None optional keys so merge keeps defaults only when omitted + for field, vals in data.items(): + data[field] = {k: v for k, v in vals.items() if v is not None} + return for_api(save_calibration(data)) + + +@api.post('/calibration/reset', response=CalibrationOut, tags=['Calibration']) +def reset_calibration(request): + return for_api(save_calibration(DEFAULTS)) diff --git a/slips/calibration.py b/slips/calibration.py new file mode 100644 index 0000000..fd5c041 --- /dev/null +++ b/slips/calibration.py @@ -0,0 +1,138 @@ +"""Label field positions (mm / pt). Stored in data/calibration.json.""" +from __future__ import annotations + +import json +import os +from copy import deepcopy +from pathlib import Path + +# Matches prior label_print.css defaults (screen + print). +DEFAULTS = { + 'batch': { + 'top': 63.0, + 'left': 30.2, + 'font': 7.0, + 'bottom_top': 43.3, + 'right_left': 22.2, + }, + 'date': { + 'top': 63.0, + 'left': 67.4, + 'font': 6.0, + 'bottom_top': 43.3, + 'bottom_left': 70.4, + }, + 'next': { + 'top': 68.5, + 'left': 84.2, + 'font': 7.0, + 'bottom_top': 48.8, + 'bottom_left': 87.2, + }, + 'weight': { + 'top': 68.5, + 'left': 37.3, + 'font': 7.0, + 'bottom_top': 48.8, + 'right_left': 29.3, + }, +} + +FIELDS = ('batch', 'date', 'next', 'weight') + + +def _data_dir() -> Path: + db_env = os.environ.get('DB_PATH') + if db_env: + return Path(db_env).parent + try: + from django.conf import settings + return Path(settings.BASE_DIR) / 'data' + except Exception: + return Path(__file__).resolve().parents[1] / 'data' + + +def calibration_path() -> Path: + return _data_dir() / 'calibration.json' + + +def _merge(base: dict, overlay: dict) -> dict: + out = deepcopy(base) + for field, vals in (overlay or {}).items(): + if field not in out or not isinstance(vals, dict): + continue + for key, val in vals.items(): + if key in out[field] and isinstance(val, (int, float)): + out[field][key] = float(val) + return out + + +def load_calibration() -> dict: + path = calibration_path() + if not path.is_file(): + return deepcopy(DEFAULTS) + try: + with path.open(encoding='utf-8') as f: + data = json.load(f) + except (OSError, json.JSONDecodeError): + return deepcopy(DEFAULTS) + return _merge(DEFAULTS, data) + + +def for_api(cal: dict) -> dict: + """Ensure optional keys are present (null) for API schema.""" + out = {} + for field in FIELDS: + v = cal[field] + out[field] = { + 'top': v['top'], + 'left': v['left'], + 'font': v['font'], + 'bottom_top': v['bottom_top'], + 'bottom_left': v.get('bottom_left'), + 'right_left': v.get('right_left'), + } + return out + + +def save_calibration(data: dict) -> dict: + merged = _merge(DEFAULTS, data) + path = calibration_path() + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix('.tmp') + with tmp.open('w', encoding='utf-8') as f: + json.dump(merged, f, indent=2) + f.write('\n') + tmp.replace(path) + return merged + + +def css_vars(cal: dict | None = None) -> str: + """Inline :root block for print + calibrate pages.""" + cal = cal or load_calibration() + lines = [':root {'] + for field in FIELDS: + v = cal[field] + lines.append(f' --{field}-top: {v["top"]}mm;') + lines.append(f' --{field}-left: {v["left"]}mm;') + lines.append(f' --{field}-font: {v["font"]}pt;') + lines.append(f' --{field}-bottom-top: {v["bottom_top"]}mm;') + if 'bottom_left' in v: + lines.append(f' --{field}-bottom-left: {v["bottom_left"]}mm;') + if 'right_left' in v: + lines.append(f' --{field}-right-left: {v["right_left"]}mm;') + lines.append('}') + return '\n'.join(lines) + + +# ponytail: assert-based check; upgrade to pytest if suite grows +if __name__ == '__main__': + css = css_vars(DEFAULTS) + assert '--batch-top: 63.0mm;' in css + assert '--date-bottom-left: 70.4mm;' in css + assert '--weight-right-left: 29.3mm;' in css + merged = _merge(DEFAULTS, {'batch': {'top': 64, 'bogus': 1}}) + assert merged['batch']['top'] == 64.0 + assert 'bogus' not in merged['batch'] + assert merged['date']['left'] == DEFAULTS['date']['left'] + print('ok') diff --git a/slips/schemas.py b/slips/schemas.py index ce88eff..8c18e9c 100644 --- a/slips/schemas.py +++ b/slips/schemas.py @@ -66,3 +66,23 @@ class OrderOut(Schema): class OrderStatusIn(Schema): status: str + + +class FieldCalibration(Schema): + top: float + left: float + font: float + bottom_top: float + bottom_left: Optional[float] = None + right_left: Optional[float] = None + + +class CalibrationIn(Schema): + batch: FieldCalibration + date: FieldCalibration + next: FieldCalibration + weight: FieldCalibration + + +class CalibrationOut(CalibrationIn): + pass diff --git a/slips/static/slips/css/label_print.css b/slips/static/slips/css/label_print.css index ceac27d..2c5b498 100644 --- a/slips/static/slips/css/label_print.css +++ b/slips/static/slips/css/label_print.css @@ -1,7 +1,5 @@ -/* Shared label field calibration — derived from - * ETICHETTE PER INKS(...).xlsx.pdf (fit-to-page A4 print). - * Positions are mm from the top-left of each slip quadrant. - * Font sizes are effective printed sizes (Excel 15/13pt × ~0.46 scale). +/* Shared label field layout — positions from CSS vars + * (defaults here; calibrate UI / data/calibration.json override via :root). */ .var-field { position: absolute; @@ -11,27 +9,27 @@ } .val-batch { - font-size: 7pt; - top: 63mm; /* +2mm vs prior top-row calibration */ - left: 30.2mm; + font-size: var(--batch-font, 7pt); + top: var(--batch-top, 63mm); + left: var(--batch-left, 30.2mm); } .val-date { - font-size: 6pt; - top: 63mm; /* +2mm vs prior top-row calibration */ - left: 67.4mm; + font-size: var(--date-font, 6pt); + top: var(--date-top, 63mm); + left: var(--date-left, 67.4mm); } .val-next { - font-size: 7pt; - top: 68.5mm; /* +2mm vs prior top-row calibration */ - left: 84.2mm; + font-size: var(--next-font, 7pt); + top: var(--next-top, 68.5mm); + left: var(--next-left, 84.2mm); } .val-weight { - font-size: 7pt; - top: 68.5mm; /* +2mm vs prior top-row calibration */ - left: 37.3mm; + font-size: var(--weight-font, 7pt); + top: var(--weight-top, 68.5mm); + left: var(--weight-left, 37.3mm); } /* @@ -39,29 +37,29 @@ * matching fields is ~118.8mm (not 148.5mm). Shift bottom slips up. * Quadrant order in the 2×2 grid: 1=TL, 2=TR, 3=BL, 4=BR. */ -.slip-quadrant:nth-child(n + 3) .val-batch, -.slip-quadrant:nth-child(n + 3) .val-date { - top: 43.3mm; /* +12mm vs prior bottom-row calibration */ -} - -.slip-quadrant:nth-child(n + 3) .val-next, -.slip-quadrant:nth-child(n + 3) .val-weight { - top: 48.8mm; /* +12mm vs prior bottom-row calibration */ +.slip-quadrant:nth-child(n + 3) .val-batch { + top: var(--batch-bottom-top, 43.3mm); } .slip-quadrant:nth-child(n + 3) .val-date { - left: 70.4mm; /* +3mm vs top-row date */ + top: var(--date-bottom-top, 43.3mm); + left: var(--date-bottom-left, 70.4mm); } .slip-quadrant:nth-child(n + 3) .val-next { - left: 87.2mm; /* +3mm vs top-row next control */ + top: var(--next-bottom-top, 48.8mm); + left: var(--next-bottom-left, 87.2mm); +} + +.slip-quadrant:nth-child(n + 3) .val-weight { + top: var(--weight-bottom-top, 48.8mm); } /* Right column (TR, BR): Batch# and Net weight */ .slip-quadrant:nth-child(2n) .val-batch { - left: 22.2mm; /* -8mm vs left-column batch */ + left: var(--batch-right-left, 22.2mm); } .slip-quadrant:nth-child(2n) .val-weight { - left: 29.3mm; /* -8mm vs left-column weight */ + left: var(--weight-right-left, 29.3mm); } diff --git a/slips/static/slips/js/calibrate.js b/slips/static/slips/js/calibrate.js new file mode 100644 index 0000000..00e992e --- /dev/null +++ b/slips/static/slips/js/calibrate.js @@ -0,0 +1,292 @@ +(() => { + const FIELDS = ['batch', 'date', 'next', 'weight']; + const LABELS = { batch: 'Batch', date: 'Date', next: 'Next control', weight: 'Weight' }; + + const TOP_KEYS = [ + { key: 'top', label: 'top' }, + { key: 'left', label: 'left' }, + { key: 'font', label: 'font pt' }, + ]; + const BOTTOM_KEYS = { + batch: [{ key: 'bottom_top', label: 'top' }], + date: [ + { key: 'bottom_top', label: 'top' }, + { key: 'bottom_left', label: 'left' }, + ], + next: [ + { key: 'bottom_top', label: 'top' }, + { key: 'bottom_left', label: 'left' }, + ], + weight: [{ key: 'bottom_top', label: 'top' }], + }; + const RIGHT_KEYS = { + batch: [{ key: 'right_left', label: 'left' }], + weight: [{ key: 'right_left', label: 'left' }], + }; + + const dataEl = document.getElementById('calibration-data'); + let state = JSON.parse(dataEl.textContent); + let saved = structuredClone(state); + let selected = { field: 'batch', section: 'top' }; + + const statusEl = document.getElementById('status'); + const stepEl = document.getElementById('step'); + const varsEl = document.getElementById('calibration-vars'); + + function round1(n) { + return Math.round(Number(n) * 10) / 10; + } + + function isDirty() { + return JSON.stringify(state) !== JSON.stringify(saved); + } + + function setStatus(msg, kind) { + statusEl.textContent = msg; + statusEl.className = 'status' + (kind ? ' ' + kind : ''); + } + + function cssFromState(cal) { + const lines = [':root {']; + for (const field of FIELDS) { + const v = cal[field]; + lines.push(` --${field}-top: ${v.top}mm;`); + lines.push(` --${field}-left: ${v.left}mm;`); + lines.push(` --${field}-font: ${v.font}pt;`); + lines.push(` --${field}-bottom-top: ${v.bottom_top}mm;`); + if (v.bottom_left != null) lines.push(` --${field}-bottom-left: ${v.bottom_left}mm;`); + if (v.right_left != null) lines.push(` --${field}-right-left: ${v.right_left}mm;`); + } + lines.push('}'); + return lines.join('\n'); + } + + function applyLive() { + varsEl.textContent = cssFromState(state); + if (isDirty()) setStatus('Unsaved changes', 'dirty'); + else setStatus('Saved', 'ok'); + syncInputs(); + highlightSelected(); + } + + function step() { + const s = parseFloat(stepEl.value); + return Number.isFinite(s) && s > 0 ? s : 0.5; + } + + function setValue(field, key, value) { + if (!(key in state[field])) return; + let v = round1(value); + if (key === 'font') v = Math.max(4, Math.min(20, v)); + else v = Math.max(0, Math.min(150, v)); + state[field][key] = v; + applyLive(); + } + + function nudge(field, key, dir) { + setValue(field, key, state[field][key] + dir * step()); + } + + function makeNudgeRow(field, key, label) { + const row = document.createElement('div'); + row.className = 'nudge'; + row.dataset.field = field; + row.dataset.key = key; + + const lab = document.createElement('label'); + lab.textContent = label; + + const input = document.createElement('input'); + input.type = 'number'; + input.step = '0.1'; + input.value = state[field][key]; + input.addEventListener('change', () => setValue(field, key, input.value)); + + const minus = document.createElement('button'); + minus.type = 'button'; + minus.textContent = '−'; + minus.addEventListener('click', () => nudge(field, key, -1)); + + const plus = document.createElement('button'); + plus.type = 'button'; + plus.textContent = '+'; + plus.addEventListener('click', () => nudge(field, key, 1)); + + row.append(lab, input, minus, plus); + return row; + } + + function makeFieldBlock(field, keys, section) { + const block = document.createElement('div'); + block.className = 'field-block'; + block.dataset.field = field; + block.dataset.section = section; + + const h = document.createElement('h3'); + h.textContent = LABELS[field]; + block.appendChild(h); + + for (const { key, label } of keys) { + if (state[field][key] == null) continue; + block.appendChild(makeNudgeRow(field, key, label)); + } + + block.addEventListener('click', () => { + selected = { field, section }; + highlightSelected(); + }); + return block; + } + + function buildPanel() { + const top = document.getElementById('sec-top'); + const bottom = document.getElementById('sec-bottom'); + const right = document.getElementById('sec-right'); + + for (const field of FIELDS) { + top.appendChild(makeFieldBlock(field, TOP_KEYS, 'top')); + if (BOTTOM_KEYS[field]) { + bottom.appendChild(makeFieldBlock(field, BOTTOM_KEYS[field], 'bottom')); + } + if (RIGHT_KEYS[field]) { + right.appendChild(makeFieldBlock(field, RIGHT_KEYS[field], 'right')); + } + } + } + + function syncInputs() { + document.querySelectorAll('.nudge').forEach((row) => { + const field = row.dataset.field; + const key = row.dataset.key; + const input = row.querySelector('input'); + if (input && document.activeElement !== input) { + input.value = state[field][key]; + } + }); + } + + function highlightSelected() { + document.querySelectorAll('.field-block').forEach((el) => { + el.classList.toggle( + 'active', + el.dataset.field === selected.field && el.dataset.section === selected.section + ); + }); + + document.querySelectorAll('.var-field').forEach((el) => { + const q = el.dataset.scope; + const field = el.dataset.field; + let match = field === selected.field; + if (selected.section === 'top') { + match = match && (q === 'TL' || q === 'TR'); + } else if (selected.section === 'bottom') { + match = match && (q === 'BL' || q === 'BR'); + } else if (selected.section === 'right') { + match = match && (q === 'TR' || q === 'BR'); + } + el.classList.toggle('selected', match); + }); + } + + function payloadFromState() { + // API schema expects all keys; optional ones may be null + const out = {}; + for (const field of FIELDS) { + out[field] = { + top: state[field].top, + left: state[field].left, + font: state[field].font, + bottom_top: state[field].bottom_top, + bottom_left: state[field].bottom_left ?? null, + right_left: state[field].right_left ?? null, + }; + } + return out; + } + + async function save() { + const btn = document.getElementById('btn-save'); + btn.disabled = true; + try { + const res = await fetch('/api/calibration', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payloadFromState()), + }); + if (!res.ok) throw new Error('HTTP ' + res.status); + state = await res.json(); + saved = structuredClone(state); + applyLive(); + setStatus('Saved to server', 'ok'); + } catch (e) { + setStatus('Save failed: ' + e.message, 'err'); + } finally { + btn.disabled = false; + } + } + + async function reset() { + if (!confirm('Reset all positions to built-in defaults?')) return; + try { + const res = await fetch('/api/calibration/reset', { method: 'POST' }); + if (!res.ok) throw new Error('HTTP ' + res.status); + state = await res.json(); + saved = structuredClone(state); + applyLive(); + setStatus('Defaults restored', 'ok'); + } catch (e) { + setStatus('Reset failed: ' + e.message, 'err'); + } + } + + document.querySelectorAll('.var-field').forEach((el) => { + el.addEventListener('click', () => { + const q = el.dataset.scope; + const field = el.dataset.field; + let section = 'top'; + if ((q === 'TR' || q === 'BR') && (field === 'batch' || field === 'weight')) { + section = 'right'; + } else if (q === 'BL' || q === 'BR') { + section = 'bottom'; + } + selected = { field, section }; + const block = document.querySelector( + `.field-block[data-field="${field}"][data-section="${section}"]` + ); + if (block) block.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); + highlightSelected(); + }); + }); + + document.addEventListener('keydown', (e) => { + if (e.target.matches('input, textarea')) return; + const map = { + ArrowLeft: ['leftish', -1], + ArrowRight: ['leftish', 1], + ArrowUp: ['topish', -1], + ArrowDown: ['topish', 1], + }; + const hit = map[e.key]; + if (!hit) return; + e.preventDefault(); + const [axis, dir] = hit; + const { field, section } = selected; + let key; + if (section === 'top') { + key = axis === 'topish' ? 'top' : 'left'; + } else if (section === 'bottom') { + key = axis === 'topish' ? 'bottom_top' : 'bottom_left'; + } else { + key = axis === 'topish' ? null : 'right_left'; + } + if (!key || state[field][key] == null) return; + nudge(field, key, dir); + }); + + document.getElementById('btn-save').addEventListener('click', save); + document.getElementById('btn-reset').addEventListener('click', reset); + document.getElementById('btn-print').addEventListener('click', () => window.print()); + + buildPanel(); + applyLive(); +})(); diff --git a/slips/templates/slips/calibrate.html b/slips/templates/slips/calibrate.html index f82a414..b5b107b 100644 --- a/slips/templates/slips/calibrate.html +++ b/slips/templates/slips/calibrate.html @@ -4,76 +4,280 @@ - Calibration Page + Calibration — Lithium | Print Label + -
-

Calibration Sheet. Print this on blank paper and overlay on a pre-printed label against light.

- - -
+
+ + +
+
+
+ {% for label in quadrants %} +
+ {{ label }} +
[Batch#]
+
[Date]
+
[Next]
+
[Weight]
+
+ {% endfor %}
- {% endfor %}
+ + {{ calibration_json|json_script:"calibration-data" }} + diff --git a/slips/templates/slips/print_page.html b/slips/templates/slips/print_page.html index 132e3f9..d607637 100644 --- a/slips/templates/slips/print_page.html +++ b/slips/templates/slips/print_page.html @@ -6,6 +6,9 @@ Print Order #{{ order.id }} +