batch journal entries

This commit is contained in:
Thanakorn S
2026-05-23 15:55:22 +07:00
parent 65e9c1668d
commit 363da054e0
2 changed files with 249 additions and 122 deletions
+246 -120
View File
@@ -70,8 +70,6 @@
<?php require '../include_ending.php'; ?>
<script>
// (batch_process lives in custom.js)
var TAB_MAP = {
'invoice': 'invoice',
'credit_note': 'credit_note',
@@ -81,19 +79,23 @@
'payment': 'payment'
};
// Stores the last loaded IDs per tab so Run doesn't need to re-fetch
var _gl_loaded = {};
// Stores full row data per tab for client-side pagination
var _gl_rows = {};
// Stores failed items from the last batch run per tab (for Retry Failed)
var _gl_failed = {};
var _gl_loaded = {}; // doc_type → [ids] (flat, used by single-formula run)
var _gl_rows = {}; // doc_type → [rows]
var _gl_failed = {}; // doc_type → failed items from last run
var _gl_loaded_by_formula = {}; // doc_type → { formula_id: [ids] }
var _formula_run_queue = {}; // doc_type → [formula_ids] remaining in "all" run
// ── init tab once ─────────────────────────────────────────────────────────
var _inited = {};
function init_gl_tab(doc_type) {
if (_inited[doc_type]) return;
_inited[doc_type] = true;
load_formula_options('gl-formula-' + doc_type, doc_type, null);
load_formula_options('gl-formula-' + doc_type, doc_type, null, function(formulas) {
var $sel = $('#gl-formula-' + doc_type);
$sel.prepend('<option value="all">— All Formulas (' + formulas.length + ') —</option>');
$sel.val('all');
});
var today = new Date();
var firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
@@ -113,15 +115,21 @@
$('#gl-date-to-' + doc_type).val(fmt(today));
}
// ── load documents into table ─────────────────────────────────────────────
// ── load documents ────────────────────────────────────────────────────────
function load_gl_tab(doc_type) {
var formula_id = $('#gl-formula-' + doc_type).val();
if (!formula_id) { alert('Please select a GL formula first.'); return; }
if (!formula_id) { bootbox.alert('Please select a GL formula first.'); return; }
if (formula_id === 'all') {
load_all_formulas(doc_type);
return;
}
var $tbody = $('#gl-tbody-' + doc_type);
var $badge = $('#gl-badge-' + doc_type);
_gl_loaded[doc_type] = [];
_gl_loaded_by_formula[doc_type] = {};
set_btn_state('#gl-btn-run-' + doc_type, false);
$badge.text('');
$tbody.html('<tr><td colspan="6" class="text-center text-muted py-4">'
@@ -143,70 +151,130 @@
formula_id: formula_id
},
onSuccess: function(res) {
var rows = res.output || [];
var table_id = 'gl-table-' + doc_type; // HTML element id (hyphens ok)
var ala_id = 'gl_table_' + doc_type; // alasql identifier (underscores only)
if (rows.length === 0) {
$tbody.html('<tr><td colspan="6" class="text-center text-muted py-4">No documents found.</td></tr>');
$('#' + table_id + ' tfoot').empty();
$badge.text('0 documents');
return;
}
_gl_loaded[doc_type] = rows.map(function(r) { return r.id; });
_gl_rows[doc_type] = rows;
// Register with alasql for client-side pagination
alasql('CREATE TABLE IF NOT EXISTS ' + ala_id);
alasql.tables[ala_id].data = rows;
var unposted = rows.filter(function(r) { return r.gl_status == 0; }).length;
var posted = rows.length - unposted;
var missing_mapping = rows.filter(function(r) {
return Number(r.product_mapping_missing || 0) > 0;
}).length;
$badge.html(
rows.length + ' document(s) &nbsp;·&nbsp; '
+ '<span class="text-danger">' + unposted + ' unposted</span>'
+ ' &nbsp;·&nbsp; '
+ '<span class="text-success">' + posted + ' posted</span>'
+ (missing_mapping > 0
? ' &nbsp;·&nbsp; <span class="text-warning">' + missing_mapping + ' missing product account mapping</span>'
: '')
);
// Wire up dynamic change_page function keyed by HTML table id
window['change_page_' + table_id] = function(page_num) {
var offset = (page_num - 1) * prop_limit;
var page_rows = alasql('SELECT * FROM ' + ala_id + ' LIMIT ' + prop_limit + ' OFFSET ' + offset);
var html = '';
$.each(page_rows, function(i, r) {
var status_badge = r.gl_status == 1
? '<span class="badge bg-success-subtle text-success">Posted</span>'
: '<span class="badge bg-danger-subtle text-danger">Unposted</span>';
var mapping_badge = product_mapping_badge(r);
html +=
'<tr>' +
'<td>' + escape_html(r.doc_number) + '</td>' +
'<td>' + escape_html(r.contact_name || '—') + '</td>' +
'<td class="text-end">' + format_number(r.grand_total, 2) + '</td>' +
'<td>' + escape_html(r.doc_date || '—') + '</td>' +
'<td>' + mapping_badge + '</td>' +
'<td>' + status_badge + '</td>' +
'</tr>';
});
$tbody.html(html);
};
$('#' + table_id + ' tfoot').html(generate_pagination(table_id, rows.length));
window['change_page_' + table_id](1);
set_btn_state('#gl-btn-run-' + doc_type, missing_mapping === 0);
_render_gl_tab(doc_type, formula_id, res.output || []);
}
});
}
function load_all_formulas(doc_type) {
var $tbody = $('#gl-tbody-' + doc_type);
var $badge = $('#gl-badge-' + doc_type);
// Collect all formula IDs from the dropdown (skip 'all' and empty)
var formula_ids = [];
$('#gl-formula-' + doc_type + ' option').each(function() {
var v = $(this).val();
if (v && v !== 'all') formula_ids.push(v);
});
if (!formula_ids.length) { bootbox.alert('No formulas available.'); return; }
_gl_loaded[doc_type] = [];
_gl_loaded_by_formula[doc_type] = {};
_gl_rows[doc_type] = [];
set_btn_state('#gl-btn-run-' + doc_type, false);
$badge.html('<i class="ti ti-loader ti-spin me-1"></i>Loading ' + formula_ids.length + ' formulas…');
$tbody.html('<tr><td colspan="6" class="text-center text-muted py-4">'
+ '<i class="ti ti-loader ti-spin me-1"></i>Loading…</td></tr>');
var pending = formula_ids.length;
var all_rows = [];
formula_ids.forEach(function(fid) {
var ctx = document.getElementById('session-context');
ajax_request({
url: '<?php echo $server_url?>accounting/api/engine/get_gl_documents.php',
action: 'get', queueLock: false, noLoading: true,
data: {
otp: ctx ? ctx.dataset.otp : '',
company_id: ctx ? ctx.dataset.companyId : '',
action: 'get',
doc_type: doc_type,
date_from: $('#gl-date-from-' + doc_type).val(),
date_to: $('#gl-date-to-' + doc_type).val(),
formula_id: fid
},
onSuccess: function(res) {
var rows = res.output || [];
rows.forEach(function(r) { r._formula_id = fid; });
_gl_loaded_by_formula[doc_type][fid] = rows.map(function(r) { return r.id; });
all_rows = all_rows.concat(rows);
if (--pending === 0) _finish_all_formulas_load(doc_type, all_rows);
},
onError: function() {
if (--pending === 0) _finish_all_formulas_load(doc_type, all_rows);
}
});
});
}
function _finish_all_formulas_load(doc_type, all_rows) {
_gl_rows[doc_type] = all_rows;
_gl_loaded[doc_type] = all_rows.map(function(r) { return r.id; });
_render_gl_tab(doc_type, 'all', all_rows);
}
function _render_gl_tab(doc_type, formula_id, rows) {
var $tbody = $('#gl-tbody-' + doc_type);
var $badge = $('#gl-badge-' + doc_type);
var table_id = 'gl-table-' + doc_type;
var ala_id = 'gl_table_' + doc_type;
if (rows.length === 0) {
$tbody.html('<tr><td colspan="6" class="text-center text-muted py-4">No documents found.</td></tr>');
$('#' + table_id + ' tfoot').empty();
$badge.text('0 documents');
return;
}
_gl_loaded[doc_type] = rows.map(function(r) { return r.id; });
_gl_rows[doc_type] = rows;
alasql('CREATE TABLE IF NOT EXISTS ' + ala_id);
alasql.tables[ala_id].data = rows;
var unposted = rows.filter(function(r) { return r.gl_status == 0; }).length;
var posted = rows.length - unposted;
var missing_mapping = rows.filter(function(r) { return Number(r.product_mapping_missing || 0) > 0; }).length;
var formula_note = formula_id === 'all'
? ' &nbsp;·&nbsp; <span class="text-info">All Formulas</span>' : '';
$badge.html(
rows.length + ' document(s)' + formula_note + ' &nbsp;·&nbsp; '
+ '<span class="text-danger">' + unposted + ' unposted</span>'
+ ' &nbsp;·&nbsp; '
+ '<span class="text-success">' + posted + ' posted</span>'
+ (missing_mapping > 0
? ' &nbsp;·&nbsp; <span class="text-warning">' + missing_mapping + ' missing product account mapping</span>'
: '')
);
window['change_page_' + table_id] = function(page_num) {
var offset = (page_num - 1) * prop_limit;
var page_rows = alasql('SELECT * FROM ' + ala_id + ' LIMIT ' + prop_limit + ' OFFSET ' + offset);
var html = '';
$.each(page_rows, function(i, r) {
var status_badge = r.gl_status == 1
? '<span class="badge bg-success-subtle text-success">Posted</span>'
: '<span class="badge bg-danger-subtle text-danger">Unposted</span>';
var mapping_badge = product_mapping_badge(r);
html +=
'<tr>' +
'<td>' + escape_html(r.doc_number) + '</td>' +
'<td>' + escape_html(r.contact_name || '—') + '</td>' +
'<td class="text-end">' + format_number(r.grand_total, 2) + '</td>' +
'<td>' + escape_html(r.doc_date || '—') + '</td>' +
'<td>' + mapping_badge + '</td>' +
'<td>' + status_badge + '</td>' +
'</tr>';
});
$tbody.html(html);
};
$('#' + table_id + ' tfoot').html(generate_pagination(table_id, rows.length));
window['change_page_' + table_id](1);
set_btn_state('#gl-btn-run-' + doc_type, missing_mapping === 0);
}
function product_mapping_badge(row) {
if (String(row.product_mapping_checked || '0') !== '1') {
return '<span class="text-muted">—</span>';
@@ -218,8 +286,7 @@
return '<span class="badge bg-success-subtle text-success">Mapped</span>';
}
// ── batch overlay helpers — delegated to shared BatchOverlay ─────────────
// ── batch overlay helpers ─────────────────────────────────────────────────
function show_batch_overlay(label, total) {
BatchOverlay.show('Batch GL Posting — ' + label, total, { unit: 'documents' });
}
@@ -228,7 +295,7 @@
BatchOverlay.update(done, total, 'document ' + done + ' of ' + total);
}
// ── run batch over all loaded IDs ─────────────────────────────────────────
// ── run batch ─────────────────────────────────────────────────────────────
var DOC_LABELS = {
invoice: 'Invoice',
credit_note: 'Credit Note',
@@ -239,6 +306,13 @@
};
function run_gl_batch(doc_type) {
var formula_id = $('#gl-formula-' + doc_type).val();
if (formula_id === 'all') {
run_all_formula_batches(doc_type);
return;
}
var ids = _gl_loaded[doc_type] || [];
if (!ids.length) return;
@@ -246,18 +320,15 @@
return Number(r.product_mapping_missing || 0) > 0;
});
if (missing_mapping.length) {
alert('Product Account Mapping is incomplete for ' + missing_mapping.length + ' loaded document(s). Fill Sales/Purchase accounts on Account Formulas > Product Accounts, then reload this batch.');
bootbox.alert('Product Account Mapping is incomplete for ' + missing_mapping.length + ' loaded document(s). Fill Sales/Purchase accounts on Account Formulas > Product Accounts, then reload this batch.');
return;
}
// Estimate TTL: ids × (throttle delay + avg PHP response) + 20% buffer, min 2 min
var per_item_ms = 200 + 150; // throttle + avg response
var estimated_ms = ids.length * per_item_ms;
var ttl_minutes = Math.max(2, Math.ceil(estimated_ms / 60000 * 1.2));
var per_item_ms = 200 + 150;
var ttl_minutes = Math.max(2, Math.ceil(ids.length * per_item_ms / 60000 * 1.2));
// Acquire DB lock before starting — blocks other tabs/users
acquire_op_lock('gl_post', function() {
_start_gl_batch(doc_type, ids);
_start_gl_batch(doc_type, ids, null);
}, function(msg, res) {
var wait_msg = msg || 'A GL posting batch is already running.';
if (res && res.expires_at) {
@@ -265,19 +336,75 @@
var remaining_m = Math.ceil(remaining_s / 60);
wait_msg += '\nEstimated wait: ~' + (remaining_s < 60 ? remaining_s + ' seconds' : remaining_m + ' minute(s)') + '.';
}
alert(wait_msg);
bootbox.alert(wait_msg);
}, ttl_minutes);
}
function _start_gl_batch(doc_type, ids) {
var formula_id = $('#gl-formula-' + doc_type).val();
// ── All Formulas sequential run ───────────────────────────────────────────
function run_all_formula_batches(doc_type) {
var by_formula = _gl_loaded_by_formula[doc_type] || {};
var queue = Object.keys(by_formula).filter(function(fid) {
return (by_formula[fid] || []).length > 0;
});
if (!queue.length) { bootbox.alert('Load documents first.'); return; }
_formula_run_queue[doc_type] = queue;
set_btn_state('#gl-btn-run-' + doc_type, false);
set_btn_state('#gl-btn-load-' + doc_type, false);
run_next_formula(doc_type);
}
function run_next_formula(doc_type) {
var queue = _formula_run_queue[doc_type] || [];
if (!queue.length) {
BatchOverlay.done('All formulas posted.');
set_btn_state('#gl-btn-load-' + doc_type, true);
load_gl_tab(doc_type);
return;
}
var fid = queue.shift();
var ids = (_gl_loaded_by_formula[doc_type] || {})[fid] || [];
var missing = (_gl_rows[doc_type] || []).filter(function(r) {
return r._formula_id == fid && Number(r.product_mapping_missing || 0) > 0;
});
if (missing.length) {
run_next_formula(doc_type); // skip this formula
return;
}
var ttl = Math.max(2, Math.ceil(ids.length * 350 / 60000 * 1.2));
var formula_label = $('#gl-formula-' + doc_type + ' option[value="' + fid + '"]').text();
acquire_op_lock('gl_post', function() {
_start_gl_batch(doc_type, ids, function() {
run_next_formula(doc_type);
}, fid);
}, function(msg, res) {
var wait_msg = msg || 'A GL posting batch is already running.';
if (res && res.expires_at) {
var s = Math.max(0, Math.round((new Date(res.expires_at) - new Date()) / 1000));
wait_msg += ' (~' + (s < 60 ? s + 's' : Math.ceil(s/60) + 'm') + ')';
}
bootbox.alert(wait_msg);
}, ttl);
}
// ── core batch processor ──────────────────────────────────────────────────
function _start_gl_batch(doc_type, ids, onComplete, formula_id_override) {
var formula_id = formula_id_override || $('#gl-formula-' + doc_type).val();
var $msg = $('#gl-msg-' + doc_type);
set_btn_state('#gl-btn-load-' + doc_type, false);
set_btn_state('#gl-btn-run-' + doc_type, false);
$msg.addClass('d-none').empty();
show_batch_overlay(DOC_LABELS[doc_type] || doc_type, ids.length);
var label = DOC_LABELS[doc_type] || doc_type;
if (formula_id_override) {
label += ' — ' + $('#gl-formula-' + doc_type + ' option[value="' + formula_id_override + '"]').text().trim();
}
show_batch_overlay(label, ids.length);
batch_process(
'gl_post',
@@ -298,54 +425,54 @@
update_batch_overlay(done, total);
},
function(failed) {
// Always release DB lock — whether succeeded or failed
release_op_lock('gl_post');
var succeeded = ids.length - failed.length;
if (failed.length === 0) {
_gl_failed[doc_type] = [];
BatchOverlay.done(succeeded + ' document(s) posted successfully.');
if (!onComplete) {
// Single-formula mode — show result in tab
if (failed.length === 0) {
_gl_failed[doc_type] = [];
BatchOverlay.done(succeeded + ' document(s) posted successfully.');
} else {
_gl_failed[doc_type] = failed;
var nums = failed.map(function(f) { return f.item; }).join(', ');
var detail = failed.map(function(f) {
return escape_html(f.item + (f.error ? ': ' + f.error : ''));
}).join('<br>');
BatchOverlay.done(failed.length + ' failed · ' + succeeded + ' succeeded.', function() {
$msg.removeClass('d-none alert-success').addClass('alert alert-danger')
.html('<strong>' + failed.length + ' failed</strong> after 3 retries (IDs: '
+ escape_html(nums) + '). ' + succeeded + ' succeeded.'
+ '<div class="small mt-2">' + detail + '</div>'
+ ' <button class="btn btn-sm btn-warning ms-2"'
+ ' onclick="retry_gl_batch(\'' + doc_type + '\')">'
+ '<i class="ti ti-refresh me-1"></i>Retry Failed</button>');
});
}
set_btn_state('#gl-btn-load-' + doc_type, true);
load_gl_tab(doc_type);
} else {
_gl_failed[doc_type] = failed;
var nums = failed.map(function(f) { return f.item; }).join(', ');
var detail = failed.map(function(f) {
return escape_html(f.item + (f.error ? ': ' + f.error : ''));
}).join('<br>');
BatchOverlay.done(failed.length + ' failed · ' + succeeded + ' succeeded.', function() {
$msg.removeClass('d-none alert-success').addClass('alert alert-danger')
.html('<strong>' + failed.length + ' failed</strong> after 3 retries (IDs: '
+ escape_html(nums) + '). ' + succeeded + ' succeeded.'
+ '<div class="small mt-2">' + detail + '</div>'
+ ' <button class="btn btn-sm btn-warning ms-2"'
+ ' onclick="retry_gl_batch(\'' + doc_type + '\')">'
+ '<i class="ti ti-refresh me-1"></i>Retry Failed</button>');
});
// All-Formulas sequential mode — hand off to queue runner
BatchOverlay.done(succeeded + ' posted' + (failed.length ? ', ' + failed.length + ' failed' : '') + '.');
onComplete(succeeded, failed.length);
}
// Log the batch action
// Log
var ctx = document.getElementById('session-context');
ajax_request({
url: '<?php echo $server_url?>accounting/api/engine/log_batch_action.php',
queueLock: false,
noLoading: true,
queueLock: false, noLoading: true,
data: {
otp: ctx ? ctx.dataset.otp : '',
company_id: ctx ? ctx.dataset.companyId : '',
action: 'post',
type: 'gl_post',
doc_type: doc_type,
total: ids.length,
succeeded: succeeded,
failed: failed.length,
action: 'post', type: 'gl_post',
doc_type: doc_type, total: ids.length,
succeeded: succeeded, failed: failed.length,
failed_ids: JSON.stringify(failed.map(function(f) { return f.item; }))
},
onSuccess: function() {}
});
// Reload table to reflect updated GL status
set_btn_state('#gl-btn-load-' + doc_type, true);
load_gl_tab(doc_type);
}
);
}
@@ -361,7 +488,7 @@
var ttl_minutes = Math.max(2, Math.ceil(ids.length * per_item_ms / 60000 * 1.2));
acquire_op_lock('gl_post', function() {
_start_gl_batch(doc_type, ids);
_start_gl_batch(doc_type, ids, null);
}, function(msg, res) {
var wait_msg = msg || 'A GL posting batch is already running.';
if (res && res.expires_at) {
@@ -369,7 +496,7 @@
var remaining_m = Math.ceil(remaining_s / 60);
wait_msg += '\nEstimated wait: ~' + (remaining_s < 60 ? remaining_s + ' seconds' : remaining_m + ' minute(s)') + '.';
}
alert(wait_msg);
bootbox.alert(wait_msg);
}, ttl_minutes);
}
@@ -408,7 +535,6 @@ function gl_tab_html(string $doc_type, string $label): string {
<div class="col-auto">
<label class="form-label mb-1 small">GL Formula <span class="text-danger">*</span></label>
<select id="gl-formula-{$doc_type}" class="form-select form-select-sm" style="width:220px;">
<option value="">— Select formula —</option>
</select>
</div>
<div class="col-auto">
@@ -431,7 +557,7 @@ function gl_tab_html(string $doc_type, string $label): string {
<!-- Result message -->
<div id="gl-msg-{$doc_type}" class="d-none mb-3"></div>
<!-- Document listing (informational, no selection) -->
<!-- Document listing -->
<table id="gl-table-{$doc_type}" class="table table-hover mb-0 table-centered">
<thead class="table-primary border-light">
<tr>
+3 -2
View File
@@ -555,7 +555,7 @@ function load_location_config(callback) {
/** =========================
* PREPARE FORM DATA
* ========================= */
function load_formula_options(select_id, document_type, selected_id) {
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',
@@ -570,12 +570,13 @@ function load_formula_options(select_id, document_type, selected_id) {
},
onSuccess: function(res) {
var $sel = $('#' + select_id);
$sel.empty().append('<option value="">— None —</option>');
$sel.empty();
$.each(res.output || [], function(i, f) {
var label = escape_html(f.formula_name) + (f.is_default == 1 ? ' (default)' : '');
$sel.append('<option value="' + f.id + '">' + label + '</option>');
});
if (selected_id) $sel.val(selected_id);
if (onLoaded) onLoaded(res.output || []);
}
});
}