diff --git a/htdocs/accountancy/admin/closure.php b/htdocs/accountancy/admin/closure.php index 99f9c8c783c..d1b0d10e262 100644 --- a/htdocs/accountancy/admin/closure.php +++ b/htdocs/accountancy/admin/closure.php @@ -61,6 +61,24 @@ if ($action == 'update') { $error++; } + $accountinggroupsusedforbalancesheetaccount = GETPOST('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT', 'alphanohtml'); + if (!empty($accountinggroupsusedforbalancesheetaccount)) { + if (!dolibarr_set_const($db, 'ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT', $accountinggroupsusedforbalancesheetaccount, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } else { + $error++; + } + + $accountinggroupsusedforincomestatement = GETPOST('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT', 'alpha'); + if (!empty($accountinggroupsusedforincomestatement)) { + if (!dolibarr_set_const($db, 'ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT', $accountinggroupsusedforincomestatement, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } else { + $error++; + } + foreach ($list_account_main as $constname) { $constvalue = GETPOST($constname, 'alpha'); if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { @@ -117,12 +135,26 @@ foreach ($list_account_main as $key) { // Journal print ''; -print ''.$langs->trans("ACCOUNTING_CLOSURE_DEFAULT_JOURNAL").''; +print ''.$langs->trans("ACCOUNTING_CLOSURE_DEFAULT_JOURNAL").''; print ''; $defaultjournal = getDolGlobalString('ACCOUNTING_CLOSURE_DEFAULT_JOURNAL'); print $formaccounting->select_journal($defaultjournal, "ACCOUNTING_CLOSURE_DEFAULT_JOURNAL", 9, 1, 0, 0); print ''; +// Accounting groups used for the balance sheet account +print ''; +print ''.$langs->trans("ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT").''; +print ''; +print ''; +print ''; + +// Accounting groups used for the income statement +print ''; +print ''.$langs->trans("ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT").''; +print ''; +print ''; +print ''; + print "\n"; print '
'; diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 75503e8cca9..49df97ac75e 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -26,6 +26,9 @@ // Class require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; /** * Class to manage Ledger (General Ledger and Subledger) @@ -194,6 +197,15 @@ class BookKeeping extends CommonObject */ public $picto = 'generic'; + /** + * @var array List of active fiscal periods cached [[date_start, date_end], ...] + */ + public static $active_fiscal_period_cached; + /** + * @var string[] SQL filter used for check if the bookkeeping record can be created/inserted/modified/deleted (cached) + */ + public static $can_modify_bookkeeping_sql_cached; + /** * Constructor @@ -285,6 +297,14 @@ class BookKeeping extends CommonObject $this->credit = 0.0; } + $result = $this->validBookkeepingDate($this->doc_date); + if ($result < 0) { + return -1; + } elseif ($result == 0) { + $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod'); + return -1; + } + // Check parameters if (($this->numero_compte == "") || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined') { $langs->loadLangs(array("errors")); @@ -630,6 +650,14 @@ class BookKeeping extends CommonObject $this->montant = 0; } + $result = $this->validBookkeepingDate($this->doc_date); + if ($result < 0) { + return -1; + } elseif ($result == 0) { + $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod'); + return -1; + } + $this->debit = price2num($this->debit, 'MT'); $this->credit = price2num($this->credit, 'MT'); $this->montant = price2num($this->montant, 'MT'); @@ -726,10 +754,11 @@ class BookKeeping extends CommonObject /** * Load object in memory from the database * - * @param int $id Id object - * @param string $ref Ref (Not used. Does not exists on this table, same as rowid) - * @param string $mode Mode - * @return int Int <0 if KO, 0 if not found, >0 if OK + * @param int $id Id object + * @param string $ref Ref + * @param string $mode Mode + * + * @return int <0 if KO, 0 if not found, >0 if OK */ public function fetch($id, $ref = null, $mode = '') { @@ -772,7 +801,7 @@ class BookKeeping extends CommonObject if (null !== $ref) { $sql .= " AND t.rowid = ".((int) $ref); } else { - $sql .= ' AND t.rowid = '.((int) $id); + $sql .= " AND t.rowid = ".((int) $id); } $resql = $this->db->query($sql); @@ -1278,6 +1307,7 @@ class BookKeeping extends CommonObject */ public function update(User $user, $notrigger = false, $mode = '') { + global $langs; $error = 0; dol_syslog(__METHOD__, LOG_DEBUG); @@ -1338,6 +1368,14 @@ class BookKeeping extends CommonObject $this->piece_num = trim($this->piece_num); } + $result = $this->canModifyBookkeeping($this->id); + if ($result < 0) { + return -1; + } elseif ($result == 0) { + $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod'); + return -1; + } + $this->debit = price2num($this->debit, 'MT'); $this->credit = price2num($this->credit, 'MT'); @@ -1412,11 +1450,17 @@ class BookKeeping extends CommonObject { $error = 0; + $sql_filter = $this->getCanModifyBookkeepingSQL(); + if (!isset($sql_filter)) { + return -1; + } + $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.$mode; $sql .= " SET ".$field." = ".(is_numeric($value) ? ((float) $value) : "'".$this->db->escape($value)."'"); $sql .= " WHERE piece_num = ".((int) $piece_num); + $sql .= $sql_filter; $resql = $this->db->query($sql); @@ -1446,8 +1490,17 @@ class BookKeeping extends CommonObject */ public function delete(User $user, $notrigger = false, $mode = '') { + global $langs; dol_syslog(__METHOD__, LOG_DEBUG); + $result = $this->canModifyBookkeeping($this->id); + if ($result < 0) { + return -1; + } elseif ($result == 0) { + $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod'); + return -1; + } + $error = 0; $this->db->begin(); @@ -1497,10 +1550,16 @@ class BookKeeping extends CommonObject { $this->db->begin(); + $sql_filter = $this->getCanModifyBookkeepingSQL(); + if (!isset($sql_filter)) { + return -1; + } + // first check if line not yet in bookkeeping $sql = "DELETE"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; $sql .= " WHERE import_key = '".$this->db->escape($importkey)."'"; + $sql .= $sql_filter; $resql = $this->db->query($sql); @@ -1537,6 +1596,11 @@ class BookKeeping extends CommonObject return -2; } + $sql_filter = $this->getCanModifyBookkeepingSQL(); + if (!isset($sql_filter)) { + return -1; + } + $this->db->begin(); // Delete record in bookkeeping @@ -1550,6 +1614,7 @@ class BookKeeping extends CommonObject $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features // Exclusion of validated entries at the time of deletion $sql .= " AND date_validated IS NULL"; + $sql .= $sql_filter; // TODO: In a future we must forbid deletion if record is inside a closed fiscal period. @@ -1580,6 +1645,11 @@ class BookKeeping extends CommonObject { global $conf; + $sql_filter = $this->getCanModifyBookkeepingSQL(); + if (!isset($sql_filter)) { + return -1; + } + $this->db->begin(); // first check if line not yet in bookkeeping @@ -1588,6 +1658,7 @@ class BookKeeping extends CommonObject $sql .= " WHERE piece_num = ".(int) $piecenum; $sql .= " AND date_validated IS NULL"; // For security, exclusion of validated entries at the time of deletion $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features + $sql .= $sql_filter; $resql = $this->db->query($sql); @@ -1917,6 +1988,11 @@ class BookKeeping extends CommonObject $error = 0; + $sql_filter = $this->getCanModifyBookkeepingSQL(); + if (!isset($sql_filter)) { + return -1; + } + $this->db->begin(); if ($direction == 0) { @@ -1948,6 +2024,7 @@ class BookKeeping extends CommonObject $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, '.((int) $next_piecenum).", '".$this->db->idate($now)."'"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND numero_compte IS NOT NULL AND entity = ' .((int) $conf->entity); + $sql .= $sql_filter; $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -1986,6 +2063,7 @@ class BookKeeping extends CommonObject $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity); + $sql .= $sql_filter; $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -1996,6 +2074,7 @@ class BookKeeping extends CommonObject if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity); + $sql .= $sql_filter; $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -2175,6 +2254,635 @@ class BookKeeping extends CommonObject return -1; } } + + /** + * Get SQL string for check if the bookkeeping can be modified or deleted ? (cached) + * + * @param string $alias Bookkeeping alias table + * @param bool $force Force reload + * @return string SQL filter + */ + public function getCanModifyBookkeepingSQL($alias = '', $force = false) + { + $alias = trim($alias); + $alias = !empty($alias) && strpos($alias, '.') < 0 ? $alias . "." : $alias; + + if (!isset(self::$can_modify_bookkeeping_sql_cached[$alias]) || $force) { + $result = $this->loadActiveFiscalPeriods($force); + if ($result < 0) { + return null; + } + + $sql_list = array(); + if (is_array(self::$active_fiscal_period_cached)) { + foreach (self::$active_fiscal_period_cached as $fiscal_period) { + $sql_list[] = "('" . $this->db->idate($fiscal_period['date_start']) . "' <= {$alias}doc_date AND {$alias}doc_date <= '" . $this->db->idate($fiscal_period['date_end']) . "')"; + } + } + self::$can_modify_bookkeeping_sql_cached[$alias] = !empty($sql_list) ? ' AND (' . implode(' OR ', $sql_list) . ')' : ''; + } + + return self::$can_modify_bookkeeping_sql_cached[$alias]; + } + + /** + * Is the bookkeeping can be modified or deleted ? + * + * @param int $id Bookkeeping ID + * @return int <0 if KO, == 0 if No, == 1 if Yes + */ + public function canModifyBookkeeping($id) + { + $result = $this->loadActiveFiscalPeriods(); + if ($result < 0) { + return -1; + } + + $bookkeeping = new BookKeeping($this->db); + $result = $bookkeeping->fetch($id); + if ($result <= 0) { + return $result; + } + + if (is_array(self::$active_fiscal_period_cached)) { + foreach (self::$active_fiscal_period_cached as $fiscal_period) { + if ($fiscal_period['date_start'] <= $bookkeeping->doc_date && $bookkeeping->doc_date <= $fiscal_period['date_end']) { + return 1; + } + } + } + + return 0; + } + + /** + * Is the bookkeeping date is valid ? + * + * @param int $date Bookkeeping date + * @return int <0 if KO, == 0 if No, == 1 if Yes + */ + public function validBookkeepingDate($date) + { + $result = $this->loadActiveFiscalPeriods(); + if ($result < 0) { + return -1; + } + + if (is_array(self::$active_fiscal_period_cached)) { + foreach (self::$active_fiscal_period_cached as $fiscal_period) { + if ($fiscal_period['date_start'] <= $date && $date <= $fiscal_period['date_end']) { + return 1; + } + } + } + + return 0; + } + + /** + * Load list of active fiscal period + * + * @param bool $force Force reload + * @return int <0 if KO, >0 if OK + */ + public function loadActiveFiscalPeriods($force = false) + { + global $conf; + + if (!isset(self::$active_fiscal_period_cached) || $force) { + $sql = "SELECT date_start, date_end"; + $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear"; + $sql .= " WHERE entity = " . ((int) $conf->entity); + $sql .= " AND statut = 0"; + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + return -1; + } + + $list = array(); + while ($obj = $this->db->fetch_object($resql)) { + $list[] = array( + 'date_start' => $this->db->jdate($obj->date_start), + 'date_end' => $this->db->jdate($obj->date_end), + ); + } + self::$active_fiscal_period_cached = $list; + } + + return 1; + } + + /** + * Get list of fiscal period + * + * @param string $filter Filter + * @return array|int <0 if KO, Fiscal periods : [[id, date_start, date_end, label], ...] + */ + public function getFiscalPeriods($filter = '') + { + global $conf; + $list = array(); + + $sql = "SELECT rowid, label, date_start, date_end, statut"; + $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear"; + $sql .= " WHERE entity = " . ((int) $conf->entity); + if (!empty($filter)) $sql .= " AND (" . $filter . ')'; + $sql .= $this->db->order('date_start', 'ASC'); + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + return -1; + } + + while ($obj = $this->db->fetch_object($resql)) { + $list[$obj->rowid] = array( + 'id' => $obj->rowid, + 'label' => $obj->label, + 'date_start' => $this->db->jdate($obj->date_start), + 'date_end' => $this->db->jdate($obj->date_end), + 'status' => $obj->statut, + ); + } + + return $list; + } + + /** + * Get list of count by month into the fiscal period + * + * @param int $date_start Date start + * @param int $date_end Date end + * @return array|int <0 if KO, Fiscal periods : [[id, date_start, date_end, label], ...] + */ + public function getCountByMonthForFiscalPeriod($date_start, $date_end) + { + $total = 0; + $list = array(); + + $sql = "SELECT YEAR(b.doc_date) as year"; + for ($i = 1; $i <= 12; $i++) { + $sql .= ", SUM(" . $this->db->ifsql("MONTH(b.doc_date)=" . $i, "1", "0") . ") AS month" . $i; + } + $sql .= ", COUNT(b.rowid) as total"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as b"; + $sql .= " WHERE b.doc_date >= '" . $this->db->idate($date_start) . "'"; + $sql .= " AND b.doc_date <= '" . $this->db->idate($date_end) . "'"; + $sql .= " AND b.entity IN (" . getEntity('bookkeeping', 0) . ")"; // We don't share object for accountancy + + // Get count for each month into the fiscal period + if (getDolGlobalString("ACCOUNTANCY_DISABLE_CLOSURE_LINE_BY_LINE")) { + // TODO Analyse is done by finding record not into a closed period + // Loop on each closed period + $sql .= " AND b.doc_date BETWEEN 0 AND 0"; + } else { + // Analyse closed record using the unitary flag/date on each record + $sql .= " AND date_validated IS NULL"; + } + + $sql .= " GROUP BY YEAR(b.doc_date)"; + $sql .= $this->db->order("year", 'ASC'); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + return -1; + } + + while ($obj = $this->db->fetch_object($resql)) { + $total += (int) $obj->total; + $year_list = array( + 'year' => (int) $obj->year, + 'count' => array(), + 'total' => (int) $obj->total, + ); + for ($i = 1; $i <= 12; $i++) { + $year_list['count'][$i] = (int) $obj->{'month' . $i}; + } + + $list[] = $year_list; + } + + $this->db->free($resql); + + return array( + 'total' => $total, + 'list' => $list, + ); + } + + /** + * Validate all movement between the specified dates + * + * @param int $date_start Date start + * @param int $date_end Date end + * @return int int <0 if KO, >0 if OK + */ + public function validateMovementForFiscalPeriod($date_start, $date_end) + { + global $conf; + + $now = dol_now(); + + // Specify as export : update field date_validated on selected month/year + $sql = " UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping"; + $sql .= " SET date_validated = '" . $this->db->idate($now) . "'"; + $sql .= " WHERE entity = " . ((int) $conf->entity); + $sql .= " AND DATE(doc_date) >= '" . $this->db->idate($date_start) . "'"; + $sql .= " AND DATE(doc_date) <= '" . $this->db->idate($date_end) . "'"; + $sql .= " AND date_validated IS NULL"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + return -1; + } + + return 1; + } + + /** + * Close fiscal period + * + * @param int $fiscal_period_id Fiscal year ID + * @param int $new_fiscal_period_id New fiscal year ID + * @param bool $separate_auxiliary_account Separate auxiliary account + * @param bool $generate_bookkeeping_records Generate closure bookkeeping records + * @return int int <0 if KO, >0 if OK + */ + public function closeFiscalPeriod($fiscal_period_id, $new_fiscal_period_id, $separate_auxiliary_account = false, $generate_bookkeeping_records = true) + { + global $conf, $langs, $user; + + // Current fiscal period + $fiscal_period_id = max(0, $fiscal_period_id); + if (empty($fiscal_period_id)) { + $langs->load('errors'); + $this->errors[] = $langs->trans('ErrorBadParameters'); + return -1; + } + $fiscal_period = new Fiscalyear($this->db); + $result = $fiscal_period->fetch($fiscal_period_id); + if ($result < 0) { + $this->error = $fiscal_period->error; + $this->errors = $fiscal_period->errors; + return -1; + } elseif (empty($fiscal_period->id)) { + $langs->loadLangs(array('errors', 'compta')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $fiscal_period_id . ')'; + return -1; + } + + // New fiscal period + $new_fiscal_period_id = max(0, $new_fiscal_period_id); + if (empty($new_fiscal_period_id)) { + $langs->load('errors'); + $this->errors[] = $langs->trans('ErrorBadParameters'); + return -1; + } + $new_fiscal_period = new Fiscalyear($this->db); + $result = $new_fiscal_period->fetch($new_fiscal_period_id); + if ($result < 0) { + $this->error = $new_fiscal_period->error; + $this->errors = $new_fiscal_period->errors; + return -1; + } elseif (empty($new_fiscal_period->id)) { + $langs->loadLangs(array('errors', 'compta')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $new_fiscal_period_id . ')'; + return -1; + } + + $error = 0; + $this->db->begin(); + + $fiscal_period->statut = Fiscalyear::STATUS_CLOSED; + $fiscal_period->status = Fiscalyear::STATUS_CLOSED; // Actually not used + $result = $fiscal_period->update($user); + if ($result < 0) { + $this->error = $fiscal_period->error; + $this->errors = $fiscal_period->errors; + $error++; + } + + if (!$error && !empty($generate_bookkeeping_records)) { + $journal_id = max(0, getDolGlobalString('ACCOUNTING_CLOSURE_DEFAULT_JOURNAL')); + if (empty($journal_id)) { + $langs->loadLangs(array('errors', 'accountancy')); + $this->errors[] = $langs->trans('ErrorBadParameters') . ' - ' . $langs->trans('Codejournal') . ' (' . $langs->trans('AccountingJournalType9') . ')'; + $error++; + } + + // Fetch journal + if (!$error) { + $journal = new AccountingJournal($this->db); + $result = $journal->fetch($journal_id); + if ($result < 0) { + $this->error = $journal->error; + $this->errors = $journal->errors; + $error++; + } elseif ($result == 0) { + $langs->loadLangs(array('errors', 'accountancy')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('Codejournal') . ' (' . $langs->trans('AccountingJournalType9') . ')'; + $error++; + } + } + + if (!$error) { + $accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT'))), 'strlen'); + $accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT'))), 'strlen'); + + $pcg_type_filter = array(); + $tmp = array_merge($accounting_groups_used_for_balance_sheet_account, $accounting_groups_used_for_income_statement); + foreach ($tmp as $item) { + $pcg_type_filter[] = "'" . $this->db->escape($item) . "'"; + } + + $sql = 'SELECT'; + $sql .= " t.numero_compte,"; + $sql .= " t.label_compte,"; + if ($separate_auxiliary_account) { + $sql .= " t.subledger_account,"; + $sql .= " t.subledger_label,"; + } + $sql .= " aa.pcg_type,"; + $sql .= " (SUM(t.credit) - SUM(t.debit)) as opening_balance"; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'accounting_account as aa ON aa.account_number = t.numero_compte'; + $sql .= ' WHERE t.entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features + $sql .= " AND aa.entity = ". ((int) $conf->entity); + $sql .= ' AND aa.fk_pcg_version IN (SELECT pcg_version FROM '.MAIN_DB_PREFIX.'accounting_system WHERE rowid = '.((int) getDolGlobalInt('CHARTOFACCOUNTS')).')'; + $sql .= ' AND aa.pcg_type IN (' . $this->db->sanitize(implode(',', $pcg_type_filter), 1) . ')'; + $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($fiscal_period->date_start) . "'"; + $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($fiscal_period->date_end) . "'"; + $sql .= ' GROUP BY t.numero_compte, t.label_compte, aa.pcg_type'; + if ($separate_auxiliary_account) { + $sql .= ' ,t.subledger_account, t.subledger_label'; + } + $sql .= $this->db->order("t.numero_compte", "ASC"); + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = 'Error ' . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + + $error++; + } else { + $now = dol_now(); + $income_statement_amount = 0; + while ($obj = $this->db->fetch_object($resql)) { + if (in_array($obj->pcg_type, $accounting_groups_used_for_income_statement)) { + $income_statement_amount += $obj->opening_balance; + } else { + // Insert bookkeeping record for balance sheet account + $mt = $obj->opening_balance; + + $bookkeeping = new BookKeeping($this->db); + $bookkeeping->doc_date = $new_fiscal_period->date_start; + $bookkeeping->date_lim_reglement = ''; + $bookkeeping->doc_ref = $new_fiscal_period->label; + $bookkeeping->date_creation = $now; + $bookkeeping->doc_type = 'closure'; + $bookkeeping->fk_doc = $new_fiscal_period->id; + $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add + $bookkeeping->thirdparty_code = ''; + + if ($separate_auxiliary_account) { + $bookkeeping->subledger_account = $obj->subledger_account; + $bookkeeping->subledger_label = $obj->subledger_label; + } else { + $bookkeeping->subledger_account = ''; + $bookkeeping->subledger_label = ''; + } + + $bookkeeping->numero_compte = $obj->numero_compte; + $bookkeeping->label_compte = $obj->label_compte; + + $bookkeeping->label_operation = $new_fiscal_period->label; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D'; + $bookkeeping->debit = ($mt < 0) ? -$mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $journal->code; + $bookkeeping->journal_label = $langs->transnoentities($journal->label); + $bookkeeping->fk_user_author = $user->id; + $bookkeeping->entity = $conf->entity; + + $result = $bookkeeping->create($user); + if ($result < 0) { + $this->error = $bookkeeping->error; + $this->errors = $bookkeeping->errors; + $error++; + break; + } + } + } + + // Insert bookkeeping record for income statement + if (!$error && $income_statement_amount != 0) { + $mt = $income_statement_amount; + $accountingaccount = new AccountingAccount($this->db); + $accountingaccount->fetch(null, getDolGlobalString($income_statement_amount < 0 ? 'ACCOUNTING_RESULT_LOSS' : 'ACCOUNTING_RESULT_PROFIT'), true); + + $bookkeeping = new BookKeeping($this->db); + $bookkeeping->doc_date = $new_fiscal_period->date_start; + $bookkeeping->date_lim_reglement = ''; + $bookkeeping->doc_ref = $new_fiscal_period->label; + $bookkeeping->date_creation = $now; + $bookkeeping->doc_type = 'closure'; + $bookkeeping->fk_doc = $new_fiscal_period->id; + $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add + $bookkeeping->thirdparty_code = ''; + + if ($separate_auxiliary_account) { + $bookkeeping->subledger_label = ''; + $bookkeeping->subledger_account = $obj->subledger_account; + $bookkeeping->subledger_label = $obj->subledger_label; + } else { + $bookkeeping->subledger_account = ''; + $bookkeeping->subledger_label = ''; + } + + $bookkeeping->numero_compte = $accountingaccount->account_number; + $bookkeeping->label_compte = $accountingaccount->label; + + $bookkeeping->label_operation = $new_fiscal_period->label; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D'; + $bookkeeping->debit = ($mt < 0) ? -$mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $journal->code; + $bookkeeping->journal_label = $langs->transnoentities($journal->label); + $bookkeeping->fk_user_author = $user->id; + $bookkeeping->entity = $conf->entity; + + $result = $bookkeeping->create($user); + if ($result < 0) { + $this->error = $bookkeeping->error; + $this->errors = $bookkeeping->errors; + $error++; + } + } + $this->db->free($resql); + } + } + } + + if ($error) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Insert accounting reversal into the inventory journal of the new fiscal period + * + * @param int $fiscal_period_id Fiscal year ID + * @param int $inventory_journal_id Inventory journal ID + * @param int $new_fiscal_period_id New fiscal year ID + * @param int $date_start Date start + * @param int $date_end Date end + * @return int int <0 if KO, >0 if OK + */ + public function insertAccountingReversal($fiscal_period_id, $inventory_journal_id, $new_fiscal_period_id, $date_start, $date_end) + { + global $conf, $langs, $user; + + // Current fiscal period + $fiscal_period_id = max(0, $fiscal_period_id); + if (empty($fiscal_period_id)) { + $langs->load('errors'); + $this->errors[] = $langs->trans('ErrorBadParameters'); + return -1; + } + $fiscal_period = new Fiscalyear($this->db); + $result = $fiscal_period->fetch($fiscal_period_id); + if ($result < 0) { + $this->error = $fiscal_period->error; + $this->errors = $fiscal_period->errors; + return -1; + } elseif (empty($fiscal_period->id)) { + $langs->loadLangs(array('errors', 'compta')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $fiscal_period_id . ')'; + return -1; + } + + // New fiscal period + $new_fiscal_period_id = max(0, $new_fiscal_period_id); + if (empty($new_fiscal_period_id)) { + $langs->load('errors'); + $this->errors[] = $langs->trans('ErrorBadParameters'); + return -1; + } + $new_fiscal_period = new Fiscalyear($this->db); + $result = $new_fiscal_period->fetch($new_fiscal_period_id); + if ($result < 0) { + $this->error = $new_fiscal_period->error; + $this->errors = $new_fiscal_period->errors; + return -1; + } elseif (empty($new_fiscal_period->id)) { + $langs->loadLangs(array('errors', 'compta')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $new_fiscal_period_id . ')'; + return -1; + } + + // Inventory journal + $inventory_journal_id = max(0, $inventory_journal_id); + if (empty($inventory_journal_id)) { + $langs->load('errors'); + $this->errors[] = $langs->trans('ErrorBadParameters'); + return -1; + } + // Fetch journal + $inventory_journal = new AccountingJournal($this->db); + $result = $inventory_journal->fetch($inventory_journal_id); + if ($result < 0) { + $this->error = $inventory_journal->error; + $this->errors = $inventory_journal->errors; + return -1; + } elseif ($result == 0) { + $langs->loadLangs(array('errors', 'accountancy')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('InventoryJournal'); + return -1; + } + + $error = 0; + $this->db->begin(); + + $sql = 'SELECT t.rowid'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' WHERE t.entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features + $sql .= " AND code_journal = '" . $this->db->escape($inventory_journal->code) . "'"; + $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($date_start) . "'"; + $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($date_end) . "'"; + $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($fiscal_period->date_start) . "'"; + $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($fiscal_period->date_end) . "'"; + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = 'Error ' . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + + $error++; + } else { + $now = dol_now(); + while ($obj = $this->db->fetch_object($resql)) { + $bookkeeping = new BookKeeping($this->db); + $result = $bookkeeping->fetch($obj->rowid); + if ($result < 0) { + $this->error = $inventory_journal->error; + $this->errors = $inventory_journal->errors; + $error++; + break; + } elseif ($result == 0) { + $langs->loadLangs(array('errors', 'accountancy')); + $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('LineId') . ': ' . $obj->rowid; + $error++; + break; + } + + $bookkeeping->id = 0; + $bookkeeping->doc_date = $new_fiscal_period->date_start; + $bookkeeping->doc_ref = $new_fiscal_period->label; + $bookkeeping->date_creation = $now; + $bookkeeping->doc_type = 'accounting_reversal'; + $bookkeeping->fk_doc = $new_fiscal_period->id; + $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add + + $bookkeeping->montant = -$bookkeeping->montant; + $bookkeeping->sens = ($bookkeeping->montant >= 0) ? 'C' : 'D'; + $old_debit = $bookkeeping->debit; + $bookkeeping->debit = $bookkeeping->credit; + $bookkeeping->credit = $old_debit; + + $bookkeeping->fk_user_author = $user->id; + $bookkeeping->entity = $conf->entity; + + $result = $bookkeeping->create($user); + if ($result < 0) { + $this->error = $bookkeeping->error; + $this->errors = $bookkeeping->errors; + $error++; + break; + } + } + $this->db->free($resql); + } + + if ($error) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return 1; + } + } } /** diff --git a/htdocs/accountancy/closure/index.php b/htdocs/accountancy/closure/index.php index 4bddd65ed1c..b9463f93d7d 100644 --- a/htdocs/accountancy/closure/index.php +++ b/htdocs/accountancy/closure/index.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2019-2023 Open-DSI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -32,32 +32,12 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; // Load translation files required by the page $langs->loadLangs(array("compta", "bills", "other", "accountancy")); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'aZ09'); +$fiscal_period_id = GETPOST('fiscal_period_id', 'int'); $validatemonth = GETPOST('validatemonth', 'int'); $validateyear = GETPOST('validateyear', 'int'); -$action = GETPOST('action', 'aZ09'); - -$object = new BookKeeping($db); - -$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); -if (GETPOST("year", 'int')) { - $year_start = GETPOST("year", 'int'); -} else { - $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) { - $year_start--; // If current month is lower that starting fiscal month, we start last year - } -} -$year_end = $year_start + 1; -$month_end = $month_start - 1; -if ($month_end < 1) { - $month_end = 12; - $year_end--; -} -$search_date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start); -$search_date_end = dol_get_last_day($year_end, $month_end); -$year_current = $year_start; - // Security check if (!isModEnabled('accounting')) { accessforbidden(); @@ -69,48 +49,105 @@ if (!$user->hasRight('accounting', 'fiscalyear', 'write')) { accessforbidden(); } +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('accountancyclosure')); + +$object = new BookKeeping($db); + +$now = dol_now(); +$fiscal_periods = $object->getFiscalPeriods(); +if (!is_array($fiscal_periods)) { + setEventMessages($object->error, $object->errors, 'errors'); +} + +$active_fiscal_periods = array(); +$last_fiscal_period = null; +$current_fiscal_period = null; +$next_fiscal_period = null; +$next_active_fiscal_period = null; +if (is_array($fiscal_periods)) { + foreach ($fiscal_periods as $fiscal_period) { + if (empty($fiscal_period['status'])) { + $active_fiscal_periods[] = $fiscal_period; + } + if (isset($current_fiscal_period)) { + if (!isset($next_fiscal_period)) { + $next_fiscal_period = $fiscal_period; + } + if (!isset($next_active_fiscal_period) && empty($fiscal_period['status'])) { + $next_active_fiscal_period = $fiscal_period; + } + } else { + if ($fiscal_period_id == $fiscal_period['id'] || (empty($fiscal_period_id) && $fiscal_period['date_start'] <= $now && $now <= $fiscal_period['date_end'])) { + $current_fiscal_period = $fiscal_period; + } else { + $last_fiscal_period = $fiscal_period; + } + } + } +} + +$accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', $conf->global->ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT)), 'strlen'); +$accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', $conf->global->ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT)), 'strlen'); /* * Actions */ -$now = dol_now(); +$parameters = array('fiscal_periods' => $fiscal_periods, 'last_fiscal_period' => $last_fiscal_period, 'current_fiscal_period' => $current_fiscal_period, 'next_fiscal_period' => $next_fiscal_period); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if ($action == 'validate_movements_confirm' && $user->hasRight('accounting', 'fiscalyear', 'write')) { - $date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); - $date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); +if (empty($reshook)) { + if (isset($current_fiscal_period) && $user->hasRight('accounting', 'fiscalyear', 'write')) { + if ($action == 'confirm_step_1' && $confirm == "yes") { + $date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); + $date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); - $error = 0; + $result = $object->validateMovementForFiscalPeriod($date_start, $date_end); + if ($result > 0) { + setEventMessages($langs->trans("AllMovementsWereRecordedAsValidated"), null, 'mesgs'); - $db->begin(); + header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : '')); + exit; + } else { + setEventMessages($langs->trans("NotAllMovementsCouldBeRecordedAsValidated"), null, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; + } + } elseif ($action == 'confirm_step_2' && $confirm == "yes") { + $new_fiscal_period_id = GETPOST('new_fiscal_period_id', 'int'); + $separate_auxiliary_account = GETPOST('separate_auxiliary_account', 'aZ09'); + $generate_bookkeeping_records = GETPOST('generate_bookkeeping_records', 'aZ09'); - // Specify as export : update field date_validated on selected month/year - $sql = " UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping"; - $sql .= " SET date_validated = '".$db->idate($now)."'"; - $sql .= " WHERE entity = " . ((int) $conf->entity); - $sql .= " AND doc_date >= '" . $db->idate($date_start) . "'"; - $sql .= " AND doc_date <= '" . $db->idate($date_end) . "'"; - $sql .= " AND date_validated IS NULL"; + $result = $object->closeFiscalPeriod($current_fiscal_period['id'], $new_fiscal_period_id, $separate_auxiliary_account, $generate_bookkeeping_records); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("AccountancyClosureCloseSuccessfully"), null, 'mesgs'); - dol_syslog("/accountancy/closure/index.php action=validate_movement_confirm -> Set movements as validated", LOG_DEBUG); - $result = $db->query($sql); - if (!$result) { - $error++; - } + header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : '')); + exit; + } + } elseif ($action == 'confirm_step_3' && $confirm == "yes") { + $inventory_journal_id = GETPOST('inventory_journal_id', 'int'); + $new_fiscal_period_id = GETPOST('new_fiscal_period_id', 'int'); + $date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); + $date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); - if (!$error) { - $db->commit(); + $result = $object->insertAccountingReversal($current_fiscal_period['id'], $inventory_journal_id, $new_fiscal_period_id, $date_start, $date_end); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("AccountancyClosureInsertAccountingReversalSuccessfully"), null, 'mesgs'); - setEventMessages($langs->trans("AllMovementsWereRecordedAsValidated"), null, 'mesgs'); - - header("Location: ".$_SERVER['PHP_SELF']."?year=".$year_start); - exit; - } else { - $db->rollback(); - - setEventMessages($langs->trans("NotAllMovementsCouldBeRecordedAsValidated"), null, 'errors'); - $action = ''; + header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : '')); + exit; + } + } } } @@ -128,120 +165,198 @@ $help_url ='EN:Module_Double_Entry_Accounting'; llxHeader('', $title, $help_url); -if ($action == 'validate_movements') { - $form_question = array(); +$formconfirm = ''; - $month = isset($conf->global->SOCIETE_FISCAL_MONTH_START) ? intval($conf->global->SOCIETE_FISCAL_MONTH_START) : 1; - $date_start = new DateTime(sprintf('%04d-%02d-%02d', $year_start, $month, 1)); - $date_end = new DateTime(sprintf('%04d-%02d-%02d', $year_start, $month, 1)); - $date_end->add(new DateInterval('P1Y')); - $date_end->sub(new DateInterval('P1D')); +if (isset($current_fiscal_period)) { + if ($action == 'step_1') { + $form_question = array(); - $form_question['date_start'] = array( - 'name' => 'date_start', - 'type' => 'date', - 'label' => $langs->trans('DateStart'), - 'value' => $date_start->format('Y-m-d') - ); - $form_question['date_end'] = array( - 'name' => 'date_end', - 'type' => 'date', - 'label' => $langs->trans('DateEnd'), - 'value' => $date_end->format('Y-m-d') - ); + $form_question['date_start'] = array( + 'name' => 'date_start', + 'type' => 'date', + 'label' => $langs->trans('DateStart'), + 'value' => $current_fiscal_period['date_start'] + ); + $form_question['date_end'] = array( + 'name' => 'date_end', + 'type' => 'date', + 'label' => $langs->trans('DateEnd'), + 'value' => $current_fiscal_period['date_end'] + ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?year='.$year_start, $langs->trans('ValidateMovements'), $langs->trans('DescValidateMovements', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'validate_movements_confirm', $form_question, '', 1, 300); - print $formconfirm; -} + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?fiscal_period_id=' . $current_fiscal_period['id'], + $langs->trans('ValidateMovements'), $langs->trans('DescValidateMovements', $langs->transnoentitiesnoconv("RegistrationInAccounting")), + 'confirm_step_1', $form_question, '', 1, 300); + } elseif ($action == 'step_2') { + $form_question = array(); -$textprevyear = ''.img_previous().''; -$textnextyear = ' '.img_next().''; + $fiscal_period_arr = array(); + foreach ($active_fiscal_periods as $info) { + $fiscal_period_arr[$info['id']] = $info['label']; + } + $form_question['new_fiscal_period_id'] = array( + 'name' => 'new_fiscal_period_id', + 'type' => 'select', + 'label' => $langs->trans('AccountancyClosureStep3NewFiscalPeriod'), + 'values' => $fiscal_period_arr, + 'default' => isset($next_active_fiscal_period) ? $next_active_fiscal_period['id'] : '', + ); + $form_question['generate_bookkeeping_records'] = array( + 'name' => 'generate_bookkeeping_records', + 'type' => 'checkbox', + 'label' => $langs->trans('AccountancyClosureGenerateClosureBookkeepingRecords'), + 'value' => 1 + ); + $form_question['separate_auxiliary_account'] = array( + 'name' => 'separate_auxiliary_account', + 'type' => 'checkbox', + 'label' => $langs->trans('AccountancyClosureSeparateAuxiliaryAccounts'), + 'value' => 0 + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?fiscal_period_id=' . $current_fiscal_period['id'], + $langs->trans('AccountancyClosureClose'), $langs->trans('AccountancyClosureConfirmClose'), + 'confirm_step_2', $form_question, '', 1, 300); + } elseif ($action == 'step_3') { + $form_question = array(); -print load_fiche_titre($langs->trans("Closure")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy'); - -print ''.$langs->trans("DescClosure").'
'; -print '
'; - - -$y = $year_current; -if (!getDolGlobalString("ACCOUNTANCY_DISABLE_CLOSURE_LINE_BY_LINE")) { - $buttonvalidate = ''.$langs->trans("ValidateMovements").''; -} else { - $buttonvalidate = ''; -} - -print_barre_liste($langs->trans("OverviewOfMovementsNotValidated"), '', '', '', '', '', '', -1, '', '', 0, $buttonvalidate, '', 0, 1, 0); - -print '
'; -print ''; -for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; - if ($j > 12) { - $j -= 12; + $form_question['inventory_journal_id'] = array( + 'name' => 'inventory_journal_id', + 'type' => 'other', + 'label' => $langs->trans('InventoryJournal'), + 'value' => $formaccounting->select_journal(0, "inventory_journal_id", 8, 1, 0, 0) + ); + $fiscal_period_arr = array(); + foreach ($active_fiscal_periods as $info) { + $fiscal_period_arr[$info['id']] = $info['label']; + } + $form_question['new_fiscal_period_id'] = array( + 'name' => 'new_fiscal_period_id', + 'type' => 'select', + 'label' => $langs->trans('AccountancyClosureStep3NewFiscalPeriod'), + 'values' => $fiscal_period_arr, + 'default' => isset($next_active_fiscal_period) ? $next_active_fiscal_period['id'] : '', + ); + $form_question['date_start'] = array( + 'name' => 'date_start', + 'type' => 'date', + 'label' => $langs->trans('DateStart'), + 'value' => dol_time_plus_duree($current_fiscal_period['date_end'], -1, 'm') + ); + $form_question['date_end'] = array( + 'name' => 'date_end', + 'type' => 'date', + 'label' => $langs->trans('DateEnd'), + 'value' => $current_fiscal_period['date_end'] + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?fiscal_period_id=' . $current_fiscal_period['id'], + $langs->trans('AccountancyClosureAccountingReversal'), $langs->trans('AccountancyClosureConfirmAccountingReversal'), + 'confirm_step_3', $form_question, '', 1, 300 + ); } - print ''; } -print ''; -if (getDolGlobalString("ACCOUNTANCY_DISABLE_CLOSURE_LINE_BY_LINE")) { - $sql = "SELECT COUNT(b.rowid) as detail,"; +// Call Hook formConfirm +$parameters = array('formConfirm' => $formconfirm, 'fiscal_periods' => $fiscal_periods, 'last_fiscal_period' => $last_fiscal_period, 'current_fiscal_period' => $current_fiscal_period, 'next_fiscal_period' => $next_fiscal_period); +$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; +} elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; +} + +// Print form confirm +print $formconfirm; + +$fiscal_period_nav_text = $langs->trans("FiscalPeriod"); +$fiscal_period_nav_text .= ' ' . img_previous() . ''; +$fiscal_period_nav_text .= ' ' . img_next() . ''; +$fiscal_period_nav_text .= ' : ' . (isset($current_fiscal_period) ? $current_fiscal_period['label'] : $langs->trans('ErrorNoFiscalPeriodActiveFound')); +$fiscal_period_nav_text .= ' (' . (isset($current_fiscal_period) ? dol_print_date($current_fiscal_period['date_start'], 'day') . ' - ' . dol_print_date($current_fiscal_period['date_end'], 'day') . ')' : ''); + +print load_fiche_titre($langs->trans("Closure") . " - " . $fiscal_period_nav_text, '', 'title_accountancy'); + +if (isset($current_fiscal_period)) { + // Step 1 + $head = array(); + $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id']; + $head[0][1] = $langs->trans("AccountancyClosureStep1"); + $head[0][2] = 'step1'; + print dol_get_fiche_head($head, 'step1', '', -1, 'title_accountancy'); + + print '' . $langs->trans("AccountancyClosureStep1Desc") . '
'; + + $count_by_month = $object->getCountByMonthForFiscalPeriod($current_fiscal_period['date_start'], $current_fiscal_period['date_end']); + if (!is_array($count_by_month)) { + setEventMessages($object->error, $object->errors, 'errors'); + } + + if (empty($count_by_month['total'])) { + $buttonvalidate = '' . $langs->trans("ValidateMovements") . ''; + } else { + $buttonvalidate = '' . $langs->trans("ValidateMovements") . ''; + } + print_barre_liste($langs->trans("OverviewOfMovementsNotValidated"), '', '', '', '', '', '', -1, '', '', 0, $buttonvalidate, '', 0, 1, 0); + + print '
'; + print '
'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).''.$langs->trans("Total").'
'; + + print ''; + $nb_years = is_array($count_by_month['list']) ? count($count_by_month['list']) : 0; + if ($nb_years > 1) print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; - if ($j > 12) { - $j -= 12; - } - $sql .= " SUM(".$db->ifsql("MONTH(b.doc_date)=".$j, "1", "0").") AS month".str_pad($j, 2, "0", STR_PAD_LEFT).","; + print ''; } - $sql .= " COUNT(b.rowid) as total"; - $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; - $sql .= " WHERE b.doc_date >= '".$db->idate($search_date_start)."'"; - $sql .= " AND b.doc_date <= '".$db->idate($search_date_end)."'"; - $sql .= " AND b.entity IN (".getEntity('bookkeeping', 0).")"; // We don't share object for accountancy - // lines not inside an existing fiscal period - $sql .= " AND NOT EXISTS (SELECT rowid FROM ".MAIN_DB_PREFIX."accounting_fiscalyear as af"; - $sql .= " WHERE b.doc_date >= af.date_start AND (b.doc_date <= af.date_end or af.date_end IS NULL)"; - $sql .= " AND af.statut = ".((int) Fiscalyear::STATUS_CLOSED); - $sql .= ")"; -} else { - // Analyse closed record using the unitary flag/date on each record - $sql = "SELECT COUNT(b.rowid) as detail,"; - for ($i = 1; $i <= 12; $i++) { - $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; - if ($j > 12) { - $j -= 12; + print ''; + print ''; + + if (is_array($count_by_month['list'])) { + foreach ($count_by_month['list'] as $info) { + print ''; + if ($nb_years > 1) print ''; + for ($i = 1; $i <= 12; $i++) { + print ''; + } + print ''; } - $sql .= " SUM(".$db->ifsql("MONTH(b.doc_date)=".$j, "1", "0").") AS month".str_pad($j, 2, "0", STR_PAD_LEFT).","; } - $sql .= " COUNT(b.rowid) as total"; - $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; - $sql .= " WHERE b.doc_date >= '".$db->idate($search_date_start)."'"; - $sql .= " AND b.doc_date <= '".$db->idate($search_date_end)."'"; - $sql .= " AND b.entity IN (".getEntity('bookkeeping', 0).")"; // We don't share object for accountancy - $sql .= " AND date_validated IS NULL"; + + print "
' . $langs->trans("Year") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . $info['year'] . '' . ((int) $info['count'][$i]) . '' . $info['total'] . '
\n"; + print '
'; + + // Step 2 + $head = array(); + $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id']; + $head[0][1] = $langs->trans("AccountancyClosureStep2"); + $head[0][2] = 'step2'; + print dol_get_fiche_head($head, 'step2', '', -1, 'title_accountancy'); + + // print '' . $langs->trans("AccountancyClosureStep2Desc") . '
'; + + if (empty($count_by_month['total']) && empty($current_fiscal_period['status'])) { + $button = '' . $langs->trans("AccountancyClosureClose") . ''; + } else { + $button = '' . $langs->trans("AccountancyClosureClose") . ''; + } + print_barre_liste('', '', '', '', '', '', '', -1, '', '', 0, $button, '', 0, 1, 0); + + // Step 3 + $head = array(); + $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id']; + $head[0][1] = $langs->trans("AccountancyClosureStep3"); + $head[0][2] = 'step3'; + print dol_get_fiche_head($head, 'step3', '', -1, 'title_accountancy'); + + // print '' . $langs->trans("AccountancyClosureStep3Desc") . '
'; + + if (empty($current_fiscal_period['status'])) { + $button = '' . $langs->trans("AccountancyClosureAccountingReversal") . ''; + } else { + $button = '' . $langs->trans("AccountancyClosureAccountingReversal") . ''; + } + print_barre_liste('', '', '', '', '', '', '', -1, '', '', 0, $button, '', 0, 1, 0); } -dol_syslog('htdocs/accountancy/closure/index.php', LOG_DEBUG); -$resql = $db->query($sql); -if ($resql) { - $num = $db->num_rows($resql); - - while ($row = $db->fetch_row($resql)) { - print ''; - for ($i = 1; $i <= 12; $i++) { - print ''.$row[$i].''; - } - print ''.$row[13].''; - print ''; - } - - $db->free($resql); -} else { - print $db->lasterror(); // Show last sql error -} -print "\n"; -print ''; - // End of page llxFooter(); $db->close(); diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index 35fcbcd23c8..bbbaad4e2ef 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -277,7 +277,7 @@ if ($result) { ); // Variable bookkeeping ($obj->rowid is Bank Id) - $tabpay[$obj->rowid]["date"] = $obj->do; + $tabpay[$obj->rowid]["date"] = $db->jdate($obj->do); $tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; // CHQ, VIR, LIQ, CB, ... $tabpay[$obj->rowid]["ref"] = $obj->label; // By default. Not unique. May be changed later $tabpay[$obj->rowid]["fk_bank"] = $obj->rowid; @@ -599,7 +599,7 @@ if (!$error && $action == 'writebookkeeping') { $error = 0; foreach ($tabpay as $key => $val) { // $key is rowid into llx_bank - $date = dol_print_date($db->jdate($val["date"]), 'day'); + $date = dol_print_date($val["date"], 'day'); $ref = getSourceDocRef($val, $tabtype[$key]); @@ -928,7 +928,7 @@ if ($action == 'exportcsv') { // ISO and not UTF8 ! print "\n"; foreach ($tabpay as $key => $val) { - $date = dol_print_date($db->jdate($val["date"]), 'day'); + $date = dol_print_date($val["date"], 'day'); $ref = getSourceDocRef($val, $tabtype[$key]); @@ -1152,7 +1152,7 @@ if (empty($action) || $action == 'view') { $r = ''; foreach ($tabpay as $key => $val) { // $key is rowid in llx_bank - $date = dol_print_date($db->jdate($val["date"]), 'day'); + $date = dol_print_date($val["date"], 'day'); $ref = getSourceDocRef($val, $tabtype[$key]); diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index fd415be3097..879edcd0fe5 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -310,10 +310,10 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2464__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_product', 2451__+MAX_llx_menu__, '/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuProductsAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 55, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2465__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_export', 2451__+MAX_llx_menu__, '/accountancy/admin/export.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'ExportOptions', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 60, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin" && $conf->global->MAIN_FEATURES_LEVEL > 1', __HANDLER__, 'left', 2466__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_closure', 2451__+MAX_llx_menu__, '/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuClosureAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 70, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2466__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_closure', 2451__+MAX_llx_menu__, '/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuClosureAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 70, __ENTITY__); -- Accounting period -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin" && $conf->global->MAIN_FEATURES_LEVEL > 0', __HANDLER__, 'left', 2450__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_period', 2451__+MAX_llx_menu__, '/accountancy/admin/fiscalyear.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'FiscalPeriod', 1, 'admin', '', '', 2, 80, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2450__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_period', 2451__+MAX_llx_menu__, '/accountancy/admin/fiscalyear.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'FiscalPeriod', 1, 'admin', '', '', 2, 80, __ENTITY__); -- Binding insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && isModEnabled("facture") && empty($conf->global->ACCOUNTING_DISABLE_BINDING_ON_SALES)', __HANDLER__, 'left', 2401__+MAX_llx_menu__, 'accountancy', 'accountancy_dispatch_customer', 2400__+MAX_llx_menu__, '/accountancy/customer/index.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_customer', 'CustomersVentilation', 1, 'accountancy', '$user->hasRight("accounting","bind","write")', '', 0, 2, __ENTITY__); diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 251eb5a548c..4557075657f 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1653,10 +1653,8 @@ function get_left_menu_accountancy($mainmenu, &$newmenu, $usemenuhider = 1, $lef global $mysoc; $newmenu->add("/accountancy/admin/index.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("General"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_general', 10); - // Fiscal year - Not really yet used. In a future will lock some periods. - if ($conf->global->MAIN_FEATURES_LEVEL > 1) { - $newmenu->add("/accountancy/admin/fiscalyear.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("FiscalPeriod"), 1, $user->hasRight('accounting', 'fiscalyear', 'write'), '', $mainmenu, 'fiscalyear', 20); - } + // Fiscal year + $newmenu->add("/accountancy/admin/fiscalyear.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("FiscalPeriod"), 1, $user->hasRight('accounting', 'fiscalyear', 'write'), '', $mainmenu, 'fiscalyear', 20); $newmenu->add("/accountancy/admin/journals_list.php?id=35&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingJournals"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_journal', 30); $newmenu->add("/accountancy/admin/accountmodel.php?id=31&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("Pcg_version"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_chartmodel', 40); @@ -1676,9 +1674,7 @@ function get_left_menu_accountancy($mainmenu, &$newmenu, $usemenuhider = 1, $lef $newmenu->add("/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuExpenseReportAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_default', 100); } $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_product', 110); - if ($conf->global->MAIN_FEATURES_LEVEL > 1) { - $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 120); - } + $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 120); $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingCategory"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_chart', 125); $newmenu->add("/accountancy/admin/export.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("ExportOptions"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_export', 130); } diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 2aeec52f8f1..c1b8cd1592c 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -184,6 +184,8 @@ ACCOUNTING_SOCIAL_JOURNAL=Social journal ACCOUNTING_RESULT_PROFIT=Result accounting account (Profit) ACCOUNTING_RESULT_LOSS=Result accounting account (Loss) ACCOUNTING_CLOSURE_DEFAULT_JOURNAL=Journal of closure +ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT=Accounting groups used for the balance sheet account (separate by comma) +ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT=Accounting groups used for the income statement (separate by comma) ACCOUNTING_ACCOUNT_TRANSFER_CASH=Account (from the Chart Of Account) to be used as the account for transitional bank transfers TransitionalAccount=Transitional bank transfer account @@ -296,8 +298,8 @@ DescVentilExpenseReportMore=If you setup accounting account on type of expense r DescVentilDoneExpenseReport=Consult here the list of the lines of expenses reports and their fees accounting account Closure=Annual closure -DescClosure=Consult here the number of movements by month not yet validated & locked -OverviewOfMovementsNotValidated=Number of movements not validated and locked +AccountancyClosureStep1Desc=Consult here the number of movements by month not yet validated & locked +OverviewOfMovementsNotValidated=Overview of movements not validated and locked AllMovementsWereRecordedAsValidated=All movements were recorded as validated and locked NotAllMovementsCouldBeRecordedAsValidated=Not all movements could be recorded as validated and locked ValidateMovements=Validate and lock movements @@ -441,12 +443,26 @@ AccountancyNoUnletteringModified=No unreconcile modified AccountancyOneUnletteringModifiedSuccessfully=One unreconcile successfully modified AccountancyUnletteringModifiedSuccessfully=%s unreconcile successfully modified +## Closure +AccountancyClosureStep1=Step 1 : Validate and lock movements +AccountancyClosureStep2=Step 2 : Close fiscal period +AccountancyClosureStep3=Step 3 : Extract entries (Optional) +AccountancyClosureClose=Close fiscal period +AccountancyClosureAccountingReversal=Extract entries +AccountancyClosureStep3NewFiscalPeriod=Next fiscal period +AccountancyClosureGenerateClosureBookkeepingRecords=Generate "has-new" entry on the next fiscal period +AccountancyClosureSeparateAuxiliaryAccounts=When generating the "has-new" entry, detail the sub-ledger accounts +AccountancyClosureCloseSuccessfully=Fiscal period has been closed successfully +AccountancyClosureInsertAccountingReversalSuccessfully=Bookkeeping records has been inserted successfully + ## Confirm box ConfirmMassUnletteringAuto=Bulk auto unreconcile confirmation ConfirmMassUnletteringManual=Bulk manual unreconcile confirmation ConfirmMassUnletteringQuestion=Are you sure you want to unreconcile the %s selected record(s)? ConfirmMassDeleteBookkeepingWriting=Bulk Delete confirmation ConfirmMassDeleteBookkeepingWritingQuestion=This will delete the transaction from the accounting (all line entries related to the same transaction will be deleted). Are you sure you want to delete the %s selected entries? +AccountancyClosureConfirmClose=Are you sure you want to close the current fiscal period ? You understand that closing the fiscal period is an irreversible action and will permanently block any modification or deletion of entries over this period. +AccountancyClosureConfirmAccountingReversal=Are you sure you want to accounting reversal ? ## Error SomeMandatoryStepsOfSetupWereNotDone=Some mandatory steps of setup was not done, please complete them @@ -465,6 +481,8 @@ AccountancyErrorMismatchBalanceAmount=The balance (%s) is not equal to 0 AccountancyErrorLetteringBookkeeping=Errors have occurred concerning the transactions: %s ErrorAccountNumberAlreadyExists=The accounting number %s already exists ErrorArchiveAddFile=Can't put "%s" file in archive +ErrorNoFiscalPeriodActiveFound=No fiscal period active found +ErrorBookkeepingDocDateNotOnActiveFiscalPeriod=The bookkeeping doc date is not on active fiscal period ## Import ImportAccountingEntries=Accounting entries