Merge pull request 'Add order count edit, remove, and undo-done' (#21) from cursor/edit-remove-undo-print-orders into main

This commit was merged in pull request #21.
This commit is contained in:
2026-10-07 04:48:11 +00:00
10 changed files with 189 additions and 41 deletions

View File

@@ -14,4 +14,4 @@ class OrderAdmin(admin.ModelAdmin):
'box_count', 'status', 'created_at']
list_filter = ['status', 'product']
search_fields = ['batch_number', 'product__code']
readonly_fields = ['canister_count', 'box_count', 'canister_pages', 'box_pages']
readonly_fields = ['canister_pages', 'box_pages']

View File

@@ -5,7 +5,7 @@ from ninja import NinjaAPI, Query
from .models import Product, Order
from .schemas import (
ProductOut, ProductIn, OrderOut, OrderIn, OrderStatusIn,
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
CalibrationIn, CalibrationOut,
)
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
@@ -48,16 +48,31 @@ def create_order(request, payload: OrderIn):
canister_weight=payload.canister_weight,
canisters_per_box=payload.canisters_per_box,
)
order.apply_weight()
order.save()
return 201, order
@api.patch('/orders/{order_id}', response=OrderOut, tags=['Orders'])
def update_order_status(request, order_id: int, payload: OrderStatusIn):
@api.patch('/orders/{order_id}', response={200: OrderOut, 400: dict}, tags=['Orders'])
def update_order(request, order_id: int, payload: OrderUpdateIn):
order = get_object_or_404(Order, id=order_id)
order.status = payload.status
if payload.status == 'done':
order.printed_at = timezone.now()
if payload.canister_count is not None or payload.box_count is not None:
if order.status != 'pending':
return 400, {'detail': 'Only pending orders can change label counts'}
if payload.canister_count is not None and payload.canister_count < 1:
return 400, {'detail': 'canister_count must be >= 1'}
if payload.box_count is not None and payload.box_count < 1:
return 400, {'detail': 'box_count must be >= 1'}
order.set_counts(payload.canister_count, payload.box_count)
if payload.status is not None:
order.status = payload.status
if payload.status == 'done':
order.printed_at = timezone.now()
elif payload.status == 'pending':
order.printed_at = None
order.save()
return order

View File

@@ -32,9 +32,9 @@ class Order(models.Model):
canister_weight = models.FloatField(default=5)
canisters_per_box = models.PositiveIntegerField(default=4)
# Calculated fields
canister_count = models.PositiveIntegerField(editable=False, default=0)
box_count = models.PositiveIntegerField(editable=False, default=0)
# Label counts (set from weight on create; editable afterwards)
canister_count = models.PositiveIntegerField(default=0)
box_count = models.PositiveIntegerField(default=0)
canister_pages = models.PositiveIntegerField(editable=False, default=0)
box_pages = models.PositiveIntegerField(editable=False, default=0)
@@ -48,9 +48,22 @@ class Order(models.Model):
def __str__(self):
return f"Order #{self.id} — {self.product.code} — {self.batch_number}"
def save(self, *args, **kwargs):
def apply_weight(self):
"""Derive canister/box counts from total_weight (create path)."""
self.canister_count = math.ceil(self.total_weight / self.canister_weight)
self.box_count = math.ceil(self.canister_count / self.canisters_per_box)
self.canister_pages = math.ceil(self.canister_count / 4)
self.box_pages = math.ceil(self.box_count / 4)
def set_counts(self, canister_count=None, box_count=None):
"""Edit label counts; keep total_weight aligned with canisters."""
if canister_count is not None:
self.canister_count = canister_count
self.total_weight = canister_count * self.canister_weight
if box_count is not None:
self.box_count = box_count
def save(self, *args, **kwargs):
if not self.canister_count and self.total_weight and self.canister_weight:
self.apply_weight()
self.canister_pages = math.ceil(self.canister_count / 4) if self.canister_count else 0
self.box_pages = math.ceil(self.box_count / 4) if self.box_count else 0
super().save(*args, **kwargs)

View File

@@ -64,8 +64,10 @@ class OrderOut(Schema):
return None
class OrderStatusIn(Schema):
status: str
class OrderUpdateIn(Schema):
status: Optional[str] = None
canister_count: Optional[int] = None
box_count: Optional[int] = None
class FieldCalibration(Schema):

