NODE JS introduction: socket polling

This commit is contained in:
Thanakorn S
2026-05-22 17:01:59 +07:00
parent 2410f7bade
commit 9c275eb358
17 changed files with 1520 additions and 2135 deletions
+105 -28
View File
@@ -180,6 +180,15 @@
<?php require '../include_ending.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<style>
/* Brief yellow flash when a card updates silently via WebSocket */
@keyframes card-flash {
0% { box-shadow: 0 0 0 3px rgba(250,204,21,0.8); }
100% { box-shadow: none; }
}
.card-flash { animation: card-flash 1s ease-out; }
</style>
<script>
var trend_chart_instance = null;
@@ -207,26 +216,33 @@
return Number(n).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
}
function show_overlays() {
$('#overlay_revenue, #overlay_expense, #overlay_net, #overlay_journals, #overlay_lock, #overlay_trend, #overlay_source, #overlay_recent').show();
// Flash a card briefly to signal a silent update happened
function flash_card(el) {
if (!el) return;
el.classList.remove('card-flash');
void el.offsetWidth; // force reflow so animation restarts
el.classList.add('card-flash');
setTimeout(function() { el.classList.remove('card-flash'); }, 1000);
}
function set_dashboard_loading() {
show_overlays();
['stat_revenue', 'stat_expense', 'stat_net', 'stat_journals'].forEach(function(id) {
document.getElementById(id).textContent = '—';
});
document.getElementById('posting_window_banner').textContent = 'Loading...';
document.getElementById('by_source_list').innerHTML =
'<div class="text-center text-muted small py-4">Loading...</div>';
document.getElementById('recent_tbody').innerHTML =
'<tr><td colspan="7" class="text-center text-muted py-4 small">Loading...</td></tr>';
}
// ── Individual load functions ─────────────────────────────────────────────
// Each accepts a `silent` flag:
// false (default) — show overlay spinner, blank value while loading
// true — keep existing value visible, flash card on update
function load_dashboard() {
set_dashboard_loading();
// load_pl(silent, flash_revenue, flash_expense)
// One DB query — but only flash cards that actually changed.
// flash_revenue / flash_expense default to true when not passed.
function load_pl(silent, flash_revenue, flash_expense) {
if (flash_revenue === undefined) flash_revenue = true;
if (flash_expense === undefined) flash_expense = true;
// Revenue, Expenses, Net Profit
if (!silent) {
$('#overlay_revenue, #overlay_expense, #overlay_net').show();
['stat_revenue', 'stat_expense', 'stat_net'].forEach(function(id) {
document.getElementById(id).textContent = '—';
});
}
ajax_request({
url: server_url + 'ac_dashboard/api/engine/pl.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
@@ -252,48 +268,89 @@
if (sub) sub.className = net >= 0 ? 'text-success mb-0 small' : 'text-danger mb-0 small';
}
$('#overlay_net').hide();
// Flash only cards that actually changed
if (silent) {
if (flash_revenue) flash_card(document.getElementById('stat_revenue').closest('.card'));
if (flash_expense) flash_card(document.getElementById('stat_expense').closest('.card'));
flash_card(net_el.closest('.card')); // net profit always updates if either changed
}
}
});
}
// Journal Entries count
function load_journals(silent) {
if (!silent) {
$('#overlay_journals').show();
document.getElementById('stat_journals').textContent = '—';
}
ajax_request({
url: server_url + 'ac_dashboard/api/engine/journals.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
onSuccess: function(res) {
document.getElementById('stat_journals').textContent = res.output.journal_count;
$('#overlay_journals').hide();
if (silent) flash_card(document.getElementById('stat_journals').closest('.card'));
}
});
}
// Posting window banner
function load_posting_window() {
$('#overlay_lock').show();
ajax_request({
url: server_url + 'ac_dashboard/api/engine/posting_window.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
onSuccess: function(res) { render_posting_window(res.output); }
});
}
// Revenue vs Expenses trend chart
function load_trend(silent) {
if (!silent) $('#overlay_trend').show();
ajax_request({
url: server_url + 'ac_dashboard/api/engine/trend.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
onSuccess: function(res) { render_trend(res.output.trend); }
onSuccess: function(res) { render_trend(res.output.trend, silent); }
});
}
// Entries by type breakdown
function load_by_source(silent) {
if (!silent) {
$('#overlay_source').show();
document.getElementById('by_source_list').innerHTML =
'<div class="text-center text-muted small py-4">Loading...</div>';
}
ajax_request({
url: server_url + 'ac_dashboard/api/engine/by_source.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
onSuccess: function(res) { render_by_source(res.output.by_source); }
onSuccess: function(res) { render_by_source(res.output.by_source, silent); }
});
}
// Recent journal entries table
function load_recent(silent) {
if (!silent) {
$('#overlay_recent').show();
document.getElementById('recent_tbody').innerHTML =
'<tr><td colspan="7" class="text-center text-muted py-4 small">Loading...</td></tr>';
}
ajax_request({
url: server_url + 'ac_dashboard/api/engine/recent.php',
autoPrepare: true, checkRequired: 0, noLoading: true, queueLock: false, action: 'read',
onSuccess: function(res) { render_recent(res.output.recent); }
onSuccess: function(res) { render_recent(res.output.recent, silent); }
});
}
// ── Full dashboard load (first load) ─────────────────────────────────────
function load_dashboard() {
load_pl(false);
load_journals(false);
load_posting_window();
load_trend(false);
load_by_source(false);
load_recent(false);
}
// ── Render functions ──────────────────────────────────────────────────────
function render_posting_window(window_data) {
var el = document.getElementById('posting_window_banner');
var from = window_data.open_from || '';
@@ -308,8 +365,7 @@
$('#overlay_lock').hide();
}
function render_trend(trend) {
// Build exactly 6 month labels (last 6 months ending today), fill zeros for missing
function render_trend(trend, silent) {
var labels = [], revenues = [], expenses = [];
var idx = {};
trend.forEach(function(r){ idx[r.period] = r; });
@@ -345,9 +401,10 @@
}
});
$('#overlay_trend').hide();
if (silent) flash_card(document.getElementById('trend_chart').closest('.card'));
}
function render_by_source(rows) {
function render_by_source(rows, silent) {
var el = document.getElementById('by_source_list');
if (!rows || rows.length === 0) {
el.innerHTML = '<div class="text-center text-muted small py-4">No entries found.</div>';
@@ -371,9 +428,10 @@
});
el.innerHTML = html;
$('#overlay_source').hide();
if (silent) flash_card(el.closest('.card'));
}
function render_recent(rows) {
function render_recent(rows, silent) {
var tbody = document.getElementById('recent_tbody');
if (!rows || rows.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-4 small">No journal entries found.</td></tr>';
@@ -397,9 +455,28 @@
});
tbody.innerHTML = html;
$('#overlay_recent').hide();
if (silent) flash_card(tbody.closest('.card'));
}
// ── Initial load ──────────────────────────────────────────────────────────
load_dashboard();
// ── Real-time: targeted silent updates per event payload ──────────────────
if (window._socket) {
window._socket.on('gl_posted', function(data) {
console.log('[dashboard] gl_posted', data);
if (data.has_revenue || data.has_expense) {
load_pl(true, data.has_revenue, data.has_expense); // only affected side flashes
load_trend(true); // trend = revenue vs expense chart, only relevant when those change
}
// Always update regardless of which accounts were hit
load_journals(true);
load_by_source(true);
load_recent(true);
});
}
</script>
</body>
@@ -13,6 +13,7 @@ require '../../../assets/utils/classes_ac/posting/PaymentPosting.php';
require '../../../assets/utils/classes_ac/posting/PurchasePosting.php';
require_role($user_role, ['owner', 'admin']);
require_once '../../../assets/utils/notify_node.php';
$doc_type = trim((string)($data['doc_type'] ?? ''));
$id = (int)($data['id'] ?? 0);
@@ -56,6 +57,22 @@ try {
$answer['success'] = 1;
$answer['message'] = $existing ? 'GL entry replaced.' : 'GL entry posted.';
$has_revenue = false;
$has_expense = false;
foreach ($built['lines'] as $line) {
$code = (int)($line['account_code'] ?? 0);
if ($code >= 4000 && $code < 5000) $has_revenue = true;
if ($code >= 5000) $has_expense = true;
}
notify_node('gl_posted', [
'doc_type' => $doc_type,
'id' => $id,
'action' => $existing ? 'replaced' : 'posted',
'has_revenue' => $has_revenue,
'has_expense' => $has_expense,
], $company_id);
} catch (Exception $e) {
if ($pdo2->inTransaction()) $pdo2->rollBack();
$answer['message'] = $e->getMessage();
@@ -234,25 +234,50 @@ class FinancialReports
// ── Monthly Trend ─────────────────────────────────────────────────────────
// Revenue vs expense per period for the last N months (defaults to 6).
// Returns rows: [{period, revenue, expense}]
// Reads from etl_gl_summary; falls back to td_gl_item for periods not yet in ETL.
public function getMonthlyTrend(int $months = 6): array
{
$from = date('Y-m', strtotime('-' . ($months - 1) . ' months'));
$sth = $this->pdo->prepare("
SELECT
g.period,
SUM(CASE WHEN a.account_type = 'revenue' THEN i.credit - i.debit ELSE 0 END) AS revenue,
SUM(CASE WHEN a.account_type = 'expense' THEN i.debit - i.credit ELSE 0 END) AS expense
FROM td_gl g
JOIN td_gl_item i ON i.gl_id = g.id AND i.company_id = g.company_id
JOIN md_account a ON a.company_id = i.company_id AND a.account_code = i.account_code
WHERE g.company_id = :cid AND g.period >= :from_period
GROUP BY g.period
ORDER BY g.period ASC
$sth = $this->pdo->prepare("
SELECT period, acc_code, SUM(debit) AS d, SUM(credit) AS c
FROM etl_gl_summary
WHERE company_id = :cid AND acc_code >= 4000 AND period >= :from
GROUP BY period, acc_code
UNION ALL
SELECT g.period, i.account_code AS acc_code, SUM(i.debit) AS d, SUM(i.credit) AS c
FROM td_gl_item i
JOIN td_gl g ON g.id = i.gl_id AND g.company_id = i.company_id
LEFT JOIN (
SELECT DISTINCT period FROM etl_gl_summary WHERE company_id = :cid2
) etl ON etl.period = g.period
WHERE i.company_id = :cid3
AND i.account_code >= 4000
AND g.source_type != 'voided'
AND g.period >= :from2
AND etl.period IS NULL
GROUP BY g.period, i.account_code
");
$sth->execute([':cid' => $this->companyId, ':from_period' => $from]);
return $sth->fetchAll(PDO::FETCH_ASSOC);
$sth->execute([
':cid' => $this->companyId, ':from' => $from,
':cid2' => $this->companyId,
':cid3' => $this->companyId, ':from2' => $from,
]);
$by_period = [];
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$p = $row['period'];
$code = (int)$row['acc_code'];
if (!isset($by_period[$p])) $by_period[$p] = ['period' => $p, 'revenue' => 0.0, 'expense' => 0.0];
if ($code >= 4000 && $code < 5000) $by_period[$p]['revenue'] += (float)$row['c'] - (float)$row['d'];
else $by_period[$p]['expense'] += (float)$row['d'] - (float)$row['c'];
}
ksort($by_period);
return array_values($by_period);
}
// ── Dashboard focused methods ─────────────────────────────────────────────
@@ -260,29 +285,48 @@ class FinancialReports
public function getDashboardPL(): array
{
// ETL first — all periods present in etl_gl_summary
// Fallback — periods in td_gl but missing from ETL (gap fill)
$sth = $this->pdo->prepare("
SELECT
a.account_type,
COALESCE(SUM(i.debit), 0) AS total_debit,
COALESCE(SUM(i.credit), 0) AS total_credit
FROM md_account a
JOIN td_gl_item i ON i.company_id = a.company_id AND i.account_code = a.account_code
JOIN td_gl g ON g.company_id = i.company_id AND g.id = i.gl_id
WHERE a.company_id = :cid
AND a.account_type IN ('revenue', 'expense')
AND a.is_posting = 1
GROUP BY a.account_type
SELECT acc_code, SUM(debit) AS d, SUM(credit) AS c
FROM etl_gl_summary
WHERE company_id = :cid AND acc_code >= 4000
GROUP BY acc_code
UNION ALL
SELECT i.account_code AS acc_code, SUM(i.debit) AS d, SUM(i.credit) AS c
FROM td_gl_item i
JOIN td_gl g ON g.id = i.gl_id AND g.company_id = i.company_id
LEFT JOIN (
SELECT DISTINCT period FROM etl_gl_summary WHERE company_id = :cid2
) etl ON etl.period = g.period
WHERE i.company_id = :cid3
AND i.account_code >= 4000
AND g.source_type != 'voided'
AND etl.period IS NULL
GROUP BY i.account_code
");
$sth->execute([':cid' => $this->companyId]);
$sth->execute([
':cid' => $this->companyId,
':cid2' => $this->companyId,
':cid3' => $this->companyId,
]);
$revenue = 0.0;
$expense = 0.0;
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
if ($row['account_type'] === 'revenue') $revenue += (float)$row['total_credit'] - (float)$row['total_debit'];
if ($row['account_type'] === 'expense') $expense += (float)$row['total_debit'] - (float)$row['total_credit'];
$code = (int)$row['acc_code'];
if ($code >= 4000 && $code < 5000) $revenue += (float)$row['c'] - (float)$row['d'];
else $expense += (float)$row['d'] - (float)$row['c'];
}
return ['revenue' => $revenue, 'expense' => $expense, 'net_profit' => $revenue - $expense];
return [
'revenue' => $revenue,
'expense' => $expense,
'net_profit' => $revenue - $expense,
'etl_gaps' => $this->getEtlGaps(),
];
}
public function getDashboardJournalCount(): int
@@ -404,6 +448,30 @@ class FinancialReports
];
}
// Returns periods that exist in td_gl but are missing from etl_gl_summary.
// Used by getDashboardPL() to signal which periods need a rebuild queue job.
private function getEtlGaps(string $from_period = ''): array
{
$sql = "
SELECT DISTINCT g.period
FROM td_gl g
LEFT JOIN (
SELECT DISTINCT period FROM etl_gl_summary WHERE company_id = :cid2
) etl ON etl.period = g.period
WHERE g.company_id = :cid
AND g.source_type NOT IN ('voided', 'reversal')
AND etl.period IS NULL
" . ($from_period ? "AND g.period >= :from_period" : "") . "
ORDER BY g.period
";
$params = [':cid' => $this->companyId, ':cid2' => $this->companyId];
if ($from_period) $params[':from_period'] = $from_period;
$sth = $this->pdo->prepare($sql);
$sth->execute($params);
return $sth->fetchAll(PDO::FETCH_COLUMN);
}
// ── GL Movement ───────────────────────────────────────────────────────────
// Per-account ledger: opening balance + chronological lines with running balance.
+44 -2
View File
@@ -71,6 +71,7 @@ class GlManager
':updated_at' => $now,
]);
$this->insertLines((int)$this->pdo->lastInsertId(), $lines);
$this->upsertEtl($lines, $period);
}
public function replaceManual(int $gl_id, string $reference, string $description, string $journal_date, string $period, array $lines): void
@@ -99,6 +100,9 @@ class GlManager
'lines' => $this->getLines($gl_id),
];
$old_lines = $history[count($history) - 1]['lines']; // captured just above
$old_period = $gl['period'];
$this->pdo->prepare(
"DELETE FROM td_gl_item WHERE company_id = :cid AND gl_id = :gl_id"
)->execute([':cid' => $this->companyId, ':gl_id' => $gl_id]);
@@ -122,6 +126,8 @@ class GlManager
]);
$this->insertLines($gl_id, $lines);
$this->upsertEtl($old_lines, $old_period, -1);
$this->upsertEtl($lines, $period);
}
public function postManual(string $reference, string $description, string $journal_date, string $period, array $lines): int
@@ -148,6 +154,7 @@ class GlManager
]);
$gl_id = (int)$this->pdo->lastInsertId();
$this->insertLines($gl_id, $lines);
$this->upsertEtl($lines, $period);
return $gl_id;
}
@@ -179,11 +186,14 @@ class GlManager
$history = json_decode($gl['history'], true) ?: [];
// Snapshot current lines into history
$old_lines = $this->getLines($gl_id);
$old_period = $gl['period'];
$history[] = [
'version' => $version,
'formula_id' => (int)$gl['formula_id'],
'replaced_at' => $now,
'lines' => $this->getLines($gl_id),
'lines' => $old_lines,
];
$this->pdo->prepare(
@@ -210,6 +220,8 @@ class GlManager
]);
$this->insertLines($gl_id, $lines);
$this->upsertEtl($old_lines, $old_period, -1);
$this->upsertEtl($lines, $period);
}
public function delete(string $source_type, int $source_id): void
@@ -264,7 +276,9 @@ class GlManager
':created_at' => $now,
':updated_at' => $now,
]);
$this->insertLines((int)$this->pdo->lastInsertId(), $reversal_lines);
$reversal_gl_id = (int)$this->pdo->lastInsertId();
$this->insertLines($reversal_gl_id, $reversal_lines);
$this->upsertEtl($reversal_lines, $gl['period']);
}
// Mark original as voided — keeps audit trail; getBySource() won't match 'voided' source_type
@@ -326,4 +340,32 @@ class GlManager
]);
}
}
// sign=1 to add, sign=-1 to subtract (used when replacing old lines)
private function upsertEtl(array $lines, string $period, int $sign = 1): void
{
if (empty($lines) || empty($period)) return;
$sth = $this->pdo->prepare(
"INSERT INTO etl_gl_summary
(company_id, acc_code, period, debit, credit, count, updated_at)
VALUES
(:cid, :acc, :period, :debit, :credit, :cnt, NOW())
ON DUPLICATE KEY UPDATE
debit = debit + VALUES(debit),
credit = credit + VALUES(credit),
count = count + VALUES(count),
updated_at = NOW()"
);
foreach ($lines as $line) {
$sth->execute([
':cid' => $this->companyId,
':acc' => (int)($line['account_code'] ?? 0),
':period' => $period,
':debit' => (float)($line['debit'] ?? 0) * $sign,
':credit' => (float)($line['credit'] ?? 0) * $sign,
':cnt' => $sign,
]);
}
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* notify_node — fire-and-forget event push to the Node.js real-time server.
*
* Call this AFTER a successful DB commit. It never throws — if Node is down
* the request times out silently in 1 second.
*
* @param string $event Event name, e.g. 'gl_posted'
* @param array $data Payload sent to the browser
* @param int $company_id Scopes the broadcast to one company's room
*/
function notify_node(string $event, array $data, int $company_id): void
{
if ($company_id <= 0) return;
$body = json_encode([
'event' => $event,
'data' => $data,
'company_id' => $company_id,
]);
$ch = curl_init(defined('NODE_EMIT_URL') ? NODE_EMIT_URL : 'http://127.0.0.1:3000/emit');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-emit-secret: ' . (defined('NODE_EMIT_SECRET') ? NODE_EMIT_SECRET : ''),
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 1, // never block PHP
CURLOPT_CONNECTTIMEOUT => 1,
]);
curl_exec($ch);
curl_close($ch);
}
@@ -52,6 +52,8 @@
$answer['new_id'] = $new_id;
$answer['message'] = 'Payment posted.';
(new UsageGuard($pdo1, $company_id, $packages))->increment();
require_once '../../../assets/utils/notify_node.php';
notify_node('payment_posted', ['id' => $new_id], $company_id);
exit(json_encode($answer));
}
@@ -52,6 +52,8 @@
$answer['new_id'] = $new_id;
$answer['message'] = 'Receipt posted.';
(new UsageGuard($pdo1, $company_id, $packages))->increment();
require_once '../../../assets/utils/notify_node.php';
notify_node('receipt_posted', ['id' => $new_id], $company_id);
exit(json_encode($answer));
}
+24
View File
@@ -7,6 +7,30 @@
</div>
<!-- ── Real-time WebSocket connection ──────────────────────────────────────── -->
<!-- Socket.io client is served by the Node.js server itself -->
<script src="<?php echo NODE_PUBLIC_URL; ?>/socket.io/socket.io.js"></script>
<script>
(function () {
// company_id is set in include_topbar.php as a JS global
if (typeof company_id === 'undefined' || !company_id) return;
window._socket = io('<?php echo NODE_PUBLIC_URL; ?>', {
query: { company_id: company_id },
reconnection: true,
reconnectionDelay: 2000,
});
window._socket.on('connect', function () {
console.log('[socket] connected', window._socket.id);
});
window._socket.on('disconnect', function () {
console.log('[socket] disconnected');
});
})();
</script>
<!-- Stock rows modal — used by: order/order.php, order/return.php, po/po.php, po/supplier_returns.php (via show_stock_rows() in custom.js) -->
<div class="modal fade" id="stock_rows_modal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-scrollable">
+2 -1
View File
@@ -255,7 +255,8 @@ $_usage_full = $_usage_max_pct >= 100;
// Global Variables
var server_url = '<?php echo $server_url; ?>';
var prop_limit = '<?php echo $prop['limit']; ?>';
var user_role = document.getElementById('session-context')?.dataset.role || 'viewer';
var user_role = document.getElementById('session-context')?.dataset.role || 'viewer';
var company_id = parseInt(document.getElementById('session-context')?.dataset.companyId || '0', 10);
// ── Log out ───────────────────────────────────────────────────────────────────
function log_out() {