/** =========================
* SIDEBAR ACTIVE STATE
* Override: activate the parent listing page for manage_* sub-pages.
* main.js (theme) handles exact-match pages; this covers second-depth pages.
* ========================= */
$(function () {
var $links = $('#sidebar').find('a.nav-link');
var path = window.location.pathname;
// Theme already handled it — an active link whose href matches the current path
var alreadyActive = $links.filter('.active').toArray().some(function (a) {
return a.pathname === path;
});
if (alreadyActive) return;
// For manage_* pages: strip "manage_" to derive the parent listing filename
var filename = path.split('/').pop();
if (!/^manage_/.test(filename)) return;
var dir = path.substring(0, path.lastIndexOf('/'));
var parentPath = dir + '/' + filename.replace(/^manage_/, '');
var $parent = $links.filter(function () { return this.pathname === parentPath; });
if ($parent.length) {
$links.removeClass('active');
$parent.addClass('active');
}
});
/** =========================
* UTILITIES
* ========================= */
/**
* Returns a debounced version of fn that delays invoking until
* after `wait` ms have elapsed since the last call.
*/
function debounce(fn, wait) {
wait = wait || 300;
var timer;
return function (event) {
var ctx = this;
var args = arguments;
// Persist the jQuery event so it's accessible after the timeout
if (event && event.persist) event.persist();
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(ctx, args);
}, wait);
};
}
/** =========================
* DEFAULT ON LOAD FUNCTION
* ========================= */
$(function () {
// Initialize autocomplete for product search inputs
init_product_search_inputs();
window.init_product_search_inputs = init_product_search_inputs;
function init_product_search_inputs(scope) {
var $scope = scope ? $(scope) : $(document);
$scope.find('input.product_search').addBack('input.product_search').each(function (i, el) {
var $el = $(el);
if ($el.data('product-search-ready')) return;
$el.data('product-search-ready', true);
$el.autocomplete({
// Fetch data from server
source: function (request, response) {
// Abort previous request (prevent multiple firing)
if ($el.data('xhr')) {
$el.data('xhr').abort();
}
// Prepare payload
let q = prepare_form_data(0, true);
q['keyword'] = request.term;
let json = JSON.stringify(q);
// Send AJAX request
var xhr = $.ajax({
url: server_url + 'ics/api/engine/product_search.php',
type: 'POST',
dataType: 'json',
data: { json: json },
// for CSRF validation
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (res) {
var aca = [];
// Map result to autocomplete format
$.each(res.result, function (i, item) {
var temp = "";
temp += "
").html(item.label))
.appendTo(ul);
};
$el.on('focus', function () {
$(this).autocomplete('search', $(this).val());
});
$el.on('blur', function () {
var secondary = $(this).attr('secondary');
if (secondary) {
$(this).val(secondary);
}
});
$el.on('input', function () {
$(this).removeAttr('data-existing secondary');
$(this).trigger('lot:cleared');
});
});
}
});
/** =========================
* SHARED PAGE UTILITIES
* ========================= */
function remove_item(idx) {
$(`#item_row_${idx}`).remove();
recalc_totals();
}
function set_select_value(selector, value, label) {
if (!value) return;
var $select = $(selector);
if (!$select.find(`option[value="${value}"]`).length) {
$select.append(``);
}
$select.val(value).prop('disabled', false);
}
function load_location_config(callback) {
return ajax_request({
url: server_url + 'setting/api/engine/company_setting.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function(res) {
var s = res.output;
advanced = s.advanced_location == 1;
label_bin = s.location_label_bin || (advanced ? 'Bin' : 'Location');
label_zone = s.location_label_zone || 'Zone';
label_aisle = s.location_label_aisle || 'Aisle';
if (callback) callback();
}
});
}
/** =========================
* PREPARE FORM DATA
* ========================= */
function load_formula_options(select_id, document_type, selected_id, onLoaded) {
var ctx = document.getElementById('session-context');
ajax_request({
url: server_url + 'accounting/api/engine/account_formula.php',
action: 'get_by_type',
queueLock: false,
noLoading: true,
data: {
otp: ctx ? ctx.dataset.otp : '',
company_id: ctx ? ctx.dataset.companyId : '',
action: 'get_by_type',
document_type: document_type
},
onSuccess: function(res) {
var $sel = $('#' + select_id);
$sel.empty();
$.each(res.output || [], function(i, f) {
var label = escape_html(f.formula_name) + (f.is_default == 1 ? ' (default)' : '');
$sel.append('');
});
if (selected_id) $sel.val(selected_id);
if (onLoaded) onLoaded(res.output || []);
}
});
}
// Line tax rate; derived from tax_amount / total_price when only the amount was stored
function line_tax_rate(item) {
var rate = parseFloat(item.tax_rate) || 0;
var amount = parseFloat(item.tax_amount) || 0;
var total = parseFloat(item.total_price) || 0;
if (rate === 0 && amount > 0 && total > 0) rate = round_dp(amount / total * 100, 2);
return rate;
}
// Returns the request promise so callers can await the options before selecting a value
function load_departments(select_id, selected_id) {
var ctx = document.getElementById('session-context');
return ajax_request({
url: server_url + 'accounting/api/engine/department.php',
action: 'get',
queueLock: false,
noLoading: true,
data: {
otp: ctx ? ctx.dataset.otp : '',
company_id: ctx ? ctx.dataset.companyId : '',
action: 'get'
},
onSuccess: function(res) {
var $sel = $('#' + select_id);
$sel.empty().append('');
$.each(res.output || [], function(i, d) {
$sel.append('');
});
if (selected_id) $sel.val(selected_id);
}
});
}
var _dept_cache = {};
function load_dept_cache() {
return ajax_request({
url: server_url + 'accounting/api/engine/department.php',
action: 'get',
queueLock: false,
noLoading: true,
autoPrepare: true,
checkRequired: 0,
onSuccess: function(res) {
_dept_cache = {};
$.each(res.output || [], function(i, d) {
_dept_cache[String(d.id)] = escape_html(d.dept_code) + ' — ' + escape_html(d.dept_name);
});
}
});
}
function get_dept_label(dept_id) {
if (!dept_id || String(dept_id) === '0') return '—';
return _dept_cache[String(dept_id)] || ('Dept #' + dept_id);
}
function populate_dept_filter(select_id) {
var $sel = $('#' + select_id);
$sel.empty().append('');
$.each(_dept_cache, function(id, label) {
$sel.append('');
});
}
/** =========================
* GENERATE PAGINATION
* ========================= */
function generate_pagination(table_id, total_records, records_per_page, current_page = 1) {
records_per_page = records_per_page ?? prop_limit;
const total_pages = Math.ceil(total_records / records_per_page);
// 1. Find the table and thead
const table = document.getElementById(table_id);
let theme_class = '';
let col_count = 1;
if (table) {
const thead = table.querySelector('thead');
if (thead) {
// 2. Look through classes for one that starts with "table-"
const bootstrap_theme = Array.from(thead.classList).find(c => c.startsWith('table-'));
if (bootstrap_theme) {
// 3. Convert "table-secondary" to "page-item-secondary"
theme_class = bootstrap_theme.replace('table-', 'page-item-');
}
// 4. Count
in the first row of thead
const header_row = thead.querySelector('tr');
if (header_row) {
col_count = header_row.querySelectorAll('th').length || 1;
}
}
}
const left_span = Math.floor(col_count / 2);
const right_span = Math.ceil(col_count / 2);
let pagination_html = `
Showing ${records_per_page} per page Total: ${total_records}
`;
return pagination_html;
}
function handlePageClick(table_id, element, pageNumber) {
// 1. Remove 'active' class from all siblings within this specific pagination bar
const paginationUl = element.closest('.pagination');
paginationUl.querySelectorAll('.page-item').forEach(li => {
li.classList.remove('active');
});
// 2. Add 'active' class to the clicked parent
element.parentElement.classList.add('active');
// 3. Define the dynamic function name
const dynamicFunctionName = `change_page_${table_id}`;
// 4. Check if the specific dynamic function exists and call it
if (typeof window[dynamicFunctionName] === "function") {
window[dynamicFunctionName](pageNumber);
} else {
console.error(`Function ${dynamicFunctionName} not found!`);
}
}
/** =========================
* FLATPICKR INITIALIZE
* ========================= */
flatpickr(".flatpickr", {
enableTime: true,
time_24hr: true,
defaultDate: new Date(),
altInput: true,
altFormat: "d/m/Y H:i:s",
dateFormat: "Y-m-d H:i:s"
});
/**
* Helper function to format date strings (assuming input is in ISO format)
*/
// Display format used across the app: YYYY-MM-DD, or YYYY-MM-DD HH:mm:ss when the value has a time.
function format_date(iso_string) {
if (!iso_string) return '—';
var split = String(iso_string).split(" ");
var datePart = split[0].split("-");
if (datePart.length !== 3) return iso_string;
var formatted = `${datePart[0]}-${datePart[1]}-${datePart[2]}`;
return split.length === 2 ? `${formatted} ${split[1]}` : formatted;
}
// DD/MM/YYYY for filling date inputs (flatpickr dateFormat 'd/m/Y'); to_iso_date() reverses it.
function format_date_input(iso_string) {
if (!iso_string) return '';
var datePart = String(iso_string).split(" ")[0].split("-");
if (datePart.length !== 3) return iso_string;
return `${datePart[2]}/${datePart[1]}/${datePart[0]}`;
}
function to_iso_date(dateStr) {
if (!dateStr) return null;
const parts = dateStr.split('/');
if (parts.length !== 3) return null;
let [day, month, year] = parts;
day = day.padStart(2, '0');
month = month.padStart(2, '0');
return `${year}-${month}-${day}`;
}
/**
* Clear every field inside a form or form-like container — the "Clear" buttons
* on the master-data pages. It was called by five pages but never defined, so
* each click threw a ReferenceError, and where the container is a