diff --git a/core/class/declarationtva_pdf.class.php b/core/class/declarationtva_pdf.class.php index d4d2906..9c9ab1c 100644 --- a/core/class/declarationtva_pdf.class.php +++ b/core/class/declarationtva_pdf.class.php @@ -1862,6 +1862,12 @@ class DeclarationTVA_PDF $entries[] = $rounding_entry; } + // Add balancing entry to ensure debits equal credits + $balancing_entry = $this->getBalancingEntry($declaration, $entries); + if ($balancing_entry) { + $entries[] = $balancing_entry; + } + return $entries; } @@ -2031,4 +2037,66 @@ class DeclarationTVA_PDF return $entry; } + + /** + * Get balancing entry to ensure debits equal credits + * + * @param DeclarationTVA $declaration Declaration object + * @param array $entries Current journal entries + * @return array|null Journal entry + */ + private function getBalancingEntry($declaration, $entries) + { + $total_debits = 0; + $total_credits = 0; + + // Calculate totals from existing entries + foreach ($entries as $entry) { + if (!empty($entry['debit'])) { + $total_debits += $this->parseAmount($entry['debit']); + } + if (!empty($entry['credit'])) { + $total_credits += $this->parseAmount($entry['credit']); + } + } + + $difference = $total_debits - $total_credits; + + // If difference is very small (less than 0.01), no balancing entry needed + if (abs($difference) < 0.01) { + return null; + } + + $entry = array( + 'account_code' => '4456700', + 'account_label' => 'TVA à payer', + 'entry_label' => $declaration->declaration_name, + 'debit' => '', + 'credit' => '' + ); + + if ($difference < 0) { + // More credits than debits, add debit to balance + $entry['debit'] = $this->formatAmountReal(abs($difference)); + } else { + // More debits than credits, add credit to balance + $entry['credit'] = $this->formatAmountReal($difference); + } + + return $entry; + } + + /** + * Parse amount string back to float + * + * @param string $amount_string Formatted amount string + * @return float Parsed amount + */ + private function parseAmount($amount_string) + { + // Remove spaces and convert comma to dot + $amount_string = str_replace(' ', '', $amount_string); + $amount_string = str_replace(',', '.', $amount_string); + return (float)$amount_string; + } }