Files
product-slip/slips/static/slips/js/i18n.js
2026-11-18 09:59:17 +03:30

393 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const translations = {
'en': {
'app_title': 'Label Printer',
'data_entry': 'Data Entry',
'crm_orders': 'Orders',
'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',
'requires_dates': 'Requires Date / Next Control',
'requires_dates_short': 'Dates',
'save': 'Save',
'cancel': 'Cancel',
'batch_number': 'Batch #',
'date': 'Date',
'next_control': 'Next Control Date',
'net_weight': 'Net Weight (kg)',
'total_weight': 'Total Weight (kg)',
'canister_weight': 'Canister Weight (kg)',
'canisters_per_box': 'Canisters per Box',
'labels_preview': 'Labels Generated',
'canisters': 'Canisters',
'boxes': 'Boxes',
'canisters_unit': 'Canisters',
'boxes_unit': 'Boxes',
'labels': 'Labels',
'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',
'total_pages': 'Pages',
'status_pending': 'Pending',
'status_done': 'Done',
'status_printing': 'Printing',
'status_cancelled': 'Cancelled',
'add_to_queue': 'Add to Print Queue',
'recent_orders': 'Recent Orders',
'crm_orders_title': 'Orders',
'refresh': 'Refresh',
'customer': 'Customer',
'company_name': 'Company name',
'delivery_note': 'Note #',
'note_qty': 'Ordered',
'delivered_qty': 'Delivered',
'remaining_qty': 'Remaining',
'product_title': 'Title',
'subtotal': 'Subtotal',
'crm_loading': 'Loading orders…',
'sg_username': 'Username',
'sg_password': 'Password',
'sg_sign_in': 'Sign in',
'sg_sign_out': 'Sign out',
'sg_signed_in': 'Signed in as',
'sg_need_login': 'Sign in to load orders.',
'sg_rejected': 'SystemGroup rejected this username or password.',
'no_crm_orders': 'No orders after this date',
'no_crm_matches': 'No orders match this search',
'orders_after': 'Orders after',
'crm_new': 'New orders added',
'status': 'Status',
'no_orders': 'No orders yet',
'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'
},
'fa': {
'app_title': 'پرینتر لیبل',
'data_entry': 'ثبت اطلاعات',
'crm_orders': 'حواله‌ها',
'products': 'محصولات',
'print_queue': 'صف چاپ',
'calibrate': 'کالیبراسیون',
'new_order': 'سفارش جدید',
'product': 'محصول',
'add_product': '+ افزودن محصول جدید',
'edit_product': 'ویرایش محصول',
'edit': 'ویرایش',
'backup': 'پشتیبان',
'restore': 'بازیابی',
'no_products': 'محصولی ثبت نشده',
'product_code': 'کد محصول',
'description': 'شرح',
'default_weight': 'وزن پیش‌فرض',
'requires_dates': 'نیاز به تاریخ / کنترل بعدی',
'requires_dates_short': 'تاریخ',
'save': 'ذخیره',
'cancel': 'لغو',
'batch_number': 'شماره بچ',
'date': 'تاریخ',
'next_control': 'تاریخ کنترل بعدی',
'net_weight': 'وزن خالص (کیلوگرم)',
'total_weight': 'وزن کل (کیلوگرم)',
'canister_weight': 'وزن گالن (کیلوگرم)',
'canisters_per_box': 'تعداد گالن در هر کارتن',
'labels_preview': 'برچسب‌های تولیدی',
'canisters': 'تعداد گالن',
'boxes': 'تعداد کارتن',
'canisters_unit': 'گالن',
'boxes_unit': 'کارتن',
'labels': 'برچسب‌ها',
'custom': 'سفارشی',
'custom_unit': 'سفارشی',
'custom_labels': 'برچسب سفارشی',
'add_custom_label': '+ افزودن برچسب سفارشی',
'pages_unit': 'صفحه',
'preview_pages': 'صفحه',
'pages_needed': 'تعداد صفحات',
'total_pages': 'صفحات',
'status_pending': 'در انتظار',
'status_done': 'انجام شد',
'status_printing': 'در حال چاپ',
'status_cancelled': 'لغو شده',
'add_to_queue': 'افزودن به صف چاپ',
'recent_orders': 'سفارشات اخیر',
'crm_orders_title': 'حواله‌ها',
'refresh': 'به‌روزرسانی',
'customer': 'مشتری',
'company_name': 'نام شرکت',
'delivery_note': 'شماره حواله',
'note_qty': 'مقدار حواله',
'delivered_qty': 'تحویل‌شده',
'remaining_qty': 'مانده',
'product_title': 'عنوان',
'subtotal': 'جمع',
'crm_loading': 'در حال دریافت سفارش‌ها…',
'sg_username': 'نام کاربری',
'sg_password': 'رمز عبور',
'sg_sign_in': 'ورود',
'sg_sign_out': 'خروج',
'sg_signed_in': 'کاربر',
'sg_need_login': 'برای دیدن حواله‌ها وارد شوید.',
'sg_rejected': 'نام کاربری یا رمز سامانه گروه نادرست است.',
'no_crm_orders': 'سفارشی بعد از این تاریخ نیست',
'no_crm_matches': 'حواله‌ای با این جستجو پیدا نشد',
'orders_after': 'حواله‌های بعد از',
'crm_new': 'سفارش جدید اضافه شد',
'status': 'وضعیت',
'no_orders': 'سفارشی ثبت نشده',
'no_pending_orders': 'سفارشی در انتظار چاپ نیست.',
'print': 'چاپ',
'mark_done': 'چاپ شد',
'undo_done': 'بازگردانی',
'remove': 'حذف',
'print_history': 'سابقه چاپ',
'printed_at': 'زمان چاپ',
'no_history': 'سابقه‌ای وجود ندارد'
}
};
let currentLang = localStorage.getItem('slip_lang') || 'fa';
let currentTheme = localStorage.getItem('slip_theme') || 'light';
// SVG flags: Windows often cannot render flag emojis (shows "IR"/"GB" instead)
const FLAG_SVG = {
fa: '<svg class="lang-flag" viewBox="0 0 9 6" aria-hidden="true"><rect width="9" height="2" fill="#239f40"/><rect y="2" width="9" height="2" fill="#fff"/><rect y="4" width="9" height="2" fill="#da0000"/></svg>',
en: '<svg class="lang-flag" viewBox="0 0 60 30" aria-hidden="true"><rect width="60" height="30" fill="#012169"/><path d="M0,0 60,30M60,0 0,30" stroke="#fff" stroke-width="6"/><path d="M0,0 60,30M60,0 0,30" stroke="#C8102E" stroke-width="2"/><path d="M30,0v30M0,15h60" stroke="#fff" stroke-width="10"/><path d="M30,0v30M0,15h60" stroke="#C8102E" stroke-width="6"/></svg>',
};
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
const label = document.getElementById('theme-label');
if (label) {
// show the theme you'll switch to
label.textContent = theme === 'light' ? '🌙' : '☀️';
}
}
function toggleTheme() {
currentTheme = currentTheme === 'light' ? 'dark' : 'light';
localStorage.setItem('slip_theme', currentTheme);
applyTheme(currentTheme);
}
function applyLanguage(lang) {
document.documentElement.lang = lang;
document.documentElement.dir = lang === 'fa' ? 'rtl' : 'ltr';
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (translations[lang][key]) {
el.textContent = translations[lang][key];
}
});
document.querySelectorAll('[data-i18n-title]').forEach(el => {
const key = el.getAttribute('data-i18n-title');
if (translations[lang][key]) el.title = translations[lang][key];
});
document.querySelectorAll('[data-i18n-aria]').forEach(el => {
const key = el.getAttribute('data-i18n-aria');
if (translations[lang][key]) el.setAttribute('aria-label', translations[lang][key]);
});
// Button shows the language you can switch to
const toggleBtn = document.getElementById('lang-label');
if (toggleBtn) {
const next = lang === 'en' ? 'fa' : 'en';
toggleBtn.innerHTML = FLAG_SVG[next] + ' ' + next.toUpperCase();
}
if (typeof window.updateLabelsPreview === 'function') {
window.updateLabelsPreview();
}
document.dispatchEvent(new Event('slip-language'));
}
function toggleLanguage() {
currentLang = currentLang === 'en' ? 'fa' : 'en';
localStorage.setItem('slip_lang', currentLang);
applyLanguage(currentLang);
}
// Common Toast notification
function showToast(message, isError = false) {
const toast = document.getElementById('toast');
if (!toast) return;
toast.textContent = message;
if (isError) {
toast.classList.add('error');
} else {
toast.classList.remove('error');
}
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 3000);
}
async function adjustCount(id, field, delta) {
const spanId = field === 'canister_count' ? `cc-${id}` : `bc-${id}`;
const otherId = field === 'canister_count' ? `bc-${id}` : `cc-${id}`;
const span = document.getElementById(spanId);
if (!span) return;
const next = parseInt(span.textContent, 10) + delta;
if (next < 0) return;
const other = document.getElementById(otherId);
const otherVal = other ? parseInt(other.textContent, 10) : 0;
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}`, {
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) pages.textContent = order.canister_pages + order.box_pages;
} catch (err) {
showToast('Network error', true);
}
}
function formatWeight(w) {
const n = Number(w);
if (!Number.isFinite(n)) return String(w);
return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(6)));
}
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.replaceChildren();
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 weightLabel = formatWeight(weight);
const row = document.createElement('div');
if (!pending) {
row.className = 'mono';
row.textContent = `${weightLabel} kg × ${count}`;
} else {
row.className = 'count-stepper';
row.dataset.weight = String(weight);
const label = document.createElement('span');
label.className = 'stepper-label';
label.textContent = `${weightLabel} 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;
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);
applyLanguage(currentLang);
});