From a94c77edd04695ec027fccf672be92a0fa87b22e Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Tue, 24 Feb 2026 18:57:35 +0100 Subject: [PATCH] NEW Accountancy - Multi reports system (#37248) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CSS * CSS * Fix phpunit * More legal info * CI * Fix CI * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Protect module * Add currency * CSS * WIP LNE * Fix navigation * cs * Debug registration process * Debug setup navigation * CI * CI * Factorize code * Fix CI * Fix CI * Fix CI * CI * CI * CI * CI * Disable phan on v23 * CI * CI * FIX: missing include for blockedlog lib (#37165) * Debug CI * fix ternary always true (#37161) * fix ternary always true * Update requests.php * Update registration.php --------- Co-authored-by: Laurent Destailleur * CI * FIX: missing include for blockedlog lib (#37165) * FIX #37134 Use json_encode for IMAP search logging in EmailCollector (#37135) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch) as each line becomes a separate log entry. Using json_encode() produces single-line structured output that works correctly with all log aggregation tools. Co-authored-by: Laurent Destailleur * Populate syslog with placeholder (#37163) Co-authored-by: Laurent Destailleur * Doc * datamodel for user change password next time (#37155) * Qual: Update phan baseline (#37172) * Fix typo in file path (#37160) Co-authored-by: Laurent Destailleur * Fix phpunit * Complete call to setStatus so we have a trigy as 4th parameter (help to fix the #37129) * FIX Product - Warning on admin (#37157) Co-authored-by: Laurent Destailleur * FIX Product - Warning on admin + CSS (#37158) * FIX Product - Warning on admin * CSS --------- Co-authored-by: Laurent Destailleur * CI * CI * CI * Avoid error if include fails * More functions in blacklist (even if nw we use the whitelist by default) * #37166 [SQL] add: email template for ticket admin creation (#37182) * Replace var_export with new function formatLogObject (#37178) * FIX BOM - Class product missing, column offset and information recording (form/input overlap) in admin (#37177) * FIX BOM - Class product missing in admin * Fix column offset and information recording (form/input overlap) * ci * ci * FIX Intracommreport - Warning & link problem on tab (#37176) * FIX Bank transfer admin - Warning & save 0 on constant PAYMENTBYBANKTRANSFER_ADDDAYS (#37175) * Look and feel v24 * Update default time handling in index.php (#37150) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix CI * Add template in migration * fix phpdoc comment (#37184) * fix phpdoc comment * fix phpdoc comment --------- Co-authored-by: Laurent Destailleur * CI * Fix phpstan * Replace var_export by formatLogObject (continued) (#37188) Co-authored-by: Laurent Destailleur * Debug amount suggested on membership public form * Issue 36923 Fix session title handling in survey creation (#37105) * Issue 36923 Fix session title handling in survey creation * Change input field to use id attribute for title --------- Co-authored-by: Laurent Destailleur * fix phpstan errors blocking action baseline (#37189) * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * refresh baseline * QUAL Replace var_export() with json_encode() in dol_syslog() calls (#37138) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch, Graylog) as each line becomes a separate log entry. json_encode() produces single-line structured output that works correctly with all log aggregation tools. This pattern is already used elsewhere in Dolibarr (accountancy, install modules). Files changed: - core/class/commoninvoice.class.php (payment intent logging) - core/class/commonobject.class.php (payment terms logging) - core/modules/mailings/advthirdparties.modules.php (mailing targets) - core/modules/oauth/google_oauthcallback.php (userinfo logging) - core/modules/oauth/generic_oauthcallback.php (userinfo logging) - public/payment/newpayment.php (GET/POST debug logging) - public/payment/paymentok.php (payment tag logging) - public/stripe/ipn.php (Stripe event data logging) - paypal/lib/paypal.lib.php (PayPal response logging) - api/index.php (API debug logging) - stripe/class/stripe.class.php (payment/setup intent logging) Co-authored-by: f-hoedl Co-authored-by: Laurent Destailleur * Fix CI * CI * Check if upload_max_filesize is not empty * clean code * Debug v23 * CI * Fix #33521 VAT total false (#36990) * - Fix #33521 VAT total false - Fix some warnings - Fix : delete $this->vat_rate * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php --------- Co-authored-by: vmaury Co-authored-by: Laurent Destailleur * NEW #25829 Automatically send the invoice generated from a template (#36967) * Update DB * ADD email template * Ajout d'une clé de trad * Ajout des traductions * Suppression des traductions, sauf en_US * Add flag auto send * Modif form + cron auto send * Suppression auto_send * correction loopError * ajout du selected au model de mail * Prise en compte default model * Fix pre-commit * ménage * precommit * Correction Phan * Correction Phan * Correction, double cal du trigger --------- Co-authored-by: Laurent Destailleur * Develop force user change pass userclass (#37174) * datamodel for user change password next time * add force_pass_change in user object * Initialize force_pass_change to 0 --------- Co-authored-by: Laurent Destailleur * Another step for #37171 * Qual: Partial phan run on PR's, complete run on integration branches (#37186) * Qual: Partial phan run on PR's, complete on main # Qual: Partial phan run on PR's, complete on main The selection is based on the branch name. To run a complete phan run in a PR, the branch name of the PR must include phan_full. This can help to fix remaining phan issue before re-integrating to the develop branch. * qual: Update workflow and pre-commit configurations - Enable phan workflow by uncommenting the relevant lines - Update actionlint version to v1.7.10 - Add manual stage to actionlint hook in pre-commit-config.yaml * qual: Update Phan analysis conditions The conditions for running Phan analysis have been updated to include an additional check for branches containing 'phan_full'. * qual: Update Phan workflow - Replace github.event.ref with github.ref_name - Add FILE_CHANGE_LIST environment variable for better file handling - Update file list creation and usage in the workflow * qual: Update Phan workflow conditions Fix the branch reference (head_ref in PR, ref_name otherwise) * Add step for debug information * Remove debug step * Fix: Missing initialisations members/new.php Following a suppression of assignments, the variables disabledphy and disabledmor were undefined. * fix: Update budget selection dropdown arguments in member creation form Correct the arguments in the member creation form. * qual: Add cs2pr to phan workflow - Add cs2pr to the tools list in the phan workflow - Change the output mode of phan to checkstyle - Add a step to add results to PR as Github notices - Add a step to provide phan log as artifact * qual: Update Phan workflow to use environment variable for file list The change fixes the Phan workflow to use the environment variable `$FILE_CHANGED_LIST` to clear the file --------- Co-authored-by: Laurent Destailleur * Fix phan * Fix phan * Merge branch '23.0' of git@github.com:Dolibarr/dolibarr.git into 23.0 * Doc * Qual: Fix ambigious redirect error on Phan workflow (#37200) # Qual: Fix ambigious redirect error on Phan workflow Rewrote the shell command that is supposed to suppress a file contents but is flagged by the environment. * PHPStan > Update baseline (#37197) Co-authored-by: Dolibot * Typo fix (#37195) * Debug v23 - filters on agenda pages * css * css * css * qual: Update PHPStan workflow to run on all files in integration (#37207) The PHPStan workflow has been updated to run on all files in integration branches. * Fix CI * Add hook in isEditable() * Debug v23 * CLOSE #37190 ODT Templates for thirdparties - Birthday is returned in epoch format (#37198) Co-authored-by: Laurent Destailleur * fix: Remove HTML from accounting menu tooltips in eldy theme (#37203) Co-authored-by: Laurent Destailleur * Qual: Update spelling (#37199) * Qual: Update spelling for pre-select variants # Qual: Update spelling for pre-select variants In English, preselect is without the hyphen. Update text and made some translations related to preselect. * Qual: Update composant to component and/or adequate translation. # Qual: Update composant to component and/or adequate translation. "Composant(s)" was mostly referenced in french file/class comments. Updated * Qual: Fix misspellings related to "criteria" # Qual: Fix misspellings related to "criteria" * Qual: Fix produt misspellings # Qual: Fix produt misspellings Change 'produt' to 'product'. * Qual: Update French comments with "composants" #Qual: Update French comments with "composants" - Translating French comments to English (avoid codespell notice) * Qual: Fixed typo 'bad practive' to 'bad practice' # Qual: Fixed typo 'bad practive' to 'bad practice' * Qual: Update phan.yml to exclude specific files from analysis - Added file exclusion pattern to match phan configuration - Added check for empty file list to avoid unnecessary phan execution * Qual: Update file filtering in phan.yml workflow The change updates the file filtering process in the phan.yml workflow to correctly redirect the output of the grep command to a temporary file. * Qual: Ignore $systemfunction always exists --------- Co-authored-by: Laurent Destailleur * Error handling methods for commonobject (#37201) * Error handling methods for commonobject (#37201) * NEW Can request and force user to change its password (#37196) * force user to change password : redirect to user card on login * force user to change password : redirect to user card on login * redirect to a dedicated page * bad old idea : self change passwd on user card + edit mode and rights: it makes a hole on security check * only apply on dolibarr auth mode context * only on dolibarr auth mode context * Fix force_pass_change SQL assignment logic --------- Co-authored-by: Laurent Destailleur * Doc * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Prepare 23.0 * Qual: Ignore exit code from `grep -v` in phan flow (#37213) # Qual: Ignore exit code from `grep -v` in phan flow `grep -v` returns 1 when the resulting filtered list is empty and would stop the execution. This is fixed with `|| true` to have a final exit code that is 0. * WIP LNE * Debug v23 * Debug v23 * WIP LNE * FIX Bad header name * Fix CSP for ping * Compatibility with multicompany * Debug * Fix include * FIX phpdoc on createFixedAmountDiscount() (#37212) * FIX phpdoc on createFixedAmountDiscount * FIX phpdoc --------- Co-authored-by: Laurent Destailleur * Fix in card css modal display (#36569) * Fix display of cards in a modal * fix php stan * fix php stan * Try a change to force CI --------- Co-authored-by: Laurent Destailleur * NEW Accountancy - Multi reports system * Button style * CI * CI * CI * CI * CI * CI * CI * More complete data on pings. * Debug v23 * Debug initdemo * Debug initdemo * Debug initdemo * Debug v23 * Update initdemo * Update initdemo * Cleaner GET call * Add id of perm in url * Init demo for v24 * Fix translation of "various payment" (not english, not pro) with the term used in english to mean "Opérations diverses (OD)" * Sync transifex * CSS * Trans * Doc * Trans * Debug v23 * Debug v23 * Trans * Debug v24 * Debug v23 * Debug v23 * WIP * Debug v23 * Debug v23 * Debug v24 * Work on LNE * WIP LNE * Debug v24 * Doc * Translation * Sync transifex * Debug * Debug * Debug * Responsive * Dev control archive integrity * Debug * Update supplier_proposal.lang (#37238) * add company name on dropdown contract list (#37245) * Clean dump file * Fix CI * FIX #37246 Modifying resteapayer calculation for credit note (#37247) * Add 'type' parameter to completeTabsHead hook (#37235) * #37257 FIX for piesemicircle (#37258) * Fix #37227 Fix #37233 * Fix #37227 Fix #37233 * QUAL French comment in English (#37225) * Edit label of $fields * QUAL French comment in English * Bump actions/upload-artifact from 4 to 6 (#37250) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 6. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v4...v6) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Laurent Destailleur * UI/UX : Transfert feedback css from experimental to core (#37226) * Transfert feedback css from experimental to core * fix php phan * Fix phan * Fix phan * Fix phan * Missing label * Debug * Add method to chech if invoice can be replaced * Fix return * Debug v24 * Fix CI * fix commoninvoice.class.php (#37267) * fix commoninvoice.class.php * Update commoninvoice.class.php * CI * CI * Debug v23 * CI * Fix CI * Debug v23 * clean code pdf.lib.php (#37265) * clean code pdf.lib.php * Update pdf.lib.php * Update pdf.lib.php --------- Co-authored-by: Laurent Destailleur * FixCI * FIX: linktoref should be able to receive more than 255 chars (#37262) Co-authored-by: Laurent Destailleur --------- Signed-off-by: dependabot[bot] Co-authored-by: Laurent Destailleur Co-authored-by: Laurent Destailleur Co-authored-by: Yamil Esteban Garcia <120027058+developmentOYR@users.noreply.github.com> Co-authored-by: Noé Cendrier <81741011+altairis-noe@users.noreply.github.com> Co-authored-by: Frédéric FRANCE Co-authored-by: minimexat Co-authored-by: hansemschnokeloch Co-authored-by: Eric - CAP-REL <1468823+rycks@users.noreply.github.com> Co-authored-by: MDW Co-authored-by: evarisk-kilyan Co-authored-by: Vanyo Co-authored-by: jeremydassaud <49372108+jeremydassaud@users.noreply.github.com> Co-authored-by: f-hoedl Co-authored-by: Vincent Maury Co-authored-by: vmaury Co-authored-by: Vincent Penel Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Dolibot Co-authored-by: Joris Le Blansch Co-authored-by: intelliking Co-authored-by: Benjamin Falière <121813548+BenjaminFlr@users.noreply.github.com> Co-authored-by: John BOTELLA <68917336+thersane-john@users.noreply.github.com> Co-authored-by: Charlène Benke <1179011+defrance@users.noreply.github.com> Co-authored-by: demiton Co-authored-by: Jyhere Co-authored-by: Delthair <41671350+Delthair@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- htdocs/accountancy/admin/account.php | 31 +- htdocs/accountancy/admin/categories.php | 495 +++++++++++++----- htdocs/accountancy/admin/categories_list.php | 140 ++++- .../class/accountancycategory.class.php | 330 +++++++++++- .../class/accountancyreport.class.php | 2 +- htdocs/core/menus/init_menu_auguria.sql | 2 +- htdocs/core/menus/standard/eldy.lib.php | 8 +- htdocs/langs/en_US/accountancy.lang | 18 + 8 files changed, 854 insertions(+), 172 deletions(-) diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 24448b2ad43..ed9d6c7eee4 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -259,6 +259,9 @@ if ($action == 'delete') { $pcgver = getDolGlobalInt('CHARTOFACCOUNTS'); $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.account_number, aa.account_parent, aa.label, aa.labelshort, aa.fk_accounting_category,"; +if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + $sql .= " (SELECT COUNT(*) FROM ".MAIN_DB_PREFIX."accounting_category_account aca WHERE aca.fk_accounting_account = aa.rowid) as nb_categories,"; +} $sql .= " aa.reconcilable, aa.centralized, aa.active, aa.import_key,"; $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; @@ -761,9 +764,31 @@ if ($resql) { } // Custom accounts if (!empty($arrayfields['categories']['checked'])) { - print ''; - // TODO Get all custom groups labels the account is in - print dol_escape_htmltag($obj->fk_accounting_category); + print ''; + + if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + // Multi report system + if (!empty($obj->nb_categories)) { + $accountingcategory_temp = new AccountancyCategory($db); + $categories = $accountingcategory_temp->getCategoriesForAccount($obj->rowid); + + $categoriesLabels = array(); + foreach ($categories as $cat) { + $categoriesLabels[] = ''.dol_escape_htmltag($cat['code']).''; + } + print implode(' ', $categoriesLabels); + } else { + print '-'; + } + } else { + // OLD SYSTEM: One-to-many + if (!empty($obj->fk_accounting_category)) { + print dol_escape_htmltag($obj->fk_accounting_category); + } else { + print '-'; + } + } + print "\n"; if (!$i) { $totalarray['nbfield']++; diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index 1de47c4756c..163efdfb22c 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -1,9 +1,9 @@ - * Copyright (C) 2017-2024 Alexandre Spangaro - * Copyright (C) 2022 Laurent Destailleur - * Copyright (C) 2024 Frédéric France - * Copyright (C) 2024-2025 MDW +/* Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2026 Alexandre Spangaro + * Copyright (C) 2014-2015 Florian Henry + * Copyright (C) 2019 Frédéric France + * Copyright (C) 2024-2026 MDW * * 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 @@ -27,9 +27,6 @@ // Load Dolibarr environment require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; /** * @var Conf $conf @@ -39,187 +36,399 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; * @var User $user */ +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; + $error = 0; // Load translation files required by the page -$langs->loadLangs(array("bills", "accountancy", "compta")); +$langs->loadLangs(array("accountancy", "admin", "bills", "compta")); -$id = GETPOSTINT('id'); -$cancel = GETPOST('cancel', 'alpha'); $action = GETPOST('action', 'aZ09'); -$cat_id = GETPOSTINT('account_category'); -$selectcpt = GETPOST('cpt_bk', 'array'); -$cpt_id = GETPOSTINT('cptid'); - -if ($cat_id == 0) { - $cat_id = null; -} - -// Load variable for pagination -$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'aZ09comma'); -$sortorder = GETPOST('sortorder', 'aZ09comma'); -$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page"); -if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { - // If $page is not defined, or '' or -1 or if we click on clear filters - $page = 0; -} -$offset = $limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; - -if (empty($sortfield)) { - $sortfield = 'account_number'; -} -if (empty($sortorder)) { - $sortorder = 'ASC'; +$confirm = GETPOST('confirm', 'alpha'); +$id = GETPOSTINT('id'); +$catid = GETPOSTINT('catid'); // Alternative parameter name for consistency +if (empty($id) && !empty($catid)) { + $id = $catid; } +$account_id = GETPOSTINT('account_id'); +$cpt_id = GETPOSTINT('cpt'); // For compatibility with old system // Security check if (!$user->hasRight('accounting', 'chartofaccount')) { accessforbidden(); } +// Initialize objects $accountingcategory = new AccountancyCategory($db); +$form = new Form($db); +$formaccounting = new FormAccounting($db); +// Load category +if ($id > 0) { + $result = $accountingcategory->fetch($id); + if ($result < 0) { + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); + } +} + +// Parameters for list (new system only) +$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page"); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} +$offset = $limit * $page; + +// Search filters (new system only) +$search_account = GETPOST('search_account', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); + +if (empty($sortfield)) { + $sortfield = "aa.account_number"; +} +if (empty($sortorder)) { + $sortorder = "ASC"; +} + +// Use new multi report system +$useNewSystem = (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')); /* * Actions */ -// If we add account -if (!empty($selectcpt)) { - $cpts = array(); - foreach ($selectcpt as $selectedoption) { - if (!array_key_exists($selectedoption, $cpts)) { - $cpts[$selectedoption] = "'".$selectedoption."'"; - } +if ($useNewSystem) { + // Remove filter + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $search_account = ''; + $search_label = ''; } - $return = $accountingcategory->updateAccAcc((int) $cat_id, $cpts); + // Add account to category + if ($action == 'add_account' && !empty($account_id)) { + $result = $accountingcategory->addAccountToCategory($account_id); - if ($return < 0) { - setEventMessages($langs->trans('errors'), $accountingcategory->errors, 'errors'); - } else { - setEventMessages($langs->trans('RecordModifiedSuccessfully'), null, 'mesgs'); - } -} - -if ($action == 'delete') { - if ($cpt_id) { - if ($accountingcategory->deleteCptCat($cpt_id)) { - setEventMessages($langs->trans('AccountRemovedFromGroup'), null, 'mesgs'); + if ($result > 0) { + setEventMessages($langs->trans("AccountAddedToCategory"), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } elseif ($result == 0) { + setEventMessages($langs->trans("AccountAlreadyInCategory"), null, 'warnings'); } else { - setEventMessages($langs->trans('errors'), null, 'errors'); + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); + } + } + + // Remove account from category + if ($action == 'confirm_delete' && $confirm == 'yes' && !empty($account_id)) { + $result = $accountingcategory->deleteAccountFromCategory($account_id); + + if ($result > 0) { + setEventMessages($langs->trans("AccountRemovedFromCategory"), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); + } + } + + // Add multiple accounts + if ($action == 'add_multiple' && GETPOST('accounts_to_add', 'array')) { + $accounts_to_add = GETPOST('accounts_to_add', 'array'); + + $result = $accountingcategory->addMultipleAccountsToCategory($accounts_to_add); + + if ($result > 0) { + setEventMessages($langs->trans("XAccountsAdded", $result), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } elseif ($result < 0) { + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); + } else { + setEventMessages($langs->trans("NoAccountAdded"), null, 'warnings'); + } + } + + // Remove all accounts + if ($action == 'confirm_remove_all' && $confirm == 'yes') { + $result = $accountingcategory->removeAllAccountsFromCategory(); + + if ($result >= 0) { + setEventMessages($langs->trans("XAccountsRemoved", $result), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); + } + } +} else { + // OLD SYSTEM: One-to-many via fk_accounting_category field + if ($action == 'clean') { + $result = $accountingcategory->deleteCptCat($cpt_id); + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } else { + setEventMessages($accountingcategory->error, $accountingcategory->errors, 'errors'); } } } - /* * View */ -$form = new Form($db); -$formaccounting = new FormAccounting($db); +$help_url = 'EN:Module_Double_Entry_Accounting#Setup|FR:Module_Comptabilité_en_Partie_Double#Configuration'; +llxHeader('', $langs->trans("AccountingCategory"), $help_url, '', 0, 0, '', '', '', 'mod-accountancy page-admin-categories'); -$title = $langs->trans('AccountingCategory'); -$help_url = 'EN:Module_Double_Entry_Accounting#Setup|FR:Module_Comptabilité_en_Partie_Double#Configuration'; +if ($useNewSystem) { + // ============================================================================ + // NEW SYSTEM VIEW + // ============================================================================ -llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-accountancy page-admin_categories'); - -$linkback = ''.$langs->trans("BackToList").''; -$titlepicto = 'setup'; - -print load_fiche_titre($langs->trans('AccountingCategory'), $linkback, $titlepicto); - -print '
'."\n"; -print ''; -print ''; - -print dol_get_fiche_head(); - -print ''; - -// Select the category -print ''; -print ''; - -print '
'.$langs->trans("AccountingCategory").''; -$s = $formaccounting->select_accounting_category((int) $cat_id, 'account_category', 1, 0, 0, 0); -if ($formaccounting->nbaccounts_category <= 0) { - print ''.$s.''; -} else { - print $s; - print ''; -} -print '
'; - -print dol_get_fiche_end(); - - -// Select the accounts -if (!empty($cat_id)) { - $return = $accountingcategory->getAccountsWithNoCategory($cat_id); - if ($return < 0) { - setEventMessages(null, $accountingcategory->errors, 'errors'); - } - print '
'; - - $arraykeyvalue = array(); - foreach ($accountingcategory->lines_cptbk as $key => $val) { - $doc_ref = !empty($val->doc_ref) ? $val->doc_ref : ''; - $arraykeyvalue[length_accountg($val->numero_compte)] = length_accountg($val->numero_compte) . ' - ' . $val->label_compte . ($doc_ref ? ' '.$doc_ref : ''); + // Confirmation dialogs + if ($action == 'delete') { + print $form->formconfirm( + $_SERVER["PHP_SELF"].'?id='.$id.'&account_id='.$account_id, + $langs->trans('RemoveAccountFromCategory'), + $langs->trans('ConfirmRemoveAccountFromCategory'), + 'confirm_delete', + '', + 0, + 1 + ); } - if (is_array($accountingcategory->lines_cptbk) && count($accountingcategory->lines_cptbk) > 0) { - print img_picto($langs->trans("AccountingAccount"), 'accounting_account', 'class="pictofixedwidth"'); - print $form->multiselectarray('cpt_bk', $arraykeyvalue, GETPOST('cpt_bk', 'array'), 0, 0, '', 0, "80%", '', '', $langs->transnoentitiesnoconv("AddAccountFromBookKeepingWithNoCategories")); - print ' '; + if ($action == 'remove_all') { + print $form->formconfirm( + $_SERVER["PHP_SELF"].'?id='.$id, + $langs->trans('RemoveAllAccountsFromCategory'), + $langs->trans('ConfirmRemoveAllAccountsFromCategory'), + 'confirm_remove_all', + '', + 0, + 1 + ); } -} -print '
'; + // Page title + $title = $langs->trans("AccountingCategory").': '.$accountingcategory->label; + print load_fiche_titre($title, '', 'title_accountancy'); + // Category information card + print dol_get_fiche_head(); -if ((empty($action) || $action == 'display' || $action == 'delete') && $cat_id > 0) { - $param = 'account_category='.((int) $cat_id); + print ''; + print ''; + print ''; + if (!empty($accountingcategory->range_account)) { + print ''; + } + print ''; + print '
'.$langs->trans("Code").''.$accountingcategory->code.'
'.$langs->trans("Label").''.$accountingcategory->label.'
'.$langs->trans("Comment").''.$accountingcategory->range_account.'
'.$langs->trans("AccountsLinked").''.$accountingcategory->countAccountsInCategory().'
'; - print '
'; - print ''."\n"; + print dol_get_fiche_end(); + + // Build SQL for linked accounts + $sql = "SELECT aa.rowid, aa.account_number, aa.label"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account as aca"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = aca.fk_accounting_account"; + $sql .= " WHERE aca.fk_accounting_category = ".((int) $id); + $sql .= " AND aa.entity = ".$conf->entity; + + // Search filters + if (!empty($search_account)) { + $sql .= natural_search("aa.account_number", $search_account); + } + if (!empty($search_label)) { + $sql .= natural_search("aa.label", $search_label); + } + + // Count total + $nbtotalofrecords = ''; + if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + if (($page * $limit) > $nbtotalofrecords) { + $page = 0; + $offset = 0; + } + } + + // Add sort and limit + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit + 1, $offset); + + $resql = $db->query($sql); + if (!$resql) { + dol_print_error($db); + exit; + } + + $num = $db->num_rows($resql); + + // Parameters + $param = '&id='.$id; + if (!empty($search_account)) { + $param .= '&search_account='.urlencode($search_account); + } + if (!empty($search_label)) { + $param .= '&search_label='.urlencode($search_label); + } + + // Form to add accounts + print ''; + print ''; + print ''; + print ''; + + // Get available accounts + $availableAccounts = $accountingcategory->getAvailableAccountsForCategory(); + + if (count($availableAccounts) > 0) { + print '
'; + print ''; + print '
'.$langs->trans("AddAccountsToCategory").": ".''; + + // Prepare array for multiselectarray + $arrayofaccounts = array(); + foreach ($availableAccounts as $account) { + $arrayofaccounts[$account['id']] = $account['account_number'].' - '.$account['label']; + } + + // Use Dolibarr native multiselect with search + print $form->multiselectarray('accounts_to_add', $arrayofaccounts, array(), 0, 0, '', 0, '100%', '', '', $langs->trans("SelectAccountsToAdd")); + + print '
'; + + print '
'; + print ''; + print '   '; + print ''; + print '
'; + } else { + print '
'.$langs->trans("AllAccountsAlreadyLinked").'
'; + } + + print ''; + + // List of linked accounts + print '
'; + print ''; + print ''; + print ''; + print ''; + + $massactionbutton = ''; + $title = $langs->trans("AccountsLinked"); + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'accountancy', 0, '', '', $limit); + print '
'; + print ''; + + // Search filters row print ''; - print getTitleFieldOfList('AccountAccounting', 0, $_SERVER['PHP_SELF'], 'account_number', '', $param, '', $sortfield, $sortorder, '')."\n"; - print getTitleFieldOfList('Label', 0, $_SERVER['PHP_SELF'], 'label', '', $param, '', $sortfield, $sortorder, '')."\n"; - print getTitleFieldOfList('', 0, $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, '')."\n"; - print ''."\n"; + print ''; + print ''; + print ''; + print ''; - if (!empty($cat_id)) { - $return = $accountingcategory->display($cat_id); // This load ->lines_display - if ($return < 0) { - setEventMessages(null, $accountingcategory->errors, 'errors'); - } + // Header row + print ''; + print_liste_field_titre("AccountNumber", $_SERVER["PHP_SELF"], "aa.account_number", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "aa.label", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'center '); + print ''; - if (is_array($accountingcategory->lines_display) && count($accountingcategory->lines_display) > 0) { - $accountingcategory->lines_display = dol_sort_array($accountingcategory->lines_display, $sortfield, $sortorder, -1, 0, 1); + // Data rows + $i = 0; + while ($i < min($num, $limit)) { + $obj = $db->fetch_object($resql); - foreach ($accountingcategory->lines_display as $cpt) { - print ''; - print ''; - print ''; - print '"; - print "\n"; - } - } else { - print ''; - } + print ''; + + // Account number + print ''; + + // Label + print ''; + + // Actions + print ''; + + print ''; + $i++; } - print "
'; + $searchpicto = $form->showFilterAndCheckAddButtons(0); + print $searchpicto; + print '
'.length_accountg($cpt->account_number).''.$cpt->label.''; - print ''; - print $langs->trans("DeleteFromCat"); - print img_picto($langs->trans("DeleteFromCat"), 'unlink', 'class="paddingleft"'); - print ""; - print "
'.$langs->trans("NoRecordFound").'
'; + print ''; + print $obj->account_number; + print ''; + print ''; + print dol_escape_htmltag($obj->label); + print ''; + print 'rowid.'" class="reposition">'; + print img_delete(); + print ''; + print '
"; + if ($num == 0) { + print ''.$langs->trans("NoAccountLinked").''; + } + + print ''; + print '
'; + print '
'; + + // Button to remove all + if ($num > 0) { + print ''; + } +} else { + // ============================================================================ + // OLD SYSTEM VIEW (compatibility) + // ============================================================================ + + $listcpt = $accountingcategory->display($id); + $listcptNotIn = $accountingcategory->getAccountsWithNoCategory($id); + + print load_fiche_titre($langs->trans('AccountingCategory')." : ".$accountingcategory->label); + + print '
'; + print ''; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + if (is_array($listcpt) && count($listcpt) > 0) { + foreach ($listcpt as $cpt) { + print ''; + print ''; + print ''; + print '"; + print "\n"; + } + } else { + print ''; + } + + print '
'.$langs->trans("AccountNumber").''.$langs->trans("Label").'
'.length_accountg($cpt->account_number).''.$cpt->label.''; + print ''; + print img_picto($langs->trans("DeleteFromCat"), 'unlink', 'class="paddingleft"'); + print "
'.$langs->trans("NoRecordFound").'
'; + print '
'; } // End of page diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index feff44e92d2..6fc3be1f054 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -1,6 +1,6 @@ - * Copyright (C) 2011-2025 Alexandre Spangaro + * Copyright (C) 2011-2026 Alexandre Spangaro * Copyright (C) 2024-2026 Frédéric France * Copyright (C) 2024-2026 MDW * @@ -26,14 +26,6 @@ // Load Dolibarr environment require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; /** * @var Conf $conf @@ -43,6 +35,16 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php * @var User $user */ +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyreport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; + // Load translation files required by the page $langs->loadLangs(array("errors", "admin", "companies", "resource", "holiday", "accountancy", "hrm")); @@ -70,7 +72,7 @@ $listlimit = GETPOSTINT('listlimit') > 0 ? GETPOSTINT('listlimit') : 1000; $sortfield = (string) GETPOST("sortfield", 'aZ09comma'); $sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page"); -if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { +if (empty($page) || $page < 0 || GETPOST('button_refresh', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // If $page is not defined, or '' or -1 or if we click on clear filters $page = 0; } @@ -80,6 +82,22 @@ $pagenext = $page + 1; $search_country_id = GETPOST('search_country_id', 'int'); +// Report filter (Multi report) +$search_report = GETPOSTINT('search_report'); +if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + if (empty($search_report)) { + // Try to get from session + if (!empty($_SESSION['accounting_category_report_filter'])) { + $search_report = $_SESSION['accounting_category_report_filter']; + } else { + $search_report = 1; // Default report + } + } else { + // Save in session + $_SESSION['accounting_category_report_filter'] = $search_report; + } +} + // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context $hookmanager->initHooks(array('admin')); @@ -99,7 +117,7 @@ $tablib[32] = "DictionaryAccountancyCategory"; // Requests to extract data $tabsql = array(); -$tabsql[32] = "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid AND c.active=1 AND a.entity IN (".getEntity('c_accounting_category').")"; +$tabsql[32] = "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.category_type, a.formula, a.position as position, a.fk_report, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid AND c.active=1 AND a.entity IN (".getEntity('c_accounting_category').")"; // Criteria to sort dictionaries $tabsqlsort = array(); @@ -147,6 +165,12 @@ $accountingcategory = new AccountancyCategory($db); if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) { $search_country_id = ''; + + // Reset report filter + if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + $search_report = 1; + $_SESSION['accounting_category_report_filter'] = 1; + } } // Actions add or modify an entry into a dictionary @@ -426,6 +450,71 @@ print load_fiche_titre($titre, $linkback, $titlepicto); print ''.$langs->trans("AccountingAccountGroupsDesc", $langs->transnoentitiesnoconv("ByPersonalizedAccountGroups")).'

'; +// Report selector (New System) +if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + print '
'; + + print '
'; + print ''; + print ''; + print ''; + + print '
'; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + print '
'.$langs->trans("Report").'
'; + + // Get list of reports + $reports_list = array(); + + $sql_reports = "SELECT r.rowid, r.code, r.label"; + $sql_reports .= " FROM ".MAIN_DB_PREFIX."c_accounting_report as r"; + $sql_reports .= " WHERE r.active = 1"; + $sql_reports .= " ORDER BY r.code ASC"; + + $resql_reports = $db->query($sql_reports); + if ($resql_reports) { + $num_reports = $db->num_rows($resql_reports); + $i_report = 0; + while ($i_report < $num_reports) { + $obj_report = $db->fetch_object($resql_reports); + $reports_list[$obj_report->rowid] = $obj_report->label.' ('.$obj_report->code.')'; + $i_report++; + } + $db->free($resql_reports); + } + + if (empty($reports_list)) { + $reports_list[1] = $langs->trans("ReportPersonalized"); + } + + // Display select with auto-submit + print ''; + + print ' '; + print ''; + + print '
'; + + print '
'; + + print '
'; + + print '
'; + print '
'; +} + // Confirmation of the deletion of the line if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id.($search_country_id > 0 ? '&search_country_id='.$search_country_id : ''), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); @@ -443,6 +532,15 @@ if ($search_country_id > 0) { $sql .= " (a.fk_country = ".((int) $search_country_id)." OR a.fk_country = 0)"; } +if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT') && $search_report > 0) { + if (preg_match('/ WHERE /', $sql)) { + $sql .= " AND "; + } else { + $sql .= " WHERE "; + } + $sql .= " a.fk_report = ".((int) $search_report); +} + // If sort order is "country", we use country_code instead if ($sortfield == 'country') { $sortfield = 'country_code'; @@ -461,6 +559,9 @@ $param = '&id='.$id; if ($search_country_id > 0) { $param .= '&search_country_id='.urlencode((string) ($search_country_id)); } +if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT') && $search_report > 0) { + $param .= '&search_report='.urlencode((string) ($search_report)); +} $paramwithsearch = $param; if ($sortorder) { $paramwithsearch .= '&sortorder='.urlencode($sortorder); @@ -889,11 +990,18 @@ if ($resql) { print ''; if (empty($obj->formula)) { // Count number of accounts into group - $nbofaccountintogroup = 0; - $listofaccountintogroup = $accountingcategory->getCptsCat($obj->rowid); - $nbofaccountintogroup = count($listofaccountintogroup); + if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + // NEW SYSTEM: Multi report + $accountingcategory_temp = new AccountancyCategory($db); + $accountingcategory_temp->id = $obj->rowid; + $nbofaccountintogroup = $accountingcategory_temp->countAccountsInCategory(); + } else { + // OLD SYSTEM: Only one report + $listofaccountintogroup = $accountingcategory->getCptsCat($obj->rowid); + $nbofaccountintogroup = count($listofaccountintogroup); + } - print ''; + print ''; print $langs->trans("NAccounts", $nbofaccountintogroup); print ''; } else { @@ -902,7 +1010,7 @@ if ($resql) { print ''; // Active - print ''; + print ''; if ($canbedisabled) { print ''.$actl[$obj->active].''; } else { diff --git a/htdocs/accountancy/class/accountancycategory.class.php b/htdocs/accountancy/class/accountancycategory.class.php index dcfdbd16518..4931bcbad02 100644 --- a/htdocs/accountancy/class/accountancycategory.class.php +++ b/htdocs/accountancy/class/accountancycategory.class.php @@ -1,8 +1,8 @@ - * Copyright (C) 2016-2025 Alexandre Spangaro - * Copyright (C) 2018-2025 Frédéric France - * Copyright (C) 2024-2025 MDW +/* Copyright (C) 2016 Jamal Elbaz + * Copyright (C) 2016-2026 Alexandre Spangaro + * Copyright (C) 2018-2025 Frédéric France + * Copyright (C) 2024-2025 MDW * * 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 @@ -906,4 +906,326 @@ class AccountancyCategory // extends CommonObject return -1; } } + + + // ==================================================================== + // MULTI REPORT METHODS (New system with llx_accounting_category_account) + // Requires constant ACCOUNTING_ENABLE_MULTI_REPORT + // ==================================================================== + + /** + * Link an accounting account to this category (multi-report system) + * + * @param int $fkAccountingAccount ID of the accounting account to link + * @return int<-1,1> <0 if KO, 0 if already exists, >0 if OK + */ + public function addAccountToCategory($fkAccountingAccount) + { + // Check if relation already exists + if ($this->isAccountInCategory($fkAccountingAccount)) { + return 0; + } + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " (fk_accounting_category, fk_accounting_account)"; + $sql .= " VALUES (".((int) $this->id).", ".((int) $fkAccountingAccount).")"; + + dol_syslog(get_class($this)."::addAccountToCategory", LOG_DEBUG); + + $this->db->begin(); + + $resql = $this->db->query($sql); + if ($resql) { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + return -1; + } + } + + /** + * Unlink an accounting account from this category (multi-report system) + * + * @param int $fkAccountingAccount ID of the accounting account to unlink + * @return int<-1,1> <0 if KO, >0 if OK + */ + public function deleteAccountFromCategory($fkAccountingAccount) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " WHERE fk_accounting_category = ".((int) $this->id); + $sql .= " AND fk_accounting_account = ".((int) $fkAccountingAccount); + + dol_syslog(get_class($this)."::deleteAccountFromCategory", LOG_DEBUG); + + $this->db->begin(); + + $resql = $this->db->query($sql); + if ($resql) { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + return -1; + } + } + + /** + * Get all accounting accounts linked to this category (multi-report system) + * + * @return array Array of accounting accounts indexed by account ID, or empty array if error + */ + public function getAccountsForCategory() + { + global $conf; + + $accounts = array(); + + $sql = "SELECT aca.fk_accounting_account, aa.account_number, aa.label"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account as aca"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = aca.fk_accounting_account"; + $sql .= " WHERE aca.fk_accounting_category = ".((int) $this->id); + $sql .= " AND aa.entity = ".$conf->entity; + $sql .= " ORDER BY aa.account_number ASC"; + + dol_syslog(get_class($this)."::getAccountsForCategory", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $accounts[$obj->fk_accounting_account] = array( + 'id' => $obj->fk_accounting_account, + 'account_number' => $obj->account_number, + 'label' => $obj->label + ); + $i++; + } + $this->db->free($resql); + return $accounts; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + dol_syslog(get_class($this)."::getAccountsForCategory ".$this->error, LOG_ERR); + return array(); + } + } + + /** + * Get categories for a specific accounting account (multi-report system) + * + * @param int $fkAccountingAccount ID of the accounting account + * @return array Array of categories indexed by category ID, or empty array if error + */ + public function getCategoriesForAccount($fkAccountingAccount) + { + global $conf; + + $categories = array(); + + $sql = "SELECT aca.fk_accounting_category, ac.code, ac.label, ac.fk_report"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account as aca"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_accounting_category as ac ON ac.rowid = aca.fk_accounting_category"; + $sql .= " WHERE aca.fk_accounting_account = ".((int) $fkAccountingAccount); + $sql .= " AND ac.entity = ".$conf->entity; + $sql .= " ORDER BY ac.position ASC"; + + dol_syslog(get_class($this)."::getCategoriesForAccount", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $categories[$obj->fk_accounting_category] = array( + 'id' => $obj->fk_accounting_category, + 'code' => $obj->code, + 'label' => $obj->label, + 'fk_report' => $obj->fk_report + ); + $i++; + } + $this->db->free($resql); + return $categories; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + dol_syslog(get_class($this)."::getCategoriesForAccount ".$this->error, LOG_ERR); + return array(); + } + } + + /** + * Check if an account belongs to this category (multi-report system) + * + * @param int $fkAccountingAccount ID of the accounting account + * @return bool True if account is in category, false otherwise + */ + public function isAccountInCategory($fkAccountingAccount) + { + $sql = "SELECT COUNT(*) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " WHERE fk_accounting_category = ".((int) $this->id); + $sql .= " AND fk_accounting_account = ".((int) $fkAccountingAccount); + + dol_syslog(get_class($this)."::isAccountInCategory", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return ($obj->nb > 0); + } + return false; + } + + /** + * Get all accounting accounts NOT linked to this category (for selection) + * + * @return array Array of available accounts, or empty array if error + */ + public function getAvailableAccountsForCategory() + { + global $conf; + + $accounts = array(); + + $pcgverid = getDolGlobalInt('CHARTOFACCOUNTS'); + $pcgvercode = dol_getIdFromCode($this->db, (string) $pcgverid, 'accounting_system', 'rowid', 'pcg_version'); + if (empty($pcgvercode)) { + $pcgvercode = $pcgverid; + } + + $sql = "SELECT aa.rowid, aa.account_number, aa.label"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; + $sql .= " WHERE aa.rowid NOT IN ("; + $sql .= " SELECT fk_accounting_account"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " WHERE fk_accounting_category = ".((int) $this->id); + $sql .= " )"; + $sql .= " AND aa.entity = ".$conf->entity; + $sql .= " AND aa.active = 1"; + $sql .= " AND aa.fk_pcg_version = '".$this->db->escape($pcgvercode)."'"; + $sql .= " ORDER BY aa.account_number ASC"; + + dol_syslog(get_class($this)."::getAvailableAccountsForCategory", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $accounts[$obj->rowid] = array( + 'id' => $obj->rowid, + 'account_number' => $obj->account_number, + 'label' => $obj->label + ); + $i++; + } + $this->db->free($resql); + return $accounts; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + dol_syslog(get_class($this)."::getAvailableAccountsForCategory ".$this->error, LOG_ERR); + return array(); + } + } + + /** + * Add multiple accounts to this category at once + * + * @param array $accountIds Array of accounting account IDs + * @return int<-1,max> Number of accounts added, -1 if error + */ + public function addMultipleAccountsToCategory(array $accountIds) + { + $added = 0; + $error = 0; + + $this->db->begin(); + + foreach ($accountIds as $accountId) { + if (!$this->isAccountInCategory($accountId)) { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " (fk_accounting_category, fk_accounting_account)"; + $sql .= " VALUES (".((int) $this->id).", ".((int) $accountId).")"; + + $resql = $this->db->query($sql); + if ($resql) { + $added++; + } else { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + } + } + + if ($error) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return $added; + } + } + + /** + * Remove all accounts from this category + * + * @return int<-1,max> Number of deleted relations if OK, -1 if error + */ + public function removeAllAccountsFromCategory() + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " WHERE fk_accounting_category = ".((int) $this->id); + + dol_syslog(get_class($this)."::removeAllAccountsFromCategory", LOG_DEBUG); + + $this->db->begin(); + + $resql = $this->db->query($sql); + if ($resql) { + $affected = $this->db->affected_rows($resql); + $this->db->commit(); + return $affected; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + return -1; + } + } + + /** + * Count number of accounts linked to this category + * + * @return int Number of accounts, <0 if error + */ + public function countAccountsInCategory() + { + $sql = "SELECT COUNT(*) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_category_account"; + $sql .= " WHERE fk_accounting_category = ".((int) $this->id); + + dol_syslog(get_class($this)."::countAccountsInCategory", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return (int) $obj->nb; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; + } + } } diff --git a/htdocs/accountancy/class/accountancyreport.class.php b/htdocs/accountancy/class/accountancyreport.class.php index 69f1dda8a0e..9d9b8b3701b 100644 --- a/htdocs/accountancy/class/accountancyreport.class.php +++ b/htdocs/accountancy/class/accountancyreport.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2024-2026 Alexandre Spangaro * Copyright (C) 2025 Frédéric France * * This program is free software; you can redistribute it and/or modify diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index 3701b84b757..529e081e4ae 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -300,7 +300,7 @@ 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', 2465__+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, 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"', __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', 2470__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_report_group', 2451__+MAX_llx_menu__, '/accountancy/admin/report_list.php?id=45&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingReport', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 75, __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" && getDolGlobalInt("ACCOUNTING_ENABLE_MULTI_REPORT")', __HANDLER__, 'left', 2470__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_report_group', 2451__+MAX_llx_menu__, '/accountancy/admin/report_list.php?id=45&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingReport', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 75, __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', 2471__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart_group', 2451__+MAX_llx_menu__, '/accountancy/admin/categories_list.php?id=32&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingCategory', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 80, __ENTITY__); -- Binding diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 4c06713d889..430b0152550 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1764,10 +1764,10 @@ 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/template/list.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuListBookkeepingTemplates"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_template', 110); - $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_product', 120); - $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 130); - if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) { - $newmenu->add("/accountancy/admin/report_list.php?id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingReport"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_report', 140); + $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_product', 110); + $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 120); + if (getDolGlobalInt('ACCOUNTING_ENABLE_MULTI_REPORT')) { + $newmenu->add("/accountancy/admin/report_list.php?id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingReport"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_report', 125); } $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', 145); } diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index eb8ddebcdf4..50bb879da49 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -339,6 +339,24 @@ BindingOptions=Options for the transfer in accountancy ApplyMassCategories=Apply mass categories AddAccountFromBookKeepingWithNoCategories=Available account not yet in the personalized group CategoryDeleted=Category for the accounting account has been removed +ManageAccountsForCategory=Manage accounts for category +AccountsLinked=Linked accounts +AccountAddedToCategory=Account added to category +AccountAlreadyInCategory=Account already in this category +AccountRemovedFromCategory=Account removed from category +RemoveAccountFromCategory=Remove account from category +ConfirmRemoveAccountFromCategory=Are you sure you want to remove this account from this category? +RemoveAllAccountsFromCategory=Remove all accounts +ConfirmRemoveAllAccountsFromCategory=Are you sure you want to remove all accounts from this category? +XAccountsAdded=%s account(s) added +XAccountsRemoved=%s account(s) removed +NoAccountAdded=No account added +NoAccountLinked=No linked account +AddAccountsToCategory=Add accounts to category +SelectAccountsToAdd=Select the accounts to add to this category +AllAccountsAlreadyLinked=All accounts are already linked to this category +ReportPersonalized=Personalized report +AccountingCategoriesFilteredByReport=Accounting categories displayed are filtered by the selected report AccountingJournals=Accounting journals AccountingJournal=Accounting journal NewAccountingJournal=New accounting journal