Files
product-slip/slips/static/slips/js/crm_orders.js
2026-11-11 14:53:44 +03:30

279 lines
8.7 KiB
JavaScript

const seenOrderKeys = new Set();
let ordersLoaded = false;
let lastSince = '';
let lastUsername = '';
let lastRows = null;
let productCodes = new Set();
function t(key) {
const pack = translations[currentLang] || translations.en;
return pack[key] || translations.en[key] || key;
}
function orderKey(row) {
return `${row.delivery_note_number}|${row.product_code}`;
}
function dateKey(raw) {
const match = /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/.exec((raw || '').trim());
if (!match) return 0;
return (+match[1]) * 10000 + (+match[2]) * 100 + (+match[3]);
}
function groupedRows(rows) {
const groups = new Map();
rows.forEach((row) => {
const name = (row.customer_name || '').trim() || '—';
if (!groups.has(name)) groups.set(name, []);
groups.get(name).push(row);
});
const list = [...groups.entries()];
list.forEach(([, items]) => {
items.sort((a, b) => dateKey(b.delivery_note_date) - dateKey(a.delivery_note_date));
});
list.sort((a, b) => dateKey(b[1][0].delivery_note_date) - dateKey(a[1][0].delivery_note_date));
return list;
}
function cell(text, className, ltr) {
const td = document.createElement('td');
if (className) td.className = className;
if (ltr) td.dir = 'ltr';
td.textContent = text || '';
return td;
}
function codeCell(row) {
const td = document.createElement('td');
td.className = 'mono';
const code = (row.product_code || '').trim();
if (!productCodes.has(code)) {
td.textContent = code;
return td;
}
const link = document.createElement('a');
const weight = (row.remaining_quantity || '').trim();
link.className = 'code-link';
link.href = `/entry/?code=${encodeURIComponent(code)}&weight=${encodeURIComponent(weight)}`;
link.textContent = code;
td.appendChild(link);
return td;
}
function renderSince() {
const wrap = document.getElementById('crm-since');
const el = document.getElementById('crm-since-date');
if (!wrap || !el) return;
if (!lastSince) {
wrap.hidden = true;
el.textContent = '';
return;
}
wrap.hidden = false;
el.textContent = lastSince;
}
function loginForm() {
return document.getElementById('crm-login');
}
function showLogin() {
loginForm().hidden = false;
document.getElementById('crm-refresh').hidden = true;
document.getElementById('crm-forget').hidden = true;
document.getElementById('crm-account').hidden = true;
document.getElementById('crm-count').hidden = true;
lastRows = null;
lastUsername = '';
ordersLoaded = false;
}
function showSession() {
loginForm().hidden = true;
document.getElementById('crm-password').value = '';
document.getElementById('crm-refresh').hidden = false;
document.getElementById('crm-forget').hidden = false;
document.getElementById('crm-count').hidden = false;
const account = document.getElementById('crm-account');
account.hidden = !lastUsername;
account.textContent = lastUsername ? `${t('sg_signed_in')} ${lastUsername}` : '';
}
function renderChrome() {
if (!loginForm().hidden) setStatus(t('sg_need_login'));
if (lastUsername) showSession();
renderSince();
if (lastRows) renderOrders(lastRows, false);
}
function renderOrders(rows, markNew) {
const body = document.getElementById('crm-orders-body');
const count = document.getElementById('crm-count');
const status = document.getElementById('crm-orders-status');
body.replaceChildren();
count.textContent = String(rows.length);
if (!rows.length) {
status.hidden = false;
status.textContent = t('no_crm_orders');
document.getElementById('crm-orders-table').hidden = true;
return 0;
}
status.hidden = true;
status.textContent = '';
document.getElementById('crm-orders-table').hidden = false;
let added = 0;
groupedRows(rows).forEach(([company, items]) => {
const head = document.createElement('tr');
head.className = 'group-row';
const label = document.createElement('td');
label.colSpan = 6;
label.textContent = company;
head.appendChild(label);
body.appendChild(head);
items.forEach((row) => {
const key = orderKey(row);
const isNew = markNew && !seenOrderKeys.has(key);
if (isNew) added += 1;
const tr = document.createElement('tr');
if (isNew) tr.className = 'row-new';
if (row.notes) tr.title = row.notes;
tr.append(
cell(row.delivery_note_date, 'mono', true),
codeCell(row),
cell(row.product_title),
cell(row.note_quantity, 'mono'),
cell(row.delivered_quantity, 'mono'),
cell(row.remaining_quantity, 'mono'),
);
body.appendChild(tr);
seenOrderKeys.add(key);
});
});
return added;
}
function setStatus(message) {
const status = document.getElementById('crm-orders-status');
const body = document.getElementById('crm-orders-body');
body.replaceChildren();
document.getElementById('crm-count').textContent = '0';
document.getElementById('crm-orders-table').hidden = true;
if (!message) {
status.hidden = true;
status.textContent = '';
return;
}
status.hidden = false;
status.textContent = message;
}
async function fetchProducts() {
const res = await fetch('/api/products');
if (!res.ok) return;
const products = await res.json().catch(() => []);
productCodes = new Set((products || []).map((p) => (p.code || '').trim()));
}
async function applyOrdersResponse(ordersRes) {
const data = await ordersRes.json().catch(() => ({}));
if (ordersRes.status === 401) {
const rejected = data.code === 'login_rejected';
seenOrderKeys.clear();
lastSince = '';
renderSince();
showLogin();
setStatus(t('sg_need_login'));
if (rejected) showToast(t('sg_rejected'), true);
return;
}
if (!ordersRes.ok) {
const message = data.detail || t('no_crm_orders');
if (!ordersLoaded) setStatus(message);
showToast(message, true);
return;
}
lastSince = data.since || '';
lastUsername = data.username || '';
lastRows = data.orders || [];
showSession();
renderSince();
const added = renderOrders(lastRows, ordersLoaded);
ordersLoaded = true;
if (added > 0) showToast(t('crm_new'));
}
async function loadCrmOrders() {
const button = document.getElementById('crm-refresh');
button.disabled = true;
if (!ordersLoaded) setStatus(t('crm_loading'));
try {
const [ordersRes] = await Promise.all([
fetch('/api/crm-orders', { cache: 'no-store' }),
fetchProducts(),
]);
await applyOrdersResponse(ordersRes);
} catch (err) {
setStatus(t('no_crm_orders'));
showToast('Network error', true);
} finally {
button.disabled = false;
}
}
async function signIn(event) {
event.preventDefault();
const button = document.getElementById('crm-sign-in');
button.disabled = true;
setStatus(t('crm_loading'));
try {
const [ordersRes] = await Promise.all([
fetch('/api/crm-orders/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
cache: 'no-store',
body: JSON.stringify({
username: document.getElementById('crm-username').value.trim(),
password: document.getElementById('crm-password').value,
}),
}),
fetchProducts(),
]);
await applyOrdersResponse(ordersRes);
} catch (err) {
setStatus(t('sg_need_login'));
showToast('Network error', true);
} finally {
button.disabled = false;
}
}
async function signOut() {
const button = document.getElementById('crm-forget');
button.disabled = true;
try {
const res = await fetch('/api/crm-orders/session', { method: 'DELETE' });
if (!res.ok) {
showToast('Network error', true);
return;
}
seenOrderKeys.clear();
lastSince = '';
renderSince();
showLogin();
setStatus(t('sg_need_login'));
} catch (err) {
showToast('Network error', true);
} finally {
button.disabled = false;
}
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('crm-refresh').addEventListener('click', loadCrmOrders);
document.getElementById('crm-forget').addEventListener('click', signOut);
loginForm().addEventListener('submit', signIn);
loadCrmOrders();
});
document.addEventListener('slip-language', renderChrome);