diff --git a/config/urls.py b/config/urls.py index 7e74a19..02af6f4 100644 --- a/config/urls.py +++ b/config/urls.py @@ -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//', views.print_page, name='print_page'), path('calibrate/', views.calibrate, name='calibrate'), diff --git a/slips/api.py b/slips/api.py index 47b9af8..9ea496e 100644 --- a/slips/api.py +++ b/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']) diff --git a/slips/static/slips/css/style.css b/slips/static/slips/css/style.css index 954e788..8825879 100644 --- a/slips/static/slips/css/style.css +++ b/slips/static/slips/css/style.css @@ -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; diff --git a/slips/static/slips/js/entry.js b/slips/static/slips/js/entry.js index 2b48ab7..85293c7 100644 --- a/slips/static/slips/js/entry.js +++ b/slips/static/slips/js/entry.js @@ -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); - } -} diff --git a/slips/static/slips/js/i18n.js b/slips/static/slips/js/i18n.js index aa8bcc6..cc7ffc6 100644 --- a/slips/static/slips/js/i18n.js +++ b/slips/static/slips/js/i18n.js @@ -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': 'وزن پیش‌فرض', diff --git a/slips/static/slips/js/products.js b/slips/static/slips/js/products.js new file mode 100644 index 0000000..bc85f4b --- /dev/null +++ b/slips/static/slips/js/products.js @@ -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); + } +} diff --git a/slips/templates/slips/base.html b/slips/templates/slips/base.html index 05df980..199777d 100644 --- a/slips/templates/slips/base.html +++ b/slips/templates/slips/base.html @@ -31,6 +31,7 @@ diff --git a/slips/templates/slips/entry.html b/slips/templates/slips/entry.html index b1b93e7..c7e35c1 100644 --- a/slips/templates/slips/entry.html +++ b/slips/templates/slips/entry.html @@ -23,29 +23,6 @@ {% endfor %} - - - - -
diff --git a/slips/templates/slips/products.html b/slips/templates/slips/products.html new file mode 100644 index 0000000..5a4cb99 --- /dev/null +++ b/slips/templates/slips/products.html @@ -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 %} +
+ +
+
+

+ Add New Product

+ 📦 +
+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+

Products

+
+ + + + {{ products|length }} +
+
+
+ + + + + + + + + + + {% for p in products %} + + + + + + + {% empty %} + + {% endfor %} + +
CodeDescriptionWeight
{{ p.code }}{{ p.description }}{{ p.default_net_weight }} + + +
No products yet
+
+
+
+ +
+{% endblock %} + +{% block extra_scripts %} + +{% endblock %} diff --git a/slips/views.py b/slips/views.py index 831ee81..a4fe98c 100644 --- a/slips/views.py +++ b/slips/views.py @@ -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]