Add Products tab with edit, remove, and backup
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -8,6 +8,7 @@ urlpatterns = [
|
||||
path('api/', api.urls),
|
||||
path('', views.index, name='index'),
|
||||
path('entry/', views.entry, name='entry'),
|
||||
path('products/', views.products, name='products'),
|
||||
path('print/', views.print_queue, name='print_queue'),
|
||||
path('print-page/<int:order_id>/', views.print_page, name='print_page'),
|
||||
path('calibrate/', views.calibrate, name='calibrate'),
|
||||
|
||||
49
slips/api.py
49
slips/api.py
@@ -1,4 +1,5 @@
|
||||
from typing import List, Optional
|
||||
from django.db import IntegrityError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.utils import timezone
|
||||
from ninja import NinjaAPI, Query
|
||||
@@ -20,12 +21,56 @@ def list_products(request):
|
||||
return Product.objects.all()
|
||||
|
||||
|
||||
@api.post('/products', response={201: ProductOut}, tags=['Products'])
|
||||
@api.post('/products', response={201: ProductOut, 400: dict}, tags=['Products'])
|
||||
def create_product(request, payload: ProductIn):
|
||||
product = Product.objects.create(**payload.dict())
|
||||
try:
|
||||
product = Product.objects.create(**payload.dict())
|
||||
except IntegrityError:
|
||||
return 400, {'detail': 'Product code already exists'}
|
||||
return 201, product
|
||||
|
||||
|
||||
@api.post('/products/restore', response={200: dict, 400: dict}, tags=['Products'])
|
||||
def restore_products(request, payload: List[ProductIn]):
|
||||
if not payload:
|
||||
return 400, {'detail': 'Empty backup'}
|
||||
created = updated = 0
|
||||
for item in payload:
|
||||
_, was_created = Product.objects.update_or_create(
|
||||
code=item.code,
|
||||
defaults={
|
||||
'description': item.description,
|
||||
'default_net_weight': item.default_net_weight,
|
||||
},
|
||||
)
|
||||
if was_created:
|
||||
created += 1
|
||||
else:
|
||||
updated += 1
|
||||
return {'created': created, 'updated': updated, 'total': created + updated}
|
||||
|
||||
|
||||
@api.put('/products/{product_id}', response={200: ProductOut, 400: dict}, tags=['Products'])
|
||||
def update_product(request, product_id: int, payload: ProductIn):
|
||||
product = get_object_or_404(Product, id=product_id)
|
||||
try:
|
||||
for key, value in payload.dict().items():
|
||||
setattr(product, key, value)
|
||||
product.save()
|
||||
except IntegrityError:
|
||||
return 400, {'detail': 'Product code already exists'}
|
||||
return product
|
||||
|
||||
|
||||
@api.delete('/products/{product_id}', response={204: None, 400: dict}, tags=['Products'])
|
||||
def delete_product(request, product_id: int):
|
||||
product = get_object_or_404(Product, id=product_id)
|
||||
if product.orders.exists():
|
||||
return 400, {'detail': 'Product has orders and cannot be removed'}
|
||||
product.delete()
|
||||
return 204, None
|
||||
|
||||
|
||||
# ─── Orders ──────────────────────────────────────────────
|
||||
|
||||
@api.get('/orders', response=List[OrderOut], tags=['Orders'])
|
||||
|
||||
@@ -255,6 +255,18 @@ html[lang="fa"] body {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.form-actions-inline {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
|
||||
@@ -117,51 +117,3 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Inline Product addition
|
||||
function showAddProduct() {
|
||||
document.getElementById('add-product-panel').style.display = 'block';
|
||||
}
|
||||
|
||||
function hideAddProduct() {
|
||||
document.getElementById('add-product-panel').style.display = 'none';
|
||||
}
|
||||
|
||||
async function addProduct() {
|
||||
const code = document.getElementById('new-code').value;
|
||||
const desc = document.getElementById('new-desc').value;
|
||||
const weight = parseFloat(document.getElementById('new-weight').value);
|
||||
|
||||
if (!code || !desc) {
|
||||
showToast('Code and Description are required', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/products', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, description: desc, default_net_weight: weight })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const p = await res.json();
|
||||
const select = document.getElementById('product');
|
||||
const opt = document.createElement('option');
|
||||
opt.value = p.id;
|
||||
opt.dataset.weight = p.default_net_weight;
|
||||
opt.textContent = `${p.code} — ${p.description}`;
|
||||
select.appendChild(opt);
|
||||
select.value = p.id;
|
||||
document.getElementById('canister-weight').value = p.default_net_weight;
|
||||
updatePreview();
|
||||
|
||||
hideAddProduct();
|
||||
showToast('Product added');
|
||||
} else {
|
||||
showToast('Error adding product', true);
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('Network error', true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,17 @@ const translations = {
|
||||
'en': {
|
||||
'app_title': 'Lithium | Print Label',
|
||||
'data_entry': 'Data Entry',
|
||||
'products': 'Products',
|
||||
'print_queue': 'Print Queue',
|
||||
'calibrate': 'Calibrate',
|
||||
'new_order': 'New Order',
|
||||
'product': 'Product',
|
||||
'add_product': '+ Add New Product',
|
||||
'edit_product': 'Edit Product',
|
||||
'edit': 'Edit',
|
||||
'backup': 'Backup',
|
||||
'restore': 'Restore',
|
||||
'no_products': 'No products yet',
|
||||
'product_code': 'Product Code',
|
||||
'description': 'Description',
|
||||
'default_weight': 'Default Weight',
|
||||
@@ -45,11 +51,17 @@ const translations = {
|
||||
'fa': {
|
||||
'app_title': 'لیتیوم | پرینت لیبل',
|
||||
'data_entry': 'ثبت اطلاعات',
|
||||
'products': 'محصولات',
|
||||
'print_queue': 'صف چاپ',
|
||||
'calibrate': 'کالیبراسیون',
|
||||
'new_order': 'سفارش جدید',
|
||||
'product': 'محصول',
|
||||
'add_product': '+ افزودن محصول جدید',
|
||||
'edit_product': 'ویرایش محصول',
|
||||
'edit': 'ویرایش',
|
||||
'backup': 'پشتیبان',
|
||||
'restore': 'بازیابی',
|
||||
'no_products': 'محصولی ثبت نشده',
|
||||
'product_code': 'کد محصول',
|
||||
'description': 'شرح',
|
||||
'default_weight': 'وزن پیشفرض',
|
||||
|
||||
154
slips/static/slips/js/products.js
Normal file
154
slips/static/slips/js/products.js
Normal file
@@ -0,0 +1,154 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const form = document.getElementById('product-form');
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('edit-id').value;
|
||||
const payload = {
|
||||
code: document.getElementById('prod-code').value.trim(),
|
||||
description: document.getElementById('prod-desc').value.trim(),
|
||||
default_net_weight: parseFloat(document.getElementById('prod-weight').value),
|
||||
};
|
||||
if (!payload.code || !payload.description) {
|
||||
showToast(currentLang === 'fa' ? 'کد و شرح لازم است' : 'Code and Description are required', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const url = id ? `/api/products/${id}` : '/api/products';
|
||||
const method = id ? 'PUT' : 'POST';
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (res.ok) {
|
||||
showToast(id
|
||||
? (currentLang === 'fa' ? 'محصول بهروز شد' : 'Product updated')
|
||||
: (currentLang === 'fa' ? 'محصول افزوده شد' : 'Product added'));
|
||||
setTimeout(() => window.location.reload(), 600);
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
showToast(err.detail || (currentLang === 'fa' ? 'خطا در ذخیره' : 'Error saving product'), true);
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('Network error', true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function setFormMode(editing) {
|
||||
const title = document.getElementById('product-form-title');
|
||||
const cancel = document.getElementById('product-cancel-btn');
|
||||
const t = translations[currentLang] || translations.en;
|
||||
title.textContent = editing ? t.edit_product : t.add_product;
|
||||
title.removeAttribute('data-i18n');
|
||||
title.setAttribute('data-i18n', editing ? 'edit_product' : 'add_product');
|
||||
cancel.style.display = editing ? '' : 'none';
|
||||
}
|
||||
|
||||
function editProduct(btn) {
|
||||
document.getElementById('edit-id').value = btn.dataset.id;
|
||||
document.getElementById('prod-code').value = btn.dataset.code;
|
||||
document.getElementById('prod-desc').value = btn.dataset.desc;
|
||||
document.getElementById('prod-weight').value = btn.dataset.weight;
|
||||
setFormMode(true);
|
||||
document.getElementById('prod-code').focus();
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
document.getElementById('edit-id').value = '';
|
||||
document.getElementById('product-form').reset();
|
||||
document.getElementById('prod-weight').value = 5;
|
||||
setFormMode(false);
|
||||
}
|
||||
|
||||
async function deleteProduct(id) {
|
||||
const msg = currentLang === 'fa' ? 'این محصول حذف شود؟' : 'Remove this product?';
|
||||
if (!confirm(msg)) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/products/${id}`, { method: 'DELETE' });
|
||||
if (res.ok) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
showToast(
|
||||
err.detail || (currentLang === 'fa' ? 'خطا در حذف' : 'Error removing product'),
|
||||
true
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('Network error', true);
|
||||
}
|
||||
}
|
||||
|
||||
async function backupProducts() {
|
||||
try {
|
||||
const res = await fetch('/api/products');
|
||||
if (!res.ok) {
|
||||
showToast(currentLang === 'fa' ? 'خطا در پشتیبانگیری' : 'Backup failed', true);
|
||||
return;
|
||||
}
|
||||
const products = await res.json();
|
||||
const payload = products.map((p) => ({
|
||||
code: p.code,
|
||||
description: p.description,
|
||||
default_net_weight: p.default_net_weight,
|
||||
}));
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2) + '\n'], { type: 'application/json' });
|
||||
const a = document.createElement('a');
|
||||
const d = new Date();
|
||||
const stamp = [
|
||||
d.getFullYear(),
|
||||
String(d.getMonth() + 1).padStart(2, '0'),
|
||||
String(d.getDate()).padStart(2, '0'),
|
||||
].join('');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `products-backup-${stamp}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
showToast(currentLang === 'fa' ? 'فایل پشتیبان دانلود شد' : 'Backup downloaded');
|
||||
} catch (err) {
|
||||
showToast('Network error', true);
|
||||
}
|
||||
}
|
||||
|
||||
function parseProductsBackup(raw) {
|
||||
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
||||
if (!Array.isArray(data) || !data.length) throw new Error('empty or invalid file');
|
||||
return data.map((item) => {
|
||||
if (!item || typeof item !== 'object') throw new Error('invalid item');
|
||||
const code = String(item.code || '').trim();
|
||||
const description = String(item.description || '').trim();
|
||||
const weight = Number(item.default_net_weight);
|
||||
if (!code || !description || !Number.isFinite(weight)) throw new Error('invalid product: ' + code);
|
||||
return { code, description, default_net_weight: weight };
|
||||
});
|
||||
}
|
||||
|
||||
async function restoreProducts(input) {
|
||||
const file = input.files && input.files[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
try {
|
||||
const payload = parseProductsBackup(await file.text());
|
||||
const msg = currentLang === 'fa'
|
||||
? 'محصولات از این فایل بازیابی شوند؟ (بر اساس کد ادغام میشود)'
|
||||
: 'Restore products from this file? (merged by code)';
|
||||
if (!confirm(msg)) return;
|
||||
const res = await fetch('/api/products/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
showToast(err.detail || (currentLang === 'fa' ? 'خطا در بازیابی' : 'Restore failed'), true);
|
||||
return;
|
||||
}
|
||||
showToast(currentLang === 'fa' ? 'بازیابی شد' : 'Restored from file');
|
||||
setTimeout(() => window.location.reload(), 600);
|
||||
} catch (err) {
|
||||
showToast((currentLang === 'fa' ? 'خطا در بازیابی: ' : 'Restore failed: ') + err.message, true);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@
|
||||
</a>
|
||||
<div class="nav-links">
|
||||
<a href="{% url 'entry' %}" class="nav-link {% block nav_entry_active %}{% endblock %}" data-i18n="data_entry">ثبت اطلاعات</a>
|
||||
<a href="{% url 'products' %}" class="nav-link {% block nav_products_active %}{% endblock %}" data-i18n="products">محصولات</a>
|
||||
<a href="{% url 'print_queue' %}" class="nav-link {% block nav_print_active %}{% endblock %}" data-i18n="print_queue">صف چاپ</a>
|
||||
<a href="{% url 'calibrate' %}" class="nav-link" data-i18n="calibrate">کالیبراسیون</a>
|
||||
</div>
|
||||
|
||||
@@ -23,29 +23,6 @@
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button type="button" class="btn btn-sm btn-ghost" onclick="showAddProduct()" data-i18n="add_product">+ Add New Product</button>
|
||||
</div>
|
||||
|
||||
<!-- Add Product Inline (hidden) -->
|
||||
<div id="add-product-panel" class="sub-panel" style="display:none;">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="new-code" data-i18n="product_code">Product Code</label>
|
||||
<input type="text" id="new-code" placeholder="ICJ/000">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="new-desc" data-i18n="description">Description</label>
|
||||
<input type="text" id="new-desc" placeholder="DIGITAL INK ...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="new-weight" data-i18n="default_weight">Default Weight</label>
|
||||
<input type="number" id="new-weight" value="5" step="1" min="1">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-actions-inline">
|
||||
<button type="button" class="btn btn-accent btn-sm" onclick="addProduct()" data-i18n="save">Save</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="hideAddProduct()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
|
||||
90
slips/templates/slips/products.html
Normal file
90
slips/templates/slips/products.html
Normal file
@@ -0,0 +1,90 @@
|
||||
{% extends 'slips/base.html' %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Products — Lithium | Print Label{% endblock %}
|
||||
{% block nav_products_active %}active{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-grid">
|
||||
<!-- Add / Edit Product -->
|
||||
<section class="card glass-card">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title" id="product-form-title" data-i18n="add_product">+ Add New Product</h2>
|
||||
<span class="card-badge badge-accent">📦</span>
|
||||
</div>
|
||||
<form id="product-form" class="form-stack">
|
||||
<input type="hidden" id="edit-id" value="">
|
||||
<div class="form-group">
|
||||
<label for="prod-code" data-i18n="product_code">Product Code</label>
|
||||
<input type="text" id="prod-code" required placeholder="ICJ/000">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="prod-desc" data-i18n="description">Description</label>
|
||||
<input type="text" id="prod-desc" required placeholder="DIGITAL INK ...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="prod-weight" data-i18n="default_weight">Default Weight</label>
|
||||
<input type="number" id="prod-weight" value="5" step="1" min="1" required>
|
||||
</div>
|
||||
<div class="form-actions-inline">
|
||||
<button type="submit" class="btn btn-accent" id="product-save-btn" data-i18n="save">Save</button>
|
||||
<button type="button" class="btn btn-ghost" id="product-cancel-btn" style="display:none;" onclick="cancelEdit()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- Product List -->
|
||||
<section class="card glass-card">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title" data-i18n="products">Products</h2>
|
||||
<div class="card-actions">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="backupProducts()" data-i18n="backup">Backup</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('restore-file').click()" data-i18n="restore">Restore</button>
|
||||
<input type="file" id="restore-file" accept="application/json,.json" hidden onchange="restoreProducts(this)">
|
||||
<span class="card-badge badge-muted" id="product-count">{{ products|length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="products-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="product_code">Code</th>
|
||||
<th data-i18n="description">Description</th>
|
||||
<th data-i18n="default_weight">Weight</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="products-body">
|
||||
{% for p in products %}
|
||||
<tr id="product-row-{{ p.id }}">
|
||||
<td class="mono">{{ p.code }}</td>
|
||||
<td>{{ p.description }}</td>
|
||||
<td class="mono">{{ p.default_net_weight }}</td>
|
||||
<td>
|
||||
<button type="button" class="btn btn-ghost btn-sm"
|
||||
data-id="{{ p.id }}"
|
||||
data-code="{{ p.code }}"
|
||||
data-desc="{{ p.description }}"
|
||||
data-weight="{{ p.default_net_weight }}"
|
||||
onclick="editProduct(this)"
|
||||
data-i18n="edit">Edit</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm btn-danger"
|
||||
onclick="deleteProduct({{ p.id }})"
|
||||
data-i18n="remove">Remove</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr><td colspan="4" class="empty-state" data-i18n="no_products">No products yet</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast"></div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_scripts %}
|
||||
<script src="{% static 'slips/js/products.js' %}"></script>
|
||||
{% endblock %}
|
||||
@@ -18,6 +18,12 @@ def entry(request):
|
||||
})
|
||||
|
||||
|
||||
def products(request):
|
||||
return render(request, 'slips/products.html', {
|
||||
'products': Product.objects.all(),
|
||||
})
|
||||
|
||||
|
||||
def print_queue(request):
|
||||
pending = Order.objects.select_related('product').filter(status='pending')
|
||||
history = Order.objects.select_related('product').filter(status='done').order_by('-printed_at')[:20]
|
||||
|
||||
Reference in New Issue
Block a user