diff --git a/core/class/declarationtva.class.php b/core/class/declarationtva.class.php index 147cf40..43e5efa 100644 --- a/core/class/declarationtva.class.php +++ b/core/class/declarationtva.class.php @@ -902,6 +902,30 @@ class DeclarationTVA return false; } + // Check if accounting entries already exist for this declaration + $existing_entries_sql = "SELECT COUNT(*) as count FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping + WHERE doc_ref = '" . $this->db->escape($this->declaration_name) . "' + AND entity = " . $this->entity; + $existing_result = $this->db->query($existing_entries_sql); + if ($existing_result && $this->db->num_rows($existing_result) > 0) { + $existing_obj = $this->db->fetch_object($existing_result); + if ($existing_obj->count > 0) { + 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_sql = "DELETE FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping + WHERE doc_ref = '" . $this->db->escape($this->declaration_name) . "' + AND entity = " . $this->entity; + $delete_result = $this->db->query($delete_sql); + if ($delete_result) { + error_log("DEBUG: Successfully deleted " . $existing_obj->count . " existing entries"); + } else { + error_log("DEBUG: Failed to delete existing entries: " . $this->db->lasterror()); + } + } + } + // Create a declaration object with the fetched data $declaration = new stdClass(); $declaration->rowid = $this->rowid;