From 3b55869a49b74c6d688790febc679a2da9f9d5de Mon Sep 17 00:00:00 2001 From: Frank Cools Date: Thu, 9 Oct 2025 01:15:23 +0200 Subject: [PATCH] Add comprehensive duplicate entry prevention - Add period-based deletion to remove entries from same period - Delete entries with TVA-related doc_ref patterns - Delete entries from same year to catch all related entries - More aggressive cleanup to prevent BookkeepingRecordAlreadyExists error --- core/class/declarationtva.class.php | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/core/class/declarationtva.class.php b/core/class/declarationtva.class.php index a1e8fe1..10c16d9 100644 --- a/core/class/declarationtva.class.php +++ b/core/class/declarationtva.class.php @@ -924,16 +924,34 @@ class DeclarationTVA error_log("DEBUG: Found " . $existing_obj->count . " existing accounting entries for declaration " . $this->declaration_name); error_log("DEBUG: Deleting existing entries to prevent duplicates"); - // Delete existing entries to prevent duplicates + // Delete existing entries to prevent duplicates (from all journals) $delete_sql = "DELETE FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE doc_ref = '" . $this->db->escape($this->declaration_name) . "' AND entity = " . $this->entity; + + // Also delete entries that might have been created with different doc_ref but same period + $delete_period_sql = "DELETE FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping + WHERE doc_date >= '" . $this->start_date . "' + AND doc_date <= '" . $this->end_date . "' + AND (doc_ref LIKE '%" . $this->db->escape($this->declaration_name) . "%' + OR doc_ref LIKE '%TVA%' + OR doc_ref LIKE '%" . date('Y', strtotime($this->start_date)) . "%') + AND entity = " . $this->entity; $delete_result = $this->db->query($delete_sql); if ($delete_result) { $deleted_count = $this->db->affected_rows($delete_result); - error_log("DEBUG: Successfully deleted " . $deleted_count . " existing entries"); + error_log("DEBUG: Successfully deleted " . $deleted_count . " existing entries by doc_ref"); } else { - error_log("DEBUG: Failed to delete existing entries: " . $this->db->lasterror()); + error_log("DEBUG: Failed to delete existing entries by doc_ref: " . $this->db->lasterror()); + } + + // Execute period-based deletion + $delete_period_result = $this->db->query($delete_period_sql); + if ($delete_period_result) { + $deleted_period_count = $this->db->affected_rows($delete_period_result); + error_log("DEBUG: Successfully deleted " . $deleted_period_count . " existing entries by period"); + } else { + error_log("DEBUG: Failed to delete existing entries by period: " . $this->db->lasterror()); } // Verify deletion