Files
wms-app/app/ics/api/engine_report/stock_trend.php
T
2026-04-09 09:48:47 +07:00

83 lines
3.0 KiB
PHP

<?php
session_start();
require '../../../assets/utils/db_auth.php';
$id = 0;
$warehouse_id = (int)$data['warehouse'];
$whMgmt = new WarehouseManager($pdo2, $company_id);
$warehouse = $whMgmt->getStockContext($warehouse_id, $id);
$table = $warehouse['table'];
// ── Always last 12 months ────────────────────────────────────────────
$now = new DateTime();
$start = (clone $now)->modify('-12 months')->format('Y-m-d 00:00:00');
$end = $now->format('Y-m-d 23:59:59');
// ── Get cumulative balance BEFORE the 12-month window ────────────────
$sql_prior = "SELECT
ROUND(COALESCE(SUM(a.`in`), 0) - COALESCE(SUM(a.`out`), 0), 2) AS `balance`
FROM `{$table}` a
WHERE
a.company_id = {$company_id} and
a.date < '{$start}'";
$sth = $pdo2->prepare($sql_prior);
$sth->execute();
$prior_balance = (float)$sth->fetchColumn();
// ── Get monthly in/out for the 12-month window ──────────────────────
$sql = "SELECT
DATE_FORMAT(a.date, '%Y-%m') AS `sort_key`,
ROUND(SUM(a.`in`), 2) AS `stock_in`,
ROUND(SUM(a.`out`), 2) AS `stock_out`
FROM `{$table}` a
WHERE
a.company_id = {$company_id} and
a.date >= '{$start}' and
a.date <= '{$end}'
GROUP BY `sort_key`
ORDER BY `sort_key` ASC";
$sth = $pdo2->prepare($sql);
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
// ── Index DB results by sort_key (YYYY-MM) ──────────────────────────
$dataByMonth = [];
foreach ($rows as $row) {
$dataByMonth[$row['sort_key']] = $row;
}
// ── Always build 12 months, accumulate running balance ──────────────
$labels = [];
$balance = [];
$running = $prior_balance;
for ($i = 11; $i >= 0; $i--) {
$dt = (clone $now)->modify("-{$i} months");
$key = $dt->format('Y-m');
$label = $dt->format('M');
$month_in = isset($dataByMonth[$key]) ? (float)$dataByMonth[$key]['stock_in'] : 0;
$month_out = isset($dataByMonth[$key]) ? (float)$dataByMonth[$key]['stock_out'] : 0;
$running += ($month_in - $month_out);
$labels[] = $label;
$balance[] = round($running, 2);
}
// ── Response ─────────────────────────────────────────────────────────
$output = [
'labels' => $labels,
'balance' => $balance,
];
$answer["output"] = $output;
$answer["success"] = 1;
exit(json_encode($answer));
?>