Files
product-slip/slips/static/slips/js/entry.js

204 lines
7.8 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.
document.addEventListener('DOMContentLoaded', () => {
const productSelect = document.getElementById('product');
const dateFields = document.getElementById('date-fields');
const dateInput = document.getElementById('prod-date');
const nextControlInput = document.getElementById('next-control');
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');
// European display dd/mm/yyyy; API still gets ISO yyyy-mm-dd
function localDmy(d) {
const day = String(d.getDate()).padStart(2, '0');
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${day}/${m}/${d.getFullYear()}`;
}
function parseDmy(s) {
const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec((s || '').trim());
if (!m) return null;
const d = new Date(+m[3], +m[2] - 1, +m[1]);
if (d.getFullYear() !== +m[3] || d.getMonth() !== +m[2] - 1 || d.getDate() !== +m[1]) return null;
return d;
}
function toYmd(d) {
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${d.getFullYear()}-${m}-${day}`;
}
function productRequiresDates() {
const opt = productSelect.options[productSelect.selectedIndex];
if (!opt || !opt.value) return true;
return opt.dataset.requiresDates !== 'false';
}
function syncDateFields() {
const needed = productRequiresDates();
dateFields.style.display = needed ? '' : 'none';
dateInput.required = needed;
nextControlInput.required = needed;
if (needed && !dateInput.value) {
dateInput.value = localDmy(new Date());
updateNextControl();
}
}
dateInput.value = localDmy(new Date());
// Auto calculate +6 months
function updateNextControl() {
const d = parseDmy(dateInput.value);
if (!d) return;
d.setMonth(d.getMonth() + 6);
nextControlInput.value = localDmy(d);
}
updateNextControl();
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;
const cw = parseFloat(canisterWeightInput.value) || 1;
const cpb = parseInt(canistersPerBoxInput.value) || 1;
const cc = Math.ceil(tw / cw);
const bc = Math.ceil(cc / cpb);
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} | ${t.custom_unit}: ${cu} | ${pages} ${t.preview_pages}`;
}
window.updateLabelsPreview = updatePreview;
// Listeners for updates
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
productSelect.addEventListener('change', (e) => {
const opt = e.target.options[e.target.selectedIndex];
if (opt && opt.dataset.weight) {
canisterWeightInput.value = opt.dataset.weight;
updatePreview();
}
syncDateFields();
});
syncDateFields();
// Submit new order
form.addEventListener('submit', async (e) => {
e.preventDefault();
const needsDates = productRequiresDates();
let production_date = null;
let next_control_date = null;
if (needsDates) {
const prodDate = parseDmy(dateInput.value);
const nextDate = parseDmy(nextControlInput.value);
if (!prodDate || !nextDate) {
showToast(currentLang === 'fa' ? 'تاریخ را به صورت روز/ماه/سال وارد کنید' : 'Use date format dd/mm/yyyy', true);
return;
}
production_date = toYmd(prodDate);
next_control_date = toYmd(nextDate);
}
const payload = {
product_id: parseInt(productSelect.value),
batch_number: document.getElementById('batch').value,
production_date,
next_control_date,
total_weight: parseFloat(totalWeightInput.value),
canister_weight: parseFloat(canisterWeightInput.value),
canisters_per_box: parseInt(canistersPerBoxInput.value),
custom_labels: collectCustomLabels()
};
try {
const res = await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
showToast(currentLang === 'fa' ? 'سفارش به صف چاپ اضافه شد' : 'Order added to print queue!');
form.reset();
customLines.replaceChildren();
dateInput.value = localDmy(new Date());
updateNextControl();
syncDateFields();
updatePreview();
setTimeout(() => window.location.reload(), 1000);
} else {
const err = await res.json();
console.error(err);
showToast('Error creating order', true);
}
} catch (err) {
showToast('Network error', true);
}
});
});