Add proper database transaction handling

- Start transaction with db->begin() before creating entries
- Commit transaction with db->commit() after all entries created
- Rollback transaction with db->rollback() on any failure
- Follow Dolibarr best practices for accounting entry creation
- Ensure entries are properly committed to database
This commit is contained in:
Frank Cools 2025-10-08 22:23:00 +02:00
parent c6984d8527
commit c400608a40

View File

@ -1225,6 +1225,10 @@ class DeclarationTVA
// Use Dolibarr's bookkeeping class with correct field mapping
require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
// Start transaction
$this->db->begin();
error_log("DEBUG: Database transaction started");
foreach ($entries as $entry) {
error_log("DEBUG: Creating accounting entry for account: " . $entry['account_code'] . ", debit: " . $entry['debit'] . ", credit: " . $entry['credit']);
@ -1295,6 +1299,7 @@ class DeclarationTVA
error_log("DEBUG: Debit entry created successfully with ID: " . $result);
} else {
error_log("DEBUG: Debit entry creation failed - result: " . $result . ", error: " . $debit->error);
$this->db->rollback();
$this->error = 'Failed to create debit entry: ' . $debit->error;
return false;
}
@ -1332,12 +1337,17 @@ class DeclarationTVA
error_log("DEBUG: Credit entry created successfully with ID: " . $result);
} else {
error_log("DEBUG: Credit entry creation failed - result: " . $result . ", error: " . $credit->error);
$this->db->rollback();
$this->error = 'Failed to create credit entry: ' . $credit->error;
return false;
}
}
}
// Commit the transaction
$this->db->commit();
error_log("DEBUG: Database transaction committed");
// Final verification - check all entries created for this declaration
$final_check_sql = "SELECT COUNT(*) as total_entries FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping
WHERE doc_ref = '" . $this->db->escape($declaration->declaration_name) . "'";