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