View File

@@ -598,6 +598,46 @@ html[dir="rtl"][data-theme="light"] .card-header::after {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--border);
flex-wrap: wrap;
align-items: center;
}
.count-stepper {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.2rem 0.5rem;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-muted);
font-variant-numeric: tabular-nums;
}
.count-stepper .stepper-label {
font-size: 0.75rem;
color: var(--text-secondary);
margin-inline-start: 0.15rem;
}
.stepper-btn {
width: 1.5rem;
height: 1.5rem;
padding: 0;
border: 1px solid var(--border);
border-radius: 4px;
background: var(--bg-secondary);
color: var(--text-primary);
cursor: pointer;
font-size: 1rem;
line-height: 1;
display: inline-flex;
align-items: center;
justify-content: center;
}
.stepper-btn:hover {
background: var(--bg-hover);
border-color: var(--accent);
}
.queue-item-actions {

View File

@@ -165,16 +165,3 @@ async function addProduct() {
showToast('Network error', true);
}
}
async function deleteOrder(id) {
if (!confirm('Cancel this order?')) return;
try {
const res = await fetch(`/api/orders/${id}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
}
} catch (err) {
showToast('Error', true);
}
}

View File

@@ -36,6 +36,8 @@ const translations = {
'no_pending_orders': 'No pending orders to print.',
'print': 'Print',
'mark_done': 'Mark Done',
'undo_done': 'Undo',
'remove': 'Remove',
'print_history': 'Print History',
'printed_at': 'Printed At',
'no_history': 'No print history'
@@ -77,6 +79,8 @@ const translations = {
'no_pending_orders': 'سفارشی در انتظار چاپ نیست.',
'print': 'چاپ',
'mark_done': 'چاپ شد',
'undo_done': 'بازگردانی',
'remove': 'حذف',
'print_history': 'سابقه چاپ',
'printed_at': 'زمان چاپ',
'no_history': 'سابقه‌ای وجود ندارد'
@@ -152,6 +156,56 @@ function showToast(message, isError = false) {
setTimeout(() => toast.classList.remove('show'), 3000);
}
async function adjustCount(id, field, delta) {
const spanId = field === 'canister_count' ? `cc-${id}` : `bc-${id}`;
const span = document.getElementById(spanId);
if (!span) return;
const next = parseInt(span.textContent, 10) + delta;
if (next < 1) return;
try {
const res = await fetch(`/api/orders/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [field]: next })
});
if (!res.ok) {
showToast(currentLang === 'fa' ? 'خطا در ویرایش' : 'Error updating order', true);
return;
}
const order = await res.json();
const cc = document.getElementById(`cc-${id}`);
const bc = document.getElementById(`bc-${id}`);
if (cc) cc.textContent = order.canister_count;
if (bc) bc.textContent = order.box_count;
const tw = document.getElementById(`tw-${id}`);
if (tw) tw.textContent = `${order.total_weight} kg`;
const pages = document.getElementById(`pages-${id}`);
if (pages) {
const unit = (translations[currentLang] || translations.en).pages_unit;
pages.innerHTML = `${order.canister_pages + order.box_pages} <span data-i18n="pages_unit">${unit}</span>`;
}
} catch (err) {
showToast('Network error', true);
}
}
async function deleteOrder(id) {
const msg = currentLang === 'fa' ? 'این سفارش حذف شود؟' : 'Remove this order?';
if (!confirm(msg)) return;
try {
const res = await fetch(`/api/orders/${id}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
} else {
showToast(currentLang === 'fa' ? 'خطا در حذف' : 'Error removing order', true);
}
} catch (err) {
showToast('Network error', true);
}
}
// Initialize on load
document.addEventListener('DOMContentLoaded', () => {
applyTheme(currentTheme);

View File

@@ -17,12 +17,30 @@ async function markDone(id) {
});
if (res.ok) {
showToast('Order marked as done');
showToast(currentLang === 'fa' ? 'سفارش به عنوان چاپ‌شده علامت خورد' : 'Order marked as done');
document.getElementById(`order-${id}`).style.display = 'none';
// Reload after brief delay to update history table
setTimeout(() => window.location.reload(), 1500);
} else {
showToast('Error updating status', true);
showToast(currentLang === 'fa' ? 'خطا در به‌روزرسانی وضعیت' : 'Error updating status', true);
}
} catch (err) {
showToast('Network error', true);
}
}
async function undoDone(id) {
try {
const res = await fetch(`/api/orders/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'pending' })
});
if (res.ok) {
showToast(currentLang === 'fa' ? 'سفارش به صف چاپ بازگشت' : 'Order returned to print queue');
setTimeout(() => window.location.reload(), 1000);
} else {
showToast(currentLang === 'fa' ? 'خطا در بازگردانی' : 'Error undoing status', true);
}
} catch (err) {
showToast('Network error', true);

View File

@@ -114,16 +114,36 @@
</thead>
<tbody id="orders-body">
{% for o in orders %}
<tr>
<tr id="order-row-{{ o.id }}">
<td class="mono">{{ o.id }}</td>
<td>{{ o.product.code }}</td>
<td class="mono">{{ o.batch_number }}</td>
<td>{{ o.canister_count }}</td>
<td>{{ o.box_count }}</td>
<td>
{% if o.status == 'pending' %}
<div class="count-stepper">
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'canister_count', -1)" aria-label="-">−</button>
<span id="cc-{{ o.id }}">{{ o.canister_count }}</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'canister_count', 1)" aria-label="+">+</button>
</div>
{% else %}
{{ o.canister_count }}
{% endif %}
</td>
<td>
{% if o.status == 'pending' %}
<div class="count-stepper">
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'box_count', -1)" aria-label="-">−</button>
<span id="bc-{{ o.id }}">{{ o.box_count }}</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'box_count', 1)" aria-label="+">+</button>
</div>
{% else %}
{{ o.box_count }}
{% endif %}
</td>
<td><span class="badge badge-{{ o.status }}">{{ o.get_status_display }}</span></td>
<td>
{% if o.status == 'pending' %}
<button class="btn btn-ghost btn-sm btn-danger" onclick="deleteOrder({{ o.id }})" data-i18n="cancel">Cancel</button>
<button class="btn btn-ghost btn-sm btn-danger" onclick="deleteOrder({{ o.id }})" data-i18n="remove">Remove</button>
{% endif %}
</td>
</tr>

