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
+10 -7
View File
@@ -32,10 +32,10 @@ class ContactManager {
/**
* Check whether a contact is referenced by any active stock transaction
* across all td_stock_* warehouse tables.
* across this company's td_stock_* warehouse tables.
*
* Used as a pre-delete guard to prevent orphaning stock records.
* Scans information_schema to discover all td_stock_* tables dynamically.
* Discovers existing td_stock_* tables through md_warehouse scoped to this company.
* Table names from information_schema are backtick-quoted for safety.
*
* @param int $contact_id The md_contact.id to check.
@@ -44,11 +44,14 @@ class ContactManager {
private function hasActiveStock(int $contact_id): bool {
$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);
foreach ($tables as $table) {
@@ -409,7 +412,7 @@ class ContactManager {
* Soft-delete a contact by negating its company_id.
*
* Blocks deletion if the contact is referenced in any active stock
* transaction across all td_stock_* warehouse tables, preventing
* transaction across this company's td_stock_* warehouse tables, preventing
* broken foreign key references in transaction history.
*
* Must be called inside dbTransaction() by the caller.