Scope stock table access by company warehouses

This commit is contained in:
Thanakorn S
2026-05-28 15:36:49 +07:00
parent 2a6441c6a9
commit b634372b22
11 changed files with 174 additions and 78 deletions
@@ -97,13 +97,7 @@ class PurchaseOrderManager {
}
if (!$has_any_stock_in) return 0;
$sth = $this->pdo->prepare(
"SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name LIKE 'td_stock_%'"
);
$sth->execute();
$tables = $sth->fetchAll(PDO::FETCH_COLUMN);
$tables = $this->getStockTables();
$total = 0;
$pending = 0;
@@ -143,9 +137,32 @@ class PurchaseOrderManager {
throw new Exception("Invalid warehouse id.");
}
$sth = $this->pdo->prepare(
"SELECT id FROM md_warehouse
WHERE company_id = :company_id AND id = :id"
);
$sth->execute([':company_id' => $this->company_id, ':id' => $warehouse_id]);
if (!$sth->fetchColumn()) {
throw new Exception("Warehouse ID {$warehouse_id} not found.");
}
return 'td_stock_' . $warehouse_id;
}
private function getStockTables(): array
{
$sth = $this->pdo->prepare(
"SELECT t.table_name
FROM md_warehouse w
JOIN information_schema.tables t
ON t.table_schema = DATABASE()
AND t.table_name = CONCAT('td_stock_', w.id)
WHERE w.company_id = :company_id"
);
$sth->execute([':company_id' => $this->company_id]);
return $sth->fetchAll(PDO::FETCH_COLUMN);
}
private function syncPoItems(int $po_id, array $items): void
{
$this->pdo->prepare(
@@ -729,13 +746,7 @@ class PurchaseOrderManager {
if ($status === -1) throw new Exception("PO is already cancelled.");
// Guard: block if any approved stock-in rows exist for this PO
$sth = $this->pdo->prepare(
"SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name LIKE 'td_stock_%'"
);
$sth->execute();
$tables = $sth->fetchAll(PDO::FETCH_COLUMN);
$tables = $this->getStockTables();
foreach ($tables as $table) {
$sth = $this->pdo->prepare(
@@ -876,12 +887,7 @@ class PurchaseOrderManager {
throw new Exception('Cannot delete — this PO has linked supplier returns. Delete or cancel the returns first.');
}
$sth4 = $this->pdo->prepare(
"SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name LIKE 'td_stock_%'"
);
$sth4->execute();
$tables = $sth4->fetchAll(PDO::FETCH_COLUMN);
$tables = $this->getStockTables();
foreach ($tables as $table) {
$sth5 = $this->pdo->prepare(