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
This commit is contained in:
Frank Cools 2025-10-09 01:15:23 +02:00
parent ef190f4c73
commit 3b55869a49

View File

@ -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