diff --git a/core/class/declarationtva.class.php b/core/class/declarationtva.class.php index 6c77f6f..dcd39df 100644 --- a/core/class/declarationtva.class.php +++ b/core/class/declarationtva.class.php @@ -541,7 +541,14 @@ class DeclarationTVA */ public function getAccountAmounts($account_code, $start_date, $end_date) { - + // For VAT accounts (445*), use fiscal year start date instead of period start + if (strpos($account_code, '445') === 0) { + $fy_start = $this->getFiscalYearStartDate($end_date); + if (!empty($fy_start)) { + $start_date = $fy_start; + } + } + // Use the correct Dolibarr accounting table structure $possible_queries = array( // Correct table and column names based on your Dolibarr structure @@ -587,6 +594,37 @@ class DeclarationTVA return array('base_amount' => 0, 'vat_amount' => 0, 'total_amount' => 0); } + /** + * Get fiscal year start date for a given reference date + * + * @param string $reference_date Reference date (YYYY-MM-DD) + * @return string Fiscal year start date (YYYY-MM-DD) + */ + private function getFiscalYearStartDate($reference_date) + { + // Try using Dolibarr accounting fiscal year table if available + $sql = "SHOW TABLES LIKE '" . MAIN_DB_PREFIX . "accounting_fiscalyear'"; + $result = $this->db->query($sql); + if ($result && $this->db->num_rows($result) > 0) { + $fy_sql = "SELECT date_start FROM " . MAIN_DB_PREFIX . "accounting_fiscalyear + WHERE entity = " . $this->entity . " + AND date_start <= '" . $this->db->escape($reference_date) . "' + AND date_end >= '" . $this->db->escape($reference_date) . "' + ORDER BY date_start DESC LIMIT 1"; + $fy_res = $this->db->query($fy_sql); + if ($fy_res && $this->db->num_rows($fy_res) > 0) { + $obj = $this->db->fetch_object($fy_res); + if (!empty($obj->date_start)) { + return $obj->date_start; + } + } + } + + // Fallback: January 1st of the year of the reference date + $year = date('Y', strtotime($reference_date)); + return $year . '-01-01'; + } + /** * Create CA-3 line record