From 4d0dad33e626e820b859a273268015949836fb8d Mon Sep 17 00:00:00 2001 From: diaco Date: Wed, 21 Oct 2026 14:01:48 +0330 Subject: [PATCH] Add custom labels printed before box and canister slips Co-authored-by: Cursor --- slips/api.py | 24 +++-- slips/migrations/0004_order_custom_labels.py | 16 ++++ slips/models.py | 38 +++++++- slips/print_layout.py | 30 +++++-- slips/schemas.py | 10 ++- slips/static/slips/css/style.css | 34 +++++++ slips/static/slips/js/entry.js | 63 ++++++++++++- slips/static/slips/js/i18n.js | 93 +++++++++++++++++++- slips/templates/slips/entry.html | 31 ++++++- slips/templates/slips/print_page.html | 1 + 10 files changed, 322 insertions(+), 18 deletions(-) create mode 100644 slips/migrations/0004_order_custom_labels.py diff --git a/slips/api.py b/slips/api.py index d4a98d5..ccb7b22 100644 --- a/slips/api.py +++ b/slips/api.py @@ -4,7 +4,7 @@ from django.shortcuts import get_object_or_404 from django.utils import timezone from ninja import NinjaAPI, Query -from .models import Product, Order +from .models import Product, Order, clean_custom_labels from .schemas import ( ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn, CalibrationIn, CalibrationOut, @@ -93,6 +93,10 @@ def create_order(request, payload: OrderIn): else: production_date = None next_control_date = None + try: + custom_labels = clean_custom_labels(payload.custom_labels) + except ValueError as exc: + return 400, {'detail': str(exc)} order = Order( product=product, batch_number=payload.batch_number, @@ -101,6 +105,7 @@ def create_order(request, payload: OrderIn): total_weight=payload.total_weight, canister_weight=payload.canister_weight, canisters_per_box=payload.canisters_per_box, + custom_labels=custom_labels, ) order.apply_weight() order.save() @@ -111,16 +116,25 @@ def create_order(request, payload: OrderIn): def update_order(request, order_id: int, payload: OrderUpdateIn): order = get_object_or_404(Order, id=order_id) - if payload.canister_count is not None or payload.box_count is not None: + counts_changed = payload.canister_count is not None or payload.box_count is not None + custom_changed = payload.custom_labels is not None + if counts_changed or custom_changed: if order.status != 'pending': return 400, {'detail': 'Only pending orders can change label counts'} cc = payload.canister_count if payload.canister_count is not None else order.canister_count bc = payload.box_count if payload.box_count is not None else order.box_count if cc < 0 or bc < 0: return 400, {'detail': 'counts must be >= 0'} - if cc == 0 and bc == 0: - return 400, {'detail': 'canister_count and box_count cannot both be 0'} - order.set_counts(payload.canister_count, payload.box_count) + try: + custom = clean_custom_labels(payload.custom_labels) if custom_changed else (order.custom_labels or []) + except ValueError as exc: + return 400, {'detail': str(exc)} + if cc == 0 and bc == 0 and not custom: + return 400, {'detail': 'at least one label is required'} + if counts_changed: + order.set_counts(payload.canister_count, payload.box_count) + if custom_changed: + order.custom_labels = custom if payload.status is not None: order.status = payload.status diff --git a/slips/migrations/0004_order_custom_labels.py b/slips/migrations/0004_order_custom_labels.py new file mode 100644 index 0000000..bc3db1d --- /dev/null +++ b/slips/migrations/0004_order_custom_labels.py @@ -0,0 +1,16 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('slips', '0003_product_requires_dates_order_dates_nullable'), + ] + + operations = [ + migrations.AddField( + model_name='order', + name='custom_labels', + field=models.JSONField(blank=True, default=list), + ), + ] diff --git a/slips/models.py b/slips/models.py index 025313b..4edc328 100644 --- a/slips/models.py +++ b/slips/models.py @@ -36,6 +36,8 @@ class Order(models.Model): # Label counts (set from weight on create; editable afterwards) canister_count = models.PositiveIntegerField(default=0) box_count = models.PositiveIntegerField(default=0) + # User-defined slips printed before box and canister labels: [{"weight", "count"}] + custom_labels = models.JSONField(default=list, blank=True) canister_pages = models.PositiveIntegerField(editable=False, default=0) box_pages = models.PositiveIntegerField(editable=False, default=0) @@ -49,6 +51,10 @@ class Order(models.Model): def __str__(self): return f"Order #{self.id} — {self.product.code} — {self.batch_number}" + @property + def custom_count(self): + return sum(int(line['count']) for line in (self.custom_labels or [])) + def apply_weight(self): """Derive canister/box counts from total_weight (create path).""" self.canister_count = math.ceil(self.total_weight / self.canister_weight) @@ -62,8 +68,36 @@ class Order(models.Model): self.box_count = box_count def save(self, *args, **kwargs): - # Mixed sheets: canister + box labels share pages; total in canister_pages - n = self.canister_count + self.box_count + # Mixed sheets: custom + box + canister labels share pages; total in canister_pages + n = self.canister_count + self.box_count + self.custom_count self.canister_pages = math.ceil(n / 4) if n else 0 self.box_pages = 0 super().save(*args, **kwargs) + + +def clean_custom_labels(lines): + """Normalize [{weight, count}] lines. Empty is valid. Raises ValueError.""" + if not lines: + return [] + cleaned = [] + for line in lines: + if isinstance(line, dict): + weight, count = line.get('weight'), line.get('count') + else: + weight, count = line.weight, line.count + try: + weight = float(weight) + except (TypeError, ValueError): + raise ValueError('custom label weight and count must be numbers') + if isinstance(count, float) and not count.is_integer(): + raise ValueError('custom label count must be a whole number') + try: + count = int(count) + except (TypeError, ValueError): + raise ValueError('custom label weight and count must be numbers') + if not math.isfinite(weight) or weight <= 0 or count < 1: + raise ValueError('custom label weight must be > 0 and count >= 1') + if weight.is_integer(): + weight = int(weight) + cleaned.append({'weight': weight, 'count': count}) + return cleaned diff --git a/slips/print_layout.py b/slips/print_layout.py index ad4aef6..29f33ce 100644 --- a/slips/print_layout.py +++ b/slips/print_layout.py @@ -36,11 +36,20 @@ def _box_weight_template(order): return template -def build_print_pages(order): - """Mix box then canister labels on shared sheets (pad only last page). +def _custom_weights(order): + """User-defined slips. Counts repeat the stored weight; they are not derived.""" + weights = [] + for line in getattr(order, 'custom_labels', None) or []: + weights.extend([_display_weight(line['weight'])] * int(line['count'])) + return weights - canister_count / box_count are print quantities only; slip weights come from - total_weight packaging so reprint steppers do not change label content. + +def build_print_pages(order): + """Custom labels, then boxes, then canisters, on shared sheets (pad only last page). + + Counts are print quantities. Box and canister weights come from total_weight + packaging, so those steppers do not change label content. Custom weights are + the ones stored on the order. """ cw = _display_weight(order.canister_weight) canister_weights = [cw] * order.canister_count @@ -51,7 +60,7 @@ def build_print_pages(order): else: box_weights = [template[i % len(template)] for i in range(order.box_count)] - weights = box_weights + canister_weights + weights = _custom_weights(order) + box_weights + canister_weights pages = [] for i in range(0, len(weights), 4): pages.append({ @@ -68,6 +77,7 @@ if __name__ == '__main__': canister_weight = 5.0 canisters_per_box = 4 box_count = 3 + custom_labels = [] pages = build_print_pages(O()) assert len(pages) == 4 # 13 labels → 4 mixed pages @@ -97,4 +107,14 @@ if __name__ == '__main__': one = build_print_pages(Small()) assert len(one) == 1 assert one[0]['slips'] == [15, 5, 5, 5] + + # Custom slips print first; box and canister weights stay on the packaging recipe + class WithCustom(O): + custom_labels = [{'weight': 8.0, 'count': 1}, {'weight': 1.5, 'count': 1}] + + mixed = build_print_pages(WithCustom()) + assert mixed[0]['slips'] == [8, 1.5, 20, 20] + assert isinstance(mixed[0]['slips'][0], int) + assert mixed[1]['slips'] == [10, 5, 5, 5] + assert len(mixed) == 4 # 2 custom + 3 boxes + 10 cans = 15 → 4 pages print('ok') diff --git a/slips/schemas.py b/slips/schemas.py index f74ab57..3e2ee30 100644 --- a/slips/schemas.py +++ b/slips/schemas.py @@ -1,5 +1,5 @@ from datetime import date -from typing import Optional +from typing import List, Optional from ninja import Schema @@ -18,6 +18,11 @@ class ProductIn(Schema): requires_dates: bool = True +class CustomLabel(Schema): + weight: float + count: int + + class OrderIn(Schema): product_id: int batch_number: str @@ -26,6 +31,7 @@ class OrderIn(Schema): total_weight: float canister_weight: float canisters_per_box: int + custom_labels: Optional[List[CustomLabel]] = None class OrderOut(Schema): @@ -41,6 +47,7 @@ class OrderOut(Schema): canisters_per_box: int canister_count: int box_count: int + custom_labels: List[CustomLabel] canister_pages: int box_pages: int status: str @@ -70,6 +77,7 @@ class OrderUpdateIn(Schema): status: Optional[str] = None canister_count: Optional[int] = None box_count: Optional[int] = None + custom_labels: Optional[List[CustomLabel]] = None class FieldCalibration(Schema): diff --git a/slips/static/slips/css/style.css b/slips/static/slips/css/style.css index 3a0aca5..6691d1a 100644 --- a/slips/static/slips/css/style.css +++ b/slips/static/slips/css/style.css @@ -344,6 +344,40 @@ form { gap: 1rem; } +.custom-lines { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.custom-line { + display: flex; + gap: 0.5rem; + align-items: center; +} + +.custom-line input { + flex: 1; +} + +.custom-line .btn { + flex: none; + width: 2.5rem; + padding-left: 0; + padding-right: 0; +} + +#add-custom-line { + align-self: flex-start; +} + +.custom-label-list { + display: flex; + flex-direction: column; + gap: 0.35rem; + align-items: flex-start; +} + .form-group { display: flex; flex-direction: column; diff --git a/slips/static/slips/js/entry.js b/slips/static/slips/js/entry.js index c1131b0..0b54d23 100644 --- a/slips/static/slips/js/entry.js +++ b/slips/static/slips/js/entry.js @@ -6,6 +6,7 @@ document.addEventListener('DOMContentLoaded', () => { const totalWeightInput = document.getElementById('total-weight'); const canisterWeightInput = document.getElementById('canister-weight'); const canistersPerBoxInput = document.getElementById('canisters-per-box'); + const customLines = document.getElementById('custom-lines'); const previewDisplay = document.getElementById('preview-display'); const form = document.getElementById('order-form'); @@ -58,6 +59,45 @@ document.addEventListener('DOMContentLoaded', () => { dateInput.addEventListener('change', updateNextControl); dateInput.addEventListener('input', updateNextControl); + function collectCustomLabels() { + const lines = []; + customLines.querySelectorAll('.custom-line').forEach((row) => { + const weight = parseFloat(row.querySelector('.custom-weight').value); + const count = parseInt(row.querySelector('.custom-count').value, 10); + if (weight > 0 && count >= 1) lines.push({ weight, count }); + }); + return lines; + } + + function addCustomLine() { + const row = document.createElement('div'); + row.className = 'custom-line'; + const weight = document.createElement('input'); + weight.type = 'number'; + weight.className = 'custom-weight'; + weight.required = true; + weight.step = '0.1'; + weight.min = '0.1'; + weight.placeholder = 'kg'; + weight.setAttribute('aria-label', 'Weight (kg)'); + const count = document.createElement('input'); + count.type = 'number'; + count.className = 'custom-count'; + count.required = true; + count.step = '1'; + count.min = '1'; + count.value = '1'; + count.setAttribute('aria-label', 'Count'); + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'btn btn-ghost btn-sm custom-remove'; + remove.textContent = '×'; + remove.setAttribute('aria-label', 'Remove'); + row.append(weight, count, remove); + customLines.appendChild(row); + weight.focus(); + } + // Auto calculate previews function updatePreview() { const tw = parseFloat(totalWeightInput.value) || 0; @@ -66,11 +106,15 @@ document.addEventListener('DOMContentLoaded', () => { const cc = Math.ceil(tw / cw); const bc = Math.ceil(cc / cpb); - const pages = Math.ceil((cc + bc) / 4) || 0; + let cu = 0; + customLines.querySelectorAll('.custom-count').forEach((input) => { + cu += parseInt(input.value, 10) || 0; + }); + const pages = Math.ceil((cc + bc + cu) / 4) || 0; const t = translations[currentLang] || translations.en; previewDisplay.textContent = - `${t.canisters_unit}: ${cc} | ${t.boxes_unit}: ${bc} | ${pages} ${t.preview_pages}`; + `${t.canisters_unit}: ${cc} | ${t.boxes_unit}: ${bc} | ${t.custom_unit}: ${cu} | ${pages} ${t.preview_pages}`; } window.updateLabelsPreview = updatePreview; @@ -78,6 +122,17 @@ document.addEventListener('DOMContentLoaded', () => { totalWeightInput.addEventListener('input', updatePreview); canisterWeightInput.addEventListener('input', updatePreview); canistersPerBoxInput.addEventListener('input', updatePreview); + customLines.addEventListener('input', updatePreview); + customLines.addEventListener('click', (e) => { + const btn = e.target.closest('.custom-remove'); + if (!btn) return; + btn.closest('.custom-line').remove(); + updatePreview(); + }); + document.getElementById('add-custom-line').addEventListener('click', () => { + addCustomLine(); + updatePreview(); + }); updatePreview(); // Auto weight + date visibility from product selection @@ -116,7 +171,8 @@ document.addEventListener('DOMContentLoaded', () => { next_control_date, total_weight: parseFloat(totalWeightInput.value), canister_weight: parseFloat(canisterWeightInput.value), - canisters_per_box: parseInt(canistersPerBoxInput.value) + canisters_per_box: parseInt(canistersPerBoxInput.value), + custom_labels: collectCustomLabels() }; try { @@ -129,6 +185,7 @@ document.addEventListener('DOMContentLoaded', () => { if (res.ok) { showToast(currentLang === 'fa' ? 'سفارش به صف چاپ اضافه شد' : 'Order added to print queue!'); form.reset(); + customLines.replaceChildren(); dateInput.value = localDmy(new Date()); updateNextControl(); syncDateFields(); diff --git a/slips/static/slips/js/i18n.js b/slips/static/slips/js/i18n.js index 07af732..d477a16 100644 --- a/slips/static/slips/js/i18n.js +++ b/slips/static/slips/js/i18n.js @@ -32,6 +32,10 @@ const translations = { 'boxes': 'Boxes', 'canisters_unit': 'Canisters', 'boxes_unit': 'Boxes', + 'custom': 'Custom', + 'custom_unit': 'Custom', + 'custom_labels': 'Custom Labels', + 'add_custom_label': '+ Add custom label', 'pages_unit': 'Page(s)', 'preview_pages': 'pages', 'pages_needed': 'Pages Needed', @@ -83,6 +87,10 @@ const translations = { 'boxes': 'تعداد کارتن', 'canisters_unit': 'گالن', 'boxes_unit': 'کارتن', + 'custom': 'سفارشی', + 'custom_unit': 'سفارشی', + 'custom_labels': 'برچسب سفارشی', + 'add_custom_label': '+ افزودن برچسب سفارشی', 'pages_unit': 'صفحه', 'preview_pages': 'صفحه', 'pages_needed': 'تعداد صفحات', @@ -181,7 +189,10 @@ async function adjustCount(id, field, delta) { if (next < 0) return; const other = document.getElementById(otherId); const otherVal = other ? parseInt(other.textContent, 10) : 0; - if (next === 0 && otherVal === 0) return; + if (next === 0 && otherVal === 0) { + const custom = document.getElementById(`custom-${id}`); + if (!custom || !custom.querySelector('.cl-count')) return; + } try { const res = await fetch(`/api/orders/${id}`, { @@ -207,6 +218,86 @@ async function adjustCount(id, field, delta) { } } +function renderCustomLabels(id, labels, pending) { + const cell = document.getElementById(`custom-${id}`); + if (!cell) return; + const lines = (labels || []).filter((line) => line && Number(line.count) > 0); + if (!lines.length) { + cell.textContent = '—'; + return; + } + const list = document.createElement('div'); + list.className = 'custom-label-list'; + lines.forEach((line, i) => { + const weight = Number(line.weight); + const count = Number(line.count); + const row = document.createElement('div'); + if (!pending) { + row.className = 'mono'; + row.textContent = `${weight} kg × ${count}`; + } else { + row.className = 'count-stepper'; + row.dataset.weight = String(weight); + const label = document.createElement('span'); + label.className = 'stepper-label'; + label.textContent = `${weight} kg`; + const down = document.createElement('button'); + down.type = 'button'; + down.className = 'stepper-btn'; + down.textContent = '−'; + down.setAttribute('aria-label', '-'); + down.addEventListener('click', () => adjustCustomCount(id, i, -1)); + const countEl = document.createElement('span'); + countEl.className = 'cl-count'; + countEl.textContent = String(count); + const up = document.createElement('button'); + up.type = 'button'; + up.className = 'stepper-btn'; + up.textContent = '+'; + up.setAttribute('aria-label', '+'); + up.addEventListener('click', () => adjustCustomCount(id, i, 1)); + row.append(label, down, countEl, up); + } + list.appendChild(row); + }); + cell.replaceChildren(list); +} + +async function adjustCustomCount(id, index, delta) { + const cell = document.getElementById(`custom-${id}`); + if (!cell) return; + const rows = [...cell.querySelectorAll('.count-stepper')]; + const row = rows[index]; + if (!row) return; + const next = parseInt(row.querySelector('.cl-count').textContent, 10) + delta; + if (next < 0) return; + const labels = rows.map((r, i) => ({ + weight: parseFloat(r.dataset.weight), + count: i === index ? next : parseInt(r.querySelector('.cl-count').textContent, 10), + })).filter((line) => line.count > 0); + const cc = parseInt(document.getElementById(`cc-${id}`)?.textContent, 10) || 0; + const bc = parseInt(document.getElementById(`bc-${id}`)?.textContent, 10) || 0; + if (cc === 0 && bc === 0 && labels.length === 0) return; + + try { + const res = await fetch(`/api/orders/${id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ custom_labels: labels }), + }); + if (!res.ok) { + showToast(currentLang === 'fa' ? 'خطا در ویرایش' : 'Error updating order', true); + return; + } + const order = await res.json(); + renderCustomLabels(id, order.custom_labels, true); + const pages = document.getElementById(`pages-${id}`); + if (pages) pages.textContent = order.canister_pages + order.box_pages; + } catch (err) { + showToast('Network error', true); + } +} + async function deleteOrder(id) { const msg = currentLang === 'fa' ? 'این سفارش حذف شود؟' : 'Remove this order?'; if (!confirm(msg)) return; diff --git a/slips/templates/slips/entry.html b/slips/templates/slips/entry.html index a473f9b..aff823c 100644 --- a/slips/templates/slips/entry.html +++ b/slips/templates/slips/entry.html @@ -56,6 +56,12 @@ +
+ +
+ +
+
@@ -85,6 +91,7 @@ Batch Canisters Boxes + Custom Pages Status @@ -118,6 +125,28 @@ {{ o.box_count }} {% endif %} + + {% if o.custom_labels %} +
+ {% if o.status == 'pending' %} + {% for line in o.custom_labels %} +
+ {{ line.weight }} kg + + {{ line.count }} + +
+ {% endfor %} + {% else %} + {% for line in o.custom_labels %} +
{{ line.weight }} kg × {{ line.count }}
+ {% endfor %} + {% endif %} +
+ {% else %} + — + {% endif %} + {{ o.canister_pages|add:o.box_pages }} {{ o.get_status_display }} @@ -127,7 +156,7 @@ {% empty %} - No orders yet + No orders yet {% endfor %} diff --git a/slips/templates/slips/print_page.html b/slips/templates/slips/print_page.html index 0aca536..6ab1340 100644 --- a/slips/templates/slips/print_page.html +++ b/slips/templates/slips/print_page.html @@ -176,6 +176,7 @@

Order #{{ order.id }} — {{ order.product.code }}
+ {% if order.custom_count %}{{ order.custom_count }} Custom |{% endif %} {{ order.canister_count }} Canisters | {{ order.box_count }} Boxes | {{ order.canister_pages|add:order.box_pages }} Pages