View File

@@ -34,17 +34,12 @@
<span class="label" data-i18n="date">Date:</span>
<span class="value">{{ o.production_date|date:"d/m/Y" }}</span>
</div>
<div class="detail-col">
<span class="label" data-i18n="total_weight">Total:</span>
<span class="value">{{ o.total_weight }} kg</span>
</div>
<div class="detail-col">
<span class="label" data-i18n="next_control">Next:</span>
<span class="value">{{ o.next_control_date|date:"d/m/Y" }}</span>
</div>
</div>
<div class="print-meta">
<span class="badge badge-neutral">{{ o.canister_count }} <span data-i18n="canisters_unit">Canisters</span> | {{ o.box_count }} <span data-i18n="boxes_unit">Boxes</span></span>
<span class="badge badge-accent">{{ o.canister_pages|add:o.box_pages }} <span data-i18n="pages_unit">Page(s)</span></span>
</div>
</div>
@@ -81,6 +76,7 @@
<th data-i18n="batch_number">Batch</th>
<th data-i18n="total_pages">Pages</th>
<th data-i18n="printed_at">Printed At</th>
<th></th>
</tr>
</thead>
<tbody id="history-body">
@@ -91,9 +87,12 @@
<td class="mono">{{ o.batch_number }}</td>
<td>{{ o.canister_pages|add:o.box_pages }}</td>
<td>{{ o.printed_at|date:"d/m/Y H:i" }}</td>
<td>
<button class="btn btn-ghost btn-sm" onclick="undoDone({{ o.id }})" data-i18n="undo_done">Undo</button>
</td>
</tr>
{% empty %}
<tr><td colspan="5" class="empty-state" data-i18n="no_history">No print history</td></tr>
<tr><td colspan="6" class="empty-state" data-i18n="no_history">No print history</td></tr>
{% endfor %}
</tbody>
</table>