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
+19 -7
View File
@@ -40,6 +40,15 @@ class WarehouseManager {
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;
}
@@ -243,7 +252,7 @@ class WarehouseManager {
/**
* Validate that the given row is the globally latest transaction for its SKU.
*
* Scans all td_stock_* tables via UNION ALL to find the single most recent
* Scans this company's td_stock_* tables via UNION ALL to find the single most recent
* transaction date across all warehouses for the SKU. If a newer row exists,
* deletion is blocked to enforce LIFO (last-in-first-out) reversal order.
*
@@ -261,20 +270,23 @@ class WarehouseManager {
string $product_name
): void {
// Discover all td_stock_* tables for this database
// Discover stock tables only for warehouses owned by this company.
$sth = $this->pdo->prepare(
"SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name LIKE 'td_stock_%'"
"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();
$sth->execute([':company_id' => $this->company_id]);
$tables = $sth->fetchAll(PDO::FETCH_COLUMN);
if (empty($tables)) {
return;
}
// Build UNION across all td_stock_* tables to find the global latest date
// Build UNION across this company's td_stock_* tables to find the global latest date
$unions = implode(' UNION ALL ', array_map(
fn($t) => "SELECT `type`, `date` FROM `$t`
WHERE company_id = :company